feat(privacy): complete the publication, hiding and preview settings screen
This commit is contained in:
1 parent
c2a8d17195
commit
5edff21d2d
28 files changed
+2230
-428
No files matched your search
@@ -1,6 +1,11 @@
|
||||
export {
|
||||
cardAccessLabels,
|
||||
cardFieldLabels,
|
||||
contactAccessAfterVisibilityChange,
|
||||
describeAccessOrganization,
|
||||
describePublicationClosure,
|
||||
evidenceBasisLabels,
|
||||
evidenceCalibrationLabels,
|
||||
buildSearchStatusSubmission,
|
||||
buildPublicationSubmission,
|
||||
currentC2State,
|
||||
@@ -16,9 +21,13 @@ export {
|
||||
specializationLabels,
|
||||
} from "./model/presentation";
|
||||
export { candidateViewQueryKeys } from "./model/query-keys";
|
||||
export { EmployerCardPreview } from "./ui/employer-card-preview";
|
||||
export type {
|
||||
C2State,
|
||||
CandidateViewPresentation,
|
||||
EvidencePresentation,
|
||||
PublicationClosureNotice,
|
||||
SelfAssessmentPresentation,
|
||||
PublicationDraft,
|
||||
PublicationSubmission,
|
||||
PublishableCardField,
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CardField, CardPreview } from "../../../shared/api/schemas";
|
||||
import { editableCardFields, presentCandidatePreview, publishableCardFields } from "./presentation";
|
||||
import {
|
||||
contactAccessAfterVisibilityChange,
|
||||
describeAccessOrganization,
|
||||
describePublicationClosure,
|
||||
editableCardFields,
|
||||
presentCandidatePreview,
|
||||
publishableCardFields,
|
||||
} from "./presentation";
|
||||
|
||||
function preview(card: NonNullable<CardPreview["card"]>): CardPreview {
|
||||
return {
|
||||
@@ -43,11 +50,99 @@ describe("candidate card presentation", () => {
|
||||
{
|
||||
specialization: "Сетевое администрирование",
|
||||
declaredGrade: "Middle",
|
||||
confirmed: false,
|
||||
confirmation: "Грейд не подтвержден",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("states the confirmation of every specialization on its own", () => {
|
||||
const result = presentCandidatePreview(
|
||||
preview({
|
||||
pseudonym: `cv1_${"b".repeat(43)}`,
|
||||
categories: [{ specialization: "backend", grade: "middle", strength: "strong" }],
|
||||
stack: null,
|
||||
self_assessment: [
|
||||
{ specialization: "backend", confirmation_status: "confirmed", declared_grade: "middle" },
|
||||
{
|
||||
specialization: "network_engineer",
|
||||
confirmation_status: "unconfirmed",
|
||||
declared_grade: "junior",
|
||||
},
|
||||
{ specialization: "qa", confirmation_status: "unconfirmed", declared_grade: null },
|
||||
],
|
||||
experience_band: null,
|
||||
work_formats: null,
|
||||
salary_compatibility: null,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
result?.selfAssessments?.map((item) => [
|
||||
item.specialization,
|
||||
item.confirmed,
|
||||
item.confirmation,
|
||||
]),
|
||||
).toEqual([
|
||||
["Backend", true, "Грейд подтвержден"],
|
||||
["Сетевое администрирование", false, "Грейд не подтвержден"],
|
||||
["Тестирование", false, "Грейд не подтвержден"],
|
||||
]);
|
||||
expect(result?.selfAssessments?.[2]?.declaredGrade).toBeNull();
|
||||
});
|
||||
|
||||
it("restates the evidence basis and calibration the server reports", () => {
|
||||
const result = presentCandidatePreview({
|
||||
...preview({
|
||||
pseudonym: `cv1_${"c".repeat(43)}`,
|
||||
categories: [{ specialization: "backend", grade: "middle", strength: "standard" }],
|
||||
stack: null,
|
||||
self_assessment: null,
|
||||
experience_band: null,
|
||||
work_formats: null,
|
||||
salary_compatibility: null,
|
||||
}),
|
||||
evidence: {
|
||||
items: [
|
||||
{
|
||||
skill: "backend",
|
||||
grade: "middle",
|
||||
trust: 1,
|
||||
basis: "synthetic_demo",
|
||||
calibration_status: "uncalibrated",
|
||||
observed_year: 2026,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(result?.evidence).toEqual([
|
||||
{
|
||||
title: "Backend: Middle",
|
||||
trust: "partial",
|
||||
trustLabel: "Онлайн-результат без подтверждения личности",
|
||||
observedYear: 2026,
|
||||
basisLabel: "Синтетическая демонстрация, не проверенное измерение",
|
||||
calibrationLabel: "Пороги не откалиброваны",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps an empty evidence list apart from a closed card", () => {
|
||||
const published = presentCandidatePreview(
|
||||
preview({
|
||||
pseudonym: `cv1_${"d".repeat(43)}`,
|
||||
categories: null,
|
||||
stack: null,
|
||||
self_assessment: null,
|
||||
experience_band: null,
|
||||
work_formats: null,
|
||||
salary_compatibility: null,
|
||||
}),
|
||||
);
|
||||
expect(published?.evidence).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not present a closed preview as an empty published card", () => {
|
||||
expect(
|
||||
presentCandidatePreview({
|
||||
@@ -82,3 +177,42 @@ describe("editable card fields", () => {
|
||||
expect(editableCardFields(stored)).toEqual(["categories", "work_formats"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("publication closure explanation", () => {
|
||||
it("explains a revoked C2 as closed future reads and a new C4 for a former company", () => {
|
||||
const notice = describePublicationClosure({
|
||||
state: "closed",
|
||||
closed_reason: "consent_revoked",
|
||||
});
|
||||
const text = [notice?.title, ...(notice?.points ?? [])].join(" ");
|
||||
|
||||
expect(text).toContain("Будущие чтения карточки компаниями закрыты");
|
||||
expect(text).toContain("Новое согласие C2 не откроет карточку само");
|
||||
expect(text).toContain("новое приглашение и новое согласие C4");
|
||||
});
|
||||
|
||||
it("explains a closing by the candidate and says nothing about a published or new card", () => {
|
||||
expect(
|
||||
describePublicationClosure({
|
||||
state: "closed",
|
||||
closed_reason: "closed_by_candidate",
|
||||
})?.points.join(" "),
|
||||
).toContain("не восстанавливает прежний доступ к контактам");
|
||||
expect(describePublicationClosure({ state: "published", closed_reason: null })).toBeNull();
|
||||
expect(
|
||||
describePublicationClosure({ state: "closed", closed_reason: "never_published" }),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("never promises that an unhide or a republish restores a contact grant", () => {
|
||||
expect(contactAccessAfterVisibilityChange).toContain("не восстанавливают прежний доступ");
|
||||
expect(contactAccessAfterVisibilityChange).toContain("новое согласие C4");
|
||||
});
|
||||
});
|
||||
|
||||
describe("card access organization", () => {
|
||||
it("does not invent a name for an organization the server cannot present", () => {
|
||||
expect(describeAccessOrganization(null)).toBe("Организация не раскрывается");
|
||||
expect(describeAccessOrganization({ name: "Компания А" })).toBe("Компания А");
|
||||
});
|
||||
});
|
||||
@@ -5,14 +5,20 @@ import type {
|
||||
CardPreview,
|
||||
CardSelfAssessment,
|
||||
CandidateExperienceBand,
|
||||
EvidenceBasis,
|
||||
EvidenceCalibrationStatus,
|
||||
EvidenceSkillCode,
|
||||
CandidateSalaryCompatibility,
|
||||
CandidateWorkFormat,
|
||||
ConsentRecord,
|
||||
HiddenOrganization,
|
||||
OrganizationEvidenceFact,
|
||||
PrivacySettings,
|
||||
Publication,
|
||||
PublicationUpdate,
|
||||
SearchStatusUpdate,
|
||||
} from "../../../shared/api/schemas";
|
||||
import type { TrustLevelValue } from "../../../shared/ui";
|
||||
|
||||
export const publishableCardFields = [
|
||||
"categories",
|
||||
@@ -196,9 +202,21 @@ export type CategoryPresentation = {
|
||||
export type SelfAssessmentPresentation = {
|
||||
specialization: string;
|
||||
declaredGrade: string | null;
|
||||
/** True only when the server says this specialization has a confirmed grade. */
|
||||
confirmed: boolean;
|
||||
confirmation: string;
|
||||
};
|
||||
|
||||
export type EvidencePresentation = {
|
||||
/** Skill and passed grade, for example "Backend: Middle". */
|
||||
title: string;
|
||||
trust: TrustLevelValue;
|
||||
trustLabel: string;
|
||||
observedYear: number;
|
||||
basisLabel: string;
|
||||
calibrationLabel: string;
|
||||
};
|
||||
|
||||
export type CandidateViewPresentation = {
|
||||
pseudonym: string;
|
||||
categories: readonly CategoryPresentation[] | null;
|
||||
@@ -207,6 +225,11 @@ export type CandidateViewPresentation = {
|
||||
experience: string | null;
|
||||
workFormats: readonly string[] | null;
|
||||
salaryCompatibility: string | null;
|
||||
/**
|
||||
* Supporting assessment facts as an organization reads them. Null while the
|
||||
* card is closed; an empty list when no visible fact supports a category.
|
||||
*/
|
||||
evidence: readonly EvidencePresentation[] | null;
|
||||
};
|
||||
|
||||
function categoryPresentation(category: CardCategory): CategoryPresentation {
|
||||
@@ -222,11 +245,53 @@ function selfAssessmentPresentation(item: CardSelfAssessment): SelfAssessmentPre
|
||||
return {
|
||||
specialization: specializationLabels[item.specialization],
|
||||
declaredGrade: item.declared_grade ? gradeLabels[item.declared_grade] : null,
|
||||
confirmed: item.confirmation_status === "confirmed",
|
||||
confirmation:
|
||||
item.confirmation_status === "confirmed" ? "Грейд подтвержден" : "Грейд не подтвержден",
|
||||
};
|
||||
}
|
||||
|
||||
const evidenceSkillLabels: Readonly<Record<EvidenceSkillCode, string>> = {
|
||||
...specializationLabels,
|
||||
...stackLabels,
|
||||
};
|
||||
|
||||
// The shape of a mark follows the strength of the confirmation, and the label
|
||||
// always names the exact meaning of the level so it never depends on the shape.
|
||||
type EvidenceTrustView = { level: TrustLevelValue; label: string };
|
||||
|
||||
const claimedEvidence: EvidenceTrustView = {
|
||||
level: "claimed",
|
||||
label: "Заявлено, не подтверждено отдельно",
|
||||
};
|
||||
|
||||
const evidenceTrust: Readonly<Record<number, EvidenceTrustView>> = {
|
||||
0: claimedEvidence,
|
||||
1: { level: "partial", label: "Онлайн-результат без подтверждения личности" },
|
||||
2: { level: "confirmed", label: "Результат привязан к подтвержденной личности" },
|
||||
3: { level: "confirmed", label: "Очная проверка" },
|
||||
};
|
||||
|
||||
export const evidenceBasisLabels: Readonly<Record<EvidenceBasis, string>> = {
|
||||
synthetic_demo: "Синтетическая демонстрация, не проверенное измерение",
|
||||
};
|
||||
|
||||
export const evidenceCalibrationLabels: Readonly<Record<EvidenceCalibrationStatus, string>> = {
|
||||
uncalibrated: "Пороги не откалиброваны",
|
||||
};
|
||||
|
||||
function evidencePresentation(fact: OrganizationEvidenceFact): EvidencePresentation {
|
||||
const trust = evidenceTrust[fact.trust] ?? claimedEvidence;
|
||||
return {
|
||||
title: `${evidenceSkillLabels[fact.skill]}: ${gradeLabels[fact.grade]}`,
|
||||
trust: trust.level,
|
||||
trustLabel: trust.label,
|
||||
observedYear: fact.observed_year,
|
||||
basisLabel: evidenceBasisLabels[fact.basis],
|
||||
calibrationLabel: evidenceCalibrationLabels[fact.calibration_status],
|
||||
};
|
||||
}
|
||||
|
||||
export function presentCandidatePreview(preview: CardPreview): CandidateViewPresentation | null {
|
||||
const card = preview.card;
|
||||
if (!card) return null;
|
||||
@@ -241,6 +306,7 @@ export function presentCandidatePreview(preview: CardPreview): CandidateViewPres
|
||||
salaryCompatibility: card.salary_compatibility
|
||||
? salaryCompatibilityLabels[card.salary_compatibility]
|
||||
: null,
|
||||
evidence: preview.evidence ? preview.evidence.items.map(evidencePresentation) : null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -269,3 +335,49 @@ export const cardAccessLabels = {
|
||||
card_viewed: "Просмотрена карточка профиля",
|
||||
contact_read: "Открыты контактные данные",
|
||||
} as const;
|
||||
|
||||
export type PublicationClosureNotice = {
|
||||
title: string;
|
||||
points: readonly string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Explains a closed card to its owner. The text restates the server reason and
|
||||
* the contract rules: a closed card is unreadable at once, and neither a new
|
||||
* C2 nor an unhide reopens an earlier contact grant. A former company reads
|
||||
* contacts again only after a new invitation and a new C4. The notice is
|
||||
* absent while the card is published and for a card that was never published.
|
||||
*/
|
||||
export function describePublicationClosure(
|
||||
publication: Pick<Publication, "state" | "closed_reason">,
|
||||
): PublicationClosureNotice | null {
|
||||
if (publication.state === "published") return null;
|
||||
if (publication.closed_reason === "consent_revoked") {
|
||||
return {
|
||||
title: "Согласие C2 отозвано, карточка закрыта",
|
||||
points: [
|
||||
"Будущие чтения карточки компаниями закрыты сразу, без ожидания обновления поиска.",
|
||||
"Новое согласие C2 не откроет карточку само: выберите поля и включите публикацию отдельным действием.",
|
||||
"Прежний доступ к контактам не возвращается. Компании, которая уже получала контакты, нужны новое приглашение и новое согласие C4.",
|
||||
],
|
||||
};
|
||||
}
|
||||
if (publication.closed_reason === "closed_by_candidate") {
|
||||
return {
|
||||
title: "Вы закрыли карточку",
|
||||
points: [
|
||||
"Будущие чтения карточки компаниями закрыты.",
|
||||
"Повторная публикация не восстанавливает прежний доступ к контактам: компании, которая уже получала контакты, нужны новое приглашение и новое согласие C4.",
|
||||
],
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Wording about contact access that follows a hide, an unhide or a republish. */
|
||||
export const contactAccessAfterVisibilityChange =
|
||||
"Скрытие закрывает будущие чтения этой компании. Снятие скрытия и повторная публикация не восстанавливают прежний доступ к контактам: бывшей компании нужны новое приглашение и новое согласие C4.";
|
||||
|
||||
export function describeAccessOrganization(organization: { name: string } | null): string {
|
||||
return organization ? organization.name : "Организация не раскрывается";
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
.preview {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.alias {
|
||||
margin: 0;
|
||||
font-size: 1.05rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.note,
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 0.925rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin-block-start: var(--space-3);
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.grid 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);
|
||||
}
|
||||
|
||||
.grid h3 {
|
||||
margin: 0 0 var(--space-3);
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.grid p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.grid .hint {
|
||||
margin-block-start: var(--space-3);
|
||||
}
|
||||
|
||||
.list {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
/* A declared grade and a confirmed grade differ by mark shape and text, not by color. */
|
||||
.assessment,
|
||||
.evidence {
|
||||
display: grid;
|
||||
gap: 0.3rem;
|
||||
min-width: 0;
|
||||
padding-block-end: var(--space-3);
|
||||
border-block-end: var(--line-thin) solid var(--color-divider);
|
||||
}
|
||||
|
||||
.list > li:last-child {
|
||||
padding-block-end: 0;
|
||||
border-block-end: 0;
|
||||
}
|
||||
|
||||
.assessment-name {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.declared {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.evidence-facts,
|
||||
.facts {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(7.5rem, auto) minmax(0, 1fr);
|
||||
gap: 0.35rem 1rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.evidence-facts dt,
|
||||
.facts dt {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.evidence-facts dd,
|
||||
.facts dd {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.facts {
|
||||
grid-template-columns: minmax(9rem, auto) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
@media (width < 48rem) {
|
||||
.grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.evidence-facts,
|
||||
.facts {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.evidence-facts dd + dt,
|
||||
.facts dd + dt {
|
||||
margin-block-start: 0.6rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { CardPreview } from "../../../shared/api/schemas";
|
||||
import { EmployerCardPreview } from "./employer-card-preview";
|
||||
|
||||
const pseudonym = `cv1_${"a".repeat(43)}`;
|
||||
|
||||
function published(overrides: Partial<CardPreview> = {}): CardPreview {
|
||||
return {
|
||||
state: "published",
|
||||
fields: ["categories", "self_assessment"],
|
||||
card: {
|
||||
pseudonym,
|
||||
categories: [{ specialization: "backend", grade: "middle", strength: "standard" }],
|
||||
stack: null,
|
||||
self_assessment: [
|
||||
{ specialization: "backend", confirmation_status: "confirmed", declared_grade: "middle" },
|
||||
{
|
||||
specialization: "network_engineer",
|
||||
confirmation_status: "unconfirmed",
|
||||
declared_grade: "junior",
|
||||
},
|
||||
{ specialization: "qa", confirmation_status: "unconfirmed", declared_grade: null },
|
||||
],
|
||||
experience_band: null,
|
||||
work_formats: null,
|
||||
salary_compatibility: null,
|
||||
},
|
||||
evidence: {
|
||||
items: [
|
||||
{
|
||||
skill: "backend",
|
||||
grade: "middle",
|
||||
trust: 1,
|
||||
basis: "synthetic_demo",
|
||||
calibration_status: "uncalibrated",
|
||||
observed_year: 2026,
|
||||
},
|
||||
],
|
||||
},
|
||||
generated_at: "2026-10-03T10:00:00Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function render(
|
||||
preview: CardPreview | undefined,
|
||||
extra: { isLoading?: boolean; error?: unknown } = {},
|
||||
) {
|
||||
return renderToStaticMarkup(
|
||||
<EmployerCardPreview
|
||||
preview={preview}
|
||||
isLoading={extra.isLoading ?? false}
|
||||
error={extra.error ?? null}
|
||||
onRetry={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("employer card preview", () => {
|
||||
it("keeps the owner alias apart from organization aliases", () => {
|
||||
const markup = render(published());
|
||||
|
||||
expect(markup).toContain("Предварительный псевдоним");
|
||||
expect(markup).toContain(pseudonym);
|
||||
expect(markup).toContain("Это отдельный псевдоним предпросмотра");
|
||||
});
|
||||
|
||||
it("states the confirmation of each specialization separately", () => {
|
||||
const markup = render(published());
|
||||
|
||||
expect(markup).toContain("Backend: Middle, стандартное подтверждение");
|
||||
expect(markup.match(/Грейд подтвержден/g)).toHaveLength(1);
|
||||
expect(markup.match(/Грейд не подтвержден/g)).toHaveLength(2);
|
||||
expect(markup).toContain("Заявлено: Junior");
|
||||
expect(markup).toContain("Уровень не указан");
|
||||
// The mark of a confirmed grade and the mark of an unconfirmed one differ in markup.
|
||||
expect(markup).toContain('data-level="confirmed"');
|
||||
expect(markup).toContain('data-level="none"');
|
||||
expect(markup).toContain("неудачные попытки компании не видят");
|
||||
});
|
||||
|
||||
it("shows the unconfirmed state per specialization when no category exists", () => {
|
||||
const markup = render(
|
||||
published({
|
||||
fields: ["self_assessment"],
|
||||
card: {
|
||||
pseudonym,
|
||||
categories: null,
|
||||
stack: null,
|
||||
self_assessment: [
|
||||
{
|
||||
specialization: "backend",
|
||||
confirmation_status: "unconfirmed",
|
||||
declared_grade: "middle",
|
||||
},
|
||||
{
|
||||
specialization: "network_engineer",
|
||||
confirmation_status: "unconfirmed",
|
||||
declared_grade: "junior",
|
||||
},
|
||||
],
|
||||
experience_band: null,
|
||||
work_formats: null,
|
||||
salary_compatibility: null,
|
||||
},
|
||||
evidence: { items: [] },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(markup).toContain("Подтвержденных категорий в карточке нет.");
|
||||
expect(markup.match(/Грейд не подтвержден/g)).toHaveLength(2);
|
||||
expect(markup).not.toContain("Грейд подтвержден");
|
||||
expect(markup).toContain("Для опубликованных категорий нет видимого подтверждающего факта.");
|
||||
});
|
||||
|
||||
it("labels the evidence basis and calibration the way the server states them", () => {
|
||||
const markup = render(published());
|
||||
|
||||
expect(markup).toContain("Подтверждающие факты оценки");
|
||||
expect(markup).toContain("Онлайн-результат без подтверждения личности");
|
||||
expect(markup).toContain("Синтетическая демонстрация, не проверенное измерение");
|
||||
expect(markup).toContain("Пороги не откалиброваны");
|
||||
expect(markup).toContain("2026");
|
||||
});
|
||||
|
||||
it("explains a closed card without offering to open it", () => {
|
||||
const markup = render({
|
||||
state: "closed",
|
||||
fields: [],
|
||||
card: null,
|
||||
evidence: null,
|
||||
generated_at: "2026-10-03T10:00:00Z",
|
||||
});
|
||||
|
||||
expect(markup).toContain("Карточка закрыта");
|
||||
expect(markup).toContain("Новый C2 не откроет ее автоматически");
|
||||
expect(markup).not.toContain("Подтверждающие факты оценки");
|
||||
});
|
||||
|
||||
it("renders the loading, error and missing states", () => {
|
||||
expect(render(undefined, { isLoading: true })).toContain("Загружаем предварительный просмотр");
|
||||
expect(render(undefined, { error: new Error("failed") })).toContain(
|
||||
"Не удалось загрузить предварительный просмотр",
|
||||
);
|
||||
expect(render(undefined)).toContain("Предварительный просмотр пока недоступен");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { CardPreview } from "../../../shared/api/schemas";
|
||||
import { EmptyState, ErrorState, LoadingState, TrustLevel } from "../../../shared/ui";
|
||||
import {
|
||||
presentCandidatePreview,
|
||||
type CandidateViewPresentation,
|
||||
type EvidencePresentation,
|
||||
type SelfAssessmentPresentation,
|
||||
} from "../model/presentation";
|
||||
import styles from "./employer-card-preview.module.css";
|
||||
|
||||
type EmployerCardPreviewProps = {
|
||||
preview: CardPreview | undefined;
|
||||
isLoading: boolean;
|
||||
error: unknown;
|
||||
onRetry: () => void;
|
||||
};
|
||||
|
||||
function SelfAssessmentItem({ item }: { item: SelfAssessmentPresentation }) {
|
||||
return (
|
||||
<li className={styles.assessment} data-confirmed={item.confirmed}>
|
||||
<strong className={styles["assessment-name"]}>{item.specialization}</strong>
|
||||
<span className={styles.declared}>
|
||||
{item.declaredGrade ? `Заявлено: ${item.declaredGrade}` : "Уровень не указан"}
|
||||
</span>
|
||||
<TrustLevel level={item.confirmed ? "confirmed" : "none"} label={item.confirmation} />
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function EvidenceItem({ item }: { item: EvidencePresentation }) {
|
||||
return (
|
||||
<li className={styles.evidence}>
|
||||
<strong>{item.title}</strong>
|
||||
<TrustLevel level={item.trust} label={item.trustLabel} />
|
||||
<dl className={styles["evidence-facts"]}>
|
||||
<dt>Год оценки</dt>
|
||||
<dd>{item.observedYear}</dd>
|
||||
<dt>Основа</dt>
|
||||
<dd>{item.basisLabel}</dd>
|
||||
<dt>Калибровка</dt>
|
||||
<dd>{item.calibrationLabel}</dd>
|
||||
</dl>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function OtherGroups({ card }: { card: CandidateViewPresentation }) {
|
||||
const hasValues = card.stack || card.experience || card.workFormats || card.salaryCompatibility;
|
||||
return (
|
||||
<section aria-labelledby="preview-other-title">
|
||||
<h3 id="preview-other-title">Другие выбранные группы</h3>
|
||||
{hasValues ? (
|
||||
<dl className={styles.facts}>
|
||||
{card.stack ? (
|
||||
<>
|
||||
<dt>Технологии</dt>
|
||||
<dd>{card.stack.join(", ") || "Нет данных"}</dd>
|
||||
</>
|
||||
) : null}
|
||||
{card.experience ? (
|
||||
<>
|
||||
<dt>Общий опыт</dt>
|
||||
<dd>{card.experience}</dd>
|
||||
</>
|
||||
) : null}
|
||||
{card.workFormats ? (
|
||||
<>
|
||||
<dt>Форматы работы</dt>
|
||||
<dd>{card.workFormats.join(", ") || "Нет данных"}</dd>
|
||||
</>
|
||||
) : null}
|
||||
{card.salaryCompatibility ? (
|
||||
<>
|
||||
<dt>Совместимость ожиданий</dt>
|
||||
<dd>{card.salaryCompatibility}</dd>
|
||||
</>
|
||||
) : null}
|
||||
</dl>
|
||||
) : (
|
||||
<p>Другие группы не содержат значений.</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The anonymous card the way the owner's private preview returns it. It shows
|
||||
* each specialization on its own: a confirmed category and a declared grade
|
||||
* that is still unconfirmed are never merged or ranked together, and the
|
||||
* evidence block restates the basis and calibration the server reports.
|
||||
*/
|
||||
export function EmployerCardPreview({
|
||||
preview,
|
||||
isLoading,
|
||||
error,
|
||||
onRetry,
|
||||
}: EmployerCardPreviewProps) {
|
||||
if (isLoading && !preview) return <LoadingState label="Загружаем предварительный просмотр..." />;
|
||||
if (error) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={error}
|
||||
onRetry={onRetry}
|
||||
title="Не удалось загрузить предварительный просмотр"
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!preview) return <EmptyState title="Предварительный просмотр пока недоступен" />;
|
||||
|
||||
const card = presentCandidatePreview(preview);
|
||||
if (!card) {
|
||||
return (
|
||||
<EmptyState
|
||||
title="Карточка закрыта"
|
||||
description="Компании не видят карточку. Новый C2 не откроет ее автоматически: публикацию нужно включить отдельно."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.preview}>
|
||||
<p className={styles.alias}>
|
||||
Предварительный псевдоним: <strong>{card.pseudonym}</strong>
|
||||
</p>
|
||||
<p className={styles.note}>
|
||||
Это отдельный псевдоним предпросмотра. В каждой организации используется свой псевдоним, а
|
||||
ее фильтры и проверка размера группы могут дополнительно скрыть или обобщить данные.
|
||||
</p>
|
||||
<div className={styles.grid}>
|
||||
<section aria-labelledby="preview-confirmed-title">
|
||||
<h3 id="preview-confirmed-title">Подтвержденные категории</h3>
|
||||
{card.categories?.length ? (
|
||||
<ul className={styles.list}>
|
||||
{card.categories.map((category) => (
|
||||
<li key={`${category.specialization}-${category.grade}`}>
|
||||
{category.specialization}: {category.grade}, {category.strength.toLowerCase()}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Подтвержденных категорий в карточке нет.</p>
|
||||
)}
|
||||
</section>
|
||||
<section aria-labelledby="preview-self-title">
|
||||
<h3 id="preview-self-title">Самооценка по направлениям</h3>
|
||||
{card.selfAssessments?.length ? (
|
||||
<ul className={styles.list}>
|
||||
{card.selfAssessments.map((item) => (
|
||||
<SelfAssessmentItem key={item.specialization} item={item} />
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Самооценка не опубликована или отсутствует.</p>
|
||||
)}
|
||||
<p className={styles.hint}>
|
||||
Статус подтверждения задается для каждой специализации отдельно. Причины его отсутствия
|
||||
и неудачные попытки компании не видят.
|
||||
</p>
|
||||
</section>
|
||||
{card.evidence ? (
|
||||
<section aria-labelledby="preview-evidence-title">
|
||||
<h3 id="preview-evidence-title">Подтверждающие факты оценки</h3>
|
||||
{card.evidence.length > 0 ? (
|
||||
<ul className={styles.list}>
|
||||
{card.evidence.map((item) => (
|
||||
<EvidenceItem key={item.title} item={item} />
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Для опубликованных категорий нет видимого подтверждающего факта.</p>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
<OtherGroups card={card} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1 +1,2 @@
|
||||
export { ConsentManagement } from "./ui/consent-management";
|
||||
export { consentPurposeAnchorId } from "./model/anchors";
|
||||
@@ -0,0 +1,4 @@
|
||||
/** Id of the block of one consent purpose, for links that move the reader to it. */
|
||||
export function consentPurposeAnchorId(purpose: string): string {
|
||||
return `consent-purpose-${purpose}`;
|
||||
}
|
||||
@@ -176,3 +176,7 @@
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
|
||||
.purpose-anchor {
|
||||
scroll-margin-block-start: var(--space-4);
|
||||
}
|
||||
@@ -33,10 +33,21 @@ import {
|
||||
groupOrganizationConsents,
|
||||
} from "../../../entities/consent";
|
||||
import type { OrganizationConsentGroup } from "../../../entities/consent";
|
||||
import { consentPurposeAnchorId } from "../model/anchors";
|
||||
import styles from "./consent-management.module.css";
|
||||
|
||||
const pageSize = 100;
|
||||
const historyQueryKey = getListMyConsentsQueryKey({ limit: pageSize });
|
||||
const noOrganizations: ReadonlySet<string> = new Set();
|
||||
|
||||
type ConsentManagementProps = {
|
||||
/**
|
||||
* Organizations the candidate currently hides the profile from. A C4 record
|
||||
* of such an organization stays in the ledger, so the list says that it
|
||||
* does not reopen contact access while the profile is hidden.
|
||||
*/
|
||||
hiddenOrganizationIds?: ReadonlySet<string>;
|
||||
};
|
||||
|
||||
type ConsentAction =
|
||||
| { kind: "account" }
|
||||
@@ -71,7 +82,8 @@ function actionCopy(action: ConsentAction): {
|
||||
acknowledgment:
|
||||
"Я понимаю, что будут отозваны все действующие согласия C4 для этой компании.",
|
||||
button: "Подтвердить отзыв",
|
||||
success: "Запрос на отзыв C4 обработан. Проверьте обновленное состояние ниже.",
|
||||
success:
|
||||
"Запрос на отзыв C4 обработан. Будущие чтения контактов этой компанией закрыты; для нового доступа нужны новое приглашение и новое согласие C4. Проверьте обновленное состояние ниже.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -80,7 +92,10 @@ function actionCopy(action: ConsentAction): {
|
||||
description: consentPurposeDetails[action.purpose].consequence,
|
||||
acknowledgment: `Я понимаю последствия отзыва C${action.purpose.slice(1)}.`,
|
||||
button: "Подтвердить отзыв",
|
||||
success: `C${action.purpose.slice(1)} отозвано. Проверьте обновленное состояние ниже.`,
|
||||
success:
|
||||
action.purpose === "c2"
|
||||
? "C2 отозвано. Карточка закрыта, будущие чтения компаниями закрыты. Новое согласие C2 карточку не откроет: публикацию нужно включить отдельно. Бывшей компании для контактов нужны новое приглашение и новое согласие C4. Проверьте обновленное состояние ниже."
|
||||
: `C${action.purpose.slice(1)} отозвано. Проверьте обновленное состояние ниже.`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -317,6 +332,7 @@ function ConsentGrantPanel({
|
||||
function OrganizationConsent({
|
||||
group,
|
||||
records,
|
||||
isHidden,
|
||||
confirming,
|
||||
accepted,
|
||||
isBusy,
|
||||
@@ -328,6 +344,7 @@ function OrganizationConsent({
|
||||
}: {
|
||||
group: OrganizationConsentGroup;
|
||||
records: ConsentRecord[];
|
||||
isHidden: boolean;
|
||||
confirming: boolean;
|
||||
accepted: boolean;
|
||||
isBusy: boolean;
|
||||
@@ -343,6 +360,12 @@ function OrganizationConsent({
|
||||
return (
|
||||
<article className={styles["organization-group"]}>
|
||||
<h3 className={styles["record-title"]}>{group.displayName}</h3>
|
||||
{isHidden ? (
|
||||
<p className={styles.notice} role="status">
|
||||
Профиль скрыт от этой компании. Запись C4 остается в журнале, но не возвращает доступ к
|
||||
контактам: он закрыт до нового приглашения и нового согласия C4.
|
||||
</p>
|
||||
) : null}
|
||||
<div className={styles["record-list"]}>
|
||||
{records.map((record) => (
|
||||
<ConsentRecordView key={record.id} record={record} />
|
||||
@@ -368,7 +391,9 @@ function OrganizationConsent({
|
||||
);
|
||||
}
|
||||
|
||||
export function ConsentManagement() {
|
||||
export function ConsentManagement({
|
||||
hiddenOrganizationIds = noOrganizations,
|
||||
}: ConsentManagementProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const session = useGetCurrentSession();
|
||||
const csrfToken = session.data?.csrf_token;
|
||||
@@ -587,102 +612,109 @@ export function ConsentManagement() {
|
||||
purpose === "c1" ? Boolean(activeRecord) : Boolean(activeRecord && action);
|
||||
|
||||
return (
|
||||
<Section
|
||||
<div
|
||||
key={purpose}
|
||||
title={`C${purpose.slice(1)}. ${consentPurposeDetails[purpose].title}`}
|
||||
description={consentPurposeDetails[purpose].consequence}
|
||||
id={consentPurposeAnchorId(purpose)}
|
||||
className={styles["purpose-anchor"]}
|
||||
tabIndex={-1}
|
||||
>
|
||||
{purpose === "c4" ? (
|
||||
c4Groups.length > 0 ? (
|
||||
<div className={styles["organization-list"]}>
|
||||
{c4Groups.map((group) => (
|
||||
<OrganizationConsent
|
||||
key={group.organizationId}
|
||||
group={group}
|
||||
records={group.records}
|
||||
confirming={
|
||||
confirmation?.kind === "organization" &&
|
||||
confirmation.organizationId === group.organizationId
|
||||
}
|
||||
accepted={acceptedConfirmation}
|
||||
isBusy={
|
||||
confirmation?.kind === "organization" &&
|
||||
confirmation.organizationId === group.organizationId &&
|
||||
revokeOrganization.isPending
|
||||
}
|
||||
isReady={canConfirm}
|
||||
onBegin={() =>
|
||||
beginConfirmation({
|
||||
kind: "organization",
|
||||
organizationId: group.organizationId,
|
||||
})
|
||||
}
|
||||
onAcceptChange={setAcceptedConfirmation}
|
||||
onCancel={cancelConfirmation}
|
||||
onConfirm={() => void submitConfirmation()}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className={styles["empty-purpose"]}>{emptyMessage}</p>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
{purposeRecords.length > 0 ? (
|
||||
<div className={styles["record-list"]}>
|
||||
{purposeRecords.map((record) => (
|
||||
<ConsentRecordView key={record.id} record={record} />
|
||||
<Section
|
||||
title={`C${purpose.slice(1)}. ${consentPurposeDetails[purpose].title}`}
|
||||
description={consentPurposeDetails[purpose].consequence}
|
||||
>
|
||||
{purpose === "c4" ? (
|
||||
c4Groups.length > 0 ? (
|
||||
<div className={styles["organization-list"]}>
|
||||
{c4Groups.map((group) => (
|
||||
<OrganizationConsent
|
||||
key={group.organizationId}
|
||||
group={group}
|
||||
records={group.records}
|
||||
isHidden={hiddenOrganizationIds.has(group.organizationId)}
|
||||
confirming={
|
||||
confirmation?.kind === "organization" &&
|
||||
confirmation.organizationId === group.organizationId
|
||||
}
|
||||
accepted={acceptedConfirmation}
|
||||
isBusy={
|
||||
confirmation?.kind === "organization" &&
|
||||
confirmation.organizationId === group.organizationId &&
|
||||
revokeOrganization.isPending
|
||||
}
|
||||
isReady={canConfirm}
|
||||
onBegin={() =>
|
||||
beginConfirmation({
|
||||
kind: "organization",
|
||||
organizationId: group.organizationId,
|
||||
})
|
||||
}
|
||||
onAcceptChange={setAcceptedConfirmation}
|
||||
onCancel={cancelConfirmation}
|
||||
onConfirm={() => void submitConfirmation()}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className={styles["empty-purpose"]}>{emptyMessage}</p>
|
||||
)}
|
||||
{canRevoke && action && !isConfirmingPurpose ? (
|
||||
<Button variant="secondary" onClick={() => beginConfirmation(action)}>
|
||||
{purpose === "c1"
|
||||
? "Отозвать C1 и запросить удаление"
|
||||
: `Отозвать C${purpose.slice(1)}`}
|
||||
</Button>
|
||||
) : null}
|
||||
{canRevoke && action && isConfirmingPurpose ? (
|
||||
<ActionConfirmation
|
||||
action={action}
|
||||
accepted={acceptedConfirmation}
|
||||
isBusy={purpose === "c1" ? deleteAccount.isPending : revoke.isPending}
|
||||
isReady={canConfirm}
|
||||
onAcceptChange={setAcceptedConfirmation}
|
||||
onCancel={cancelConfirmation}
|
||||
onConfirm={() => void submitConfirmation()}
|
||||
/>
|
||||
) : null}
|
||||
<div className={styles["grant-actions"]}>
|
||||
{grantPurpose === purpose ? (
|
||||
<ConsentGrantPanel
|
||||
key={purpose}
|
||||
purpose={purpose}
|
||||
activeRecord={activeRecord}
|
||||
csrfToken={canMutate ? csrfToken : undefined}
|
||||
isSubmitting={grant.isPending}
|
||||
onCancel={() => setGrantPurpose(null)}
|
||||
onGrant={submitGrant}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
{purposeRecords.length > 0 ? (
|
||||
<div className={styles["record-list"]}>
|
||||
{purposeRecords.map((record) => (
|
||||
<ConsentRecordView key={record.id} record={record} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
variant="quiet"
|
||||
aria-expanded={grantPurpose === purpose}
|
||||
onClick={() => {
|
||||
setStatusMessage(null);
|
||||
setActionError(null);
|
||||
setGrantPurpose(purpose);
|
||||
}}
|
||||
>
|
||||
Прочитать текущий текст C{purpose.slice(1)}
|
||||
</Button>
|
||||
<p className={styles["empty-purpose"]}>{emptyMessage}</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Section>
|
||||
{canRevoke && action && !isConfirmingPurpose ? (
|
||||
<Button variant="secondary" onClick={() => beginConfirmation(action)}>
|
||||
{purpose === "c1"
|
||||
? "Отозвать C1 и запросить удаление"
|
||||
: `Отозвать C${purpose.slice(1)}`}
|
||||
</Button>
|
||||
) : null}
|
||||
{canRevoke && action && isConfirmingPurpose ? (
|
||||
<ActionConfirmation
|
||||
action={action}
|
||||
accepted={acceptedConfirmation}
|
||||
isBusy={purpose === "c1" ? deleteAccount.isPending : revoke.isPending}
|
||||
isReady={canConfirm}
|
||||
onAcceptChange={setAcceptedConfirmation}
|
||||
onCancel={cancelConfirmation}
|
||||
onConfirm={() => void submitConfirmation()}
|
||||
/>
|
||||
) : null}
|
||||
<div className={styles["grant-actions"]}>
|
||||
{grantPurpose === purpose ? (
|
||||
<ConsentGrantPanel
|
||||
key={purpose}
|
||||
purpose={purpose}
|
||||
activeRecord={activeRecord}
|
||||
csrfToken={canMutate ? csrfToken : undefined}
|
||||
isSubmitting={grant.isPending}
|
||||
onCancel={() => setGrantPurpose(null)}
|
||||
onGrant={submitGrant}
|
||||
/>
|
||||
) : (
|
||||
<Button
|
||||
variant="quiet"
|
||||
aria-expanded={grantPurpose === purpose}
|
||||
onClick={() => {
|
||||
setStatusMessage(null);
|
||||
setActionError(null);
|
||||
setGrantPurpose(purpose);
|
||||
}}
|
||||
>
|
||||
Прочитать текущий текст C{purpose.slice(1)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -72,6 +72,56 @@
|
||||
border-inline-start-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.step {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
/* The state is stated in text; the stronger edge only repeats it for sighted users. */
|
||||
.step[data-c2-state="inactive"] {
|
||||
border-inline-start: var(--line-strong) solid var(--color-danger);
|
||||
}
|
||||
|
||||
.step[data-c2-state="active"] {
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
}
|
||||
|
||||
.step-title {
|
||||
margin: 0;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.step-text {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.closure {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.closure-title {
|
||||
margin: 0;
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.closure ul {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
margin: 0;
|
||||
padding-inline-start: 1.25rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
@@ -39,6 +39,7 @@ describe("profile visibility controls", () => {
|
||||
onDraftChange={vi.fn()}
|
||||
onSave={vi.fn()}
|
||||
onReload={vi.fn()}
|
||||
onOpenConsent={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
const search = renderToStaticMarkup(
|
||||
@@ -51,7 +52,8 @@ describe("profile visibility controls", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(publication).toContain("Для публикации сначала отдельно примите согласие C2 ниже.");
|
||||
expect(publication).toContain("Для публикации сначала отдельно примите согласие C2");
|
||||
expect(publication).toContain("Перейти к согласию C2");
|
||||
expect(publication).toContain("Подтвержденная категория и уровень");
|
||||
expect(publication).toContain("Самооценка по направлениям");
|
||||
expect(publication).toContain('aria-disabled="true"');
|
||||
@@ -77,6 +79,7 @@ describe("profile visibility controls", () => {
|
||||
onDraftChange={vi.fn()}
|
||||
onSave={vi.fn()}
|
||||
onReload={vi.fn()}
|
||||
onOpenConsent={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -85,3 +88,58 @@ describe("profile visibility controls", () => {
|
||||
expect(markup).toContain("Загрузить актуальные настройки");
|
||||
});
|
||||
});
|
||||
|
||||
describe("publication closure notice", () => {
|
||||
const closedByRevocation: PrivacySettings = {
|
||||
...settings,
|
||||
publication: {
|
||||
state: "closed",
|
||||
closed_reason: "consent_revoked",
|
||||
fields: [],
|
||||
consent_id: "00000000-0000-4000-8000-000000000002",
|
||||
published_at: "2026-10-02T00:00:00Z",
|
||||
version: 3,
|
||||
},
|
||||
};
|
||||
|
||||
function render(value: PrivacySettings, c2State: "active" | "inactive") {
|
||||
return renderToStaticMarkup(
|
||||
<PublicationControls
|
||||
settings={value}
|
||||
c2State={c2State}
|
||||
draft={{ state: "closed", fields: [], expectedVersion: value.publication.version }}
|
||||
isDirty={false}
|
||||
isStale={false}
|
||||
hasUnsupportedFields={false}
|
||||
canSave={false}
|
||||
isSaving={false}
|
||||
message={null}
|
||||
error={null}
|
||||
onDraftChange={vi.fn()}
|
||||
onSave={vi.fn()}
|
||||
onReload={vi.fn()}
|
||||
onOpenConsent={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
it("explains closed future reads and a new C4 after a revocation", () => {
|
||||
const markup = render(closedByRevocation, "inactive");
|
||||
|
||||
expect(markup).toContain("Согласие C2 отозвано, карточка закрыта");
|
||||
expect(markup).toContain("Будущие чтения карточки компаниями закрыты");
|
||||
expect(markup).toContain("новое приглашение и новое согласие C4");
|
||||
});
|
||||
|
||||
it("keeps a fresh C2 apart from the publication that it never reopens", () => {
|
||||
const markup = render(closedByRevocation, "active");
|
||||
|
||||
expect(markup).toContain("Согласие C2 действует. Оно само по себе не включает публикацию.");
|
||||
expect(markup).toContain("Новое согласие C2 не откроет карточку само");
|
||||
expect(markup).not.toContain("Перейти к согласию C2");
|
||||
});
|
||||
|
||||
it("shows no closure notice for a card that was never published", () => {
|
||||
expect(render(settings, "inactive")).not.toContain("карточка закрыта");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useId } from "react";
|
||||
import {
|
||||
cardFieldLabels,
|
||||
describePublicationClosure,
|
||||
publishableCardFields,
|
||||
type C2State,
|
||||
type PublicationDraft,
|
||||
@@ -23,8 +24,17 @@ type PublicationControlsProps = {
|
||||
onDraftChange: (draft: PublicationDraft) => void;
|
||||
onSave: () => void;
|
||||
onReload: () => void;
|
||||
/** Moves the reader to the C2 consent block. It never grants anything. */
|
||||
onOpenConsent: () => void;
|
||||
};
|
||||
|
||||
const c2StepText = {
|
||||
active: "Согласие C2 действует. Оно само по себе не включает публикацию.",
|
||||
checking: "Проверяем полную историю согласий C2. До завершения публикация недоступна.",
|
||||
inactive:
|
||||
"Для публикации сначала отдельно примите согласие C2 в блоке «C2. Публикация карточки кандидата» выше.",
|
||||
} as const satisfies Record<C2State, string>;
|
||||
|
||||
export function PublicationControls({
|
||||
settings,
|
||||
c2State,
|
||||
@@ -39,10 +49,12 @@ export function PublicationControls({
|
||||
onDraftChange,
|
||||
onSave,
|
||||
onReload,
|
||||
onOpenConsent,
|
||||
}: PublicationControlsProps) {
|
||||
const stateId = useId();
|
||||
const fieldsId = useId();
|
||||
const c2Id = useId();
|
||||
const closure = describePublicationClosure(settings.publication);
|
||||
|
||||
function toggleField(field: PublicationDraft["fields"][number], checked: boolean) {
|
||||
const next = checked
|
||||
@@ -63,8 +75,33 @@ export function PublicationControls({
|
||||
Текущее состояние:{" "}
|
||||
{settings.publication.state === "published" ? "опубликована" : "закрыта"}.
|
||||
</p>
|
||||
{closure ? (
|
||||
<div className={styles.closure} role="status">
|
||||
<p className={styles["closure-title"]}>{closure.title}</p>
|
||||
<ul>
|
||||
{closure.points.map((point) => (
|
||||
<li key={point}>{point}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className={styles.step} data-c2-state={c2State}>
|
||||
<h3 className={styles["step-title"]}>Шаг 1. Согласие C2</h3>
|
||||
<p id={c2Id} className={styles["step-text"]}>
|
||||
{c2StepText[c2State]}
|
||||
</p>
|
||||
{c2State === "inactive" ? (
|
||||
<div className={styles.actions}>
|
||||
<Button variant="secondary" onClick={onOpenConsent}>
|
||||
Перейти к согласию C2
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<fieldset className={styles.group} aria-describedby={stateId}>
|
||||
<legend>Состояние карточки</legend>
|
||||
<legend>Шаг 2. Состояние карточки</legend>
|
||||
<p id={stateId} className={styles.help}>
|
||||
Закрытая карточка не доступна компаниям. Повторная публикация требует отдельного
|
||||
действия.
|
||||
@@ -94,7 +131,7 @@ export function PublicationControls({
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group} aria-describedby={fieldsId}>
|
||||
<legend>Поля анонимной карточки</legend>
|
||||
<legend>Шаг 3. Поля анонимной карточки</legend>
|
||||
<p id={fieldsId} className={styles.help}>
|
||||
Имя, контакты, работодатели и суммы зарплаты не публикуются. Подтвержденные категории и
|
||||
самооценка показываются раздельно.
|
||||
@@ -118,13 +155,6 @@ export function PublicationControls({
|
||||
Выберите разрешенные поля или явно закройте публикацию.
|
||||
</p>
|
||||
) : null}
|
||||
<p id={c2Id} className={styles.help}>
|
||||
{c2State === "active"
|
||||
? "Согласие C2 активно. Оно само по себе не включает публикацию."
|
||||
: c2State === "checking"
|
||||
? "Проверяем полную историю согласий C2. До завершения публикация недоступна."
|
||||
: "Для публикации сначала отдельно примите согласие C2 ниже."}
|
||||
</p>
|
||||
{isStale ? (
|
||||
<div className={styles.error} role="alert">
|
||||
Настройки изменились на сервере. Ваш черновик сохранен на экране. Загрузите актуальные
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export { ConsentsPage } from "./ui/consents-page";
|
||||
@@ -1,25 +0,0 @@
|
||||
import { ConsentManagement } from "../../../features/consent-management";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { ButtonLink, Page, Section } from "../../../shared/ui";
|
||||
|
||||
export function ConsentsPage() {
|
||||
return (
|
||||
<Page
|
||||
title="Согласия и настройки приватности"
|
||||
eyebrow="Кабинет кандидата"
|
||||
lead="Здесь можно проверить историю каждого согласия и отдельно изменить его состояние."
|
||||
width="wide"
|
||||
>
|
||||
<ConsentManagement />
|
||||
<Section title="Ручная оценка">
|
||||
<p>
|
||||
Можно запросить оценку специалистом до первого теста или после отзыва согласия на
|
||||
автоматическую оценку. Запрос не включает согласие обратно.
|
||||
</p>
|
||||
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
|
||||
Запросить ручную оценку
|
||||
</ButtonLink>
|
||||
</Section>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,8 @@
|
||||
.preview,
|
||||
.organization-columns {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--space-5);
|
||||
}
|
||||
|
||||
.preview-alias {
|
||||
margin: 0;
|
||||
font-size: 1.05rem;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.note {
|
||||
@@ -16,13 +12,6 @@
|
||||
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);
|
||||
@@ -31,39 +20,11 @@
|
||||
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;
|
||||
@@ -110,10 +71,6 @@
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.preview-grid li + li {
|
||||
margin-block-start: 0.4rem;
|
||||
}
|
||||
|
||||
.pagination {
|
||||
display: grid;
|
||||
justify-items: start;
|
||||
@@ -139,17 +96,7 @@
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,7 @@
|
||||
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";
|
||||
import type { CardAccess, HiddenOrganization, PrivacyEventList } from "../../../shared/api/schemas";
|
||||
import { CardAccessHistory, OrganizationVisibility, PrivacyHistory } from "./privacy-page";
|
||||
|
||||
const orgA = {
|
||||
id: "00000000-0000-4000-8000-000000000001",
|
||||
@@ -40,49 +30,56 @@ function hiddenOrganization(organization: typeof orgA): HiddenOrganization {
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
evidence: {
|
||||
items: [
|
||||
{
|
||||
skill: "backend",
|
||||
grade: "junior",
|
||||
trust: 1,
|
||||
basis: "synthetic_demo",
|
||||
calibration_status: "uncalibrated",
|
||||
observed_year: 2026,
|
||||
},
|
||||
],
|
||||
},
|
||||
generated_at: "2026-10-03T10:00:00Z",
|
||||
};
|
||||
it("shows who read the card and when, within the permitted detail", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<PrivacyPreview preview={preview} isLoading={false} error={null} onRetry={vi.fn()} />,
|
||||
<CardAccessHistory
|
||||
records={[
|
||||
accessRecord("00000000-0000-4000-8000-000000000051", orgA, "contact_read"),
|
||||
accessRecord("00000000-0000-4000-8000-000000000052", null),
|
||||
]}
|
||||
hiddenOrganizationIds={new Set([orgA.id])}
|
||||
isLoading={false}
|
||||
error={null}
|
||||
hasMore={false}
|
||||
isFetching={false}
|
||||
onLoad={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Предварительный псевдоним");
|
||||
expect(markup).toContain("Это отдельный псевдоним предпросмотра");
|
||||
expect(markup).toContain("Подтвержденные категории");
|
||||
expect(markup).toContain("Backend: Junior");
|
||||
expect(markup).toContain("Самооценка по направлениям");
|
||||
expect(markup).toContain("Frontend: Middle; грейд не подтвержден");
|
||||
expect(markup).toContain("Открыты контактные данные");
|
||||
expect(markup).toContain("Просмотрена карточка профиля");
|
||||
expect(markup).toContain("Компания А");
|
||||
expect(markup).toContain('dateTime="2026-10-01T10:00:00Z"');
|
||||
expect(markup).toContain("Организация не раскрывается");
|
||||
expect(markup).toContain("Сейчас профиль скрыт от этой организации");
|
||||
expect(markup).toContain("Сотрудники, запросы, фильтры и место в выдаче здесь не сохраняются");
|
||||
expect(markup).toContain("Показана вся история");
|
||||
});
|
||||
|
||||
it("shows an empty access history and an empty settings history", () => {
|
||||
const access = renderToStaticMarkup(
|
||||
<CardAccessHistory
|
||||
records={[]}
|
||||
isLoading={false}
|
||||
error={null}
|
||||
hasMore={false}
|
||||
isFetching={false}
|
||||
onLoad={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
const settings = renderToStaticMarkup(
|
||||
<PrivacyHistory
|
||||
events={[]}
|
||||
isLoading={false}
|
||||
error={null}
|
||||
hasMore={false}
|
||||
isFetching={false}
|
||||
onLoad={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(access).toContain("История доступа пока пуста");
|
||||
expect(settings).toContain("История настроек пока пуста");
|
||||
});
|
||||
|
||||
it("does not offer hide actions until the hidden list is fully loaded", () => {
|
||||
@@ -114,7 +111,7 @@ describe("privacy page sections", () => {
|
||||
"Список действий появится после загрузки всех страниц скрытых компаний",
|
||||
);
|
||||
expect(markup).not.toContain("Скрыть профиль</button>");
|
||||
expect(markup).toContain("не восстанавливает C4");
|
||||
expect(markup).toContain("не восстанавливают прежний доступ к контактам");
|
||||
});
|
||||
|
||||
it("shows only organizations from access history as hide candidates", () => {
|
||||
@@ -148,7 +145,7 @@ describe("privacy page sections", () => {
|
||||
expect(markup).toContain("Компания Б");
|
||||
expect(markup).toContain("Скрыть профиль");
|
||||
expect(markup).toContain("Загрузить ранние записи");
|
||||
expect(markup).toContain("Снятие скрытия само по себе не восстанавливает C4");
|
||||
expect(markup).toContain("новое приглашение и новое согласие C4");
|
||||
});
|
||||
|
||||
it("does not describe a partial history page as the complete history", () => {
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { ConsentManagement } from "../../../features/consent-management";
|
||||
import { ConsentManagement, consentPurposeAnchorId } from "../../../features/consent-management";
|
||||
import { PublicationControls, SearchStatusControl } from "../../../features/profile-visibility";
|
||||
import {
|
||||
buildPublicationSubmission,
|
||||
buildSearchStatusSubmission,
|
||||
cardAccessLabels,
|
||||
cardFieldLabels,
|
||||
contactAccessAfterVisibilityChange,
|
||||
currentC2State,
|
||||
describeAccessOrganization,
|
||||
EmployerCardPreview,
|
||||
formatPrivacyDate,
|
||||
hasUnsupportedPublishedFields,
|
||||
isSamePublicationDraft,
|
||||
organizationsAvailableToHide,
|
||||
presentCandidatePreview,
|
||||
privacyEventLabels,
|
||||
publicationDraftFromSettings,
|
||||
type OrganizationReference,
|
||||
@@ -43,10 +45,10 @@ import {
|
||||
setMySearchStatus,
|
||||
unhideOrganization,
|
||||
} from "../../../shared/api/endpoints/privacy/privacy";
|
||||
import { paths } from "../../../shared/config";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
import type {
|
||||
CardAccess,
|
||||
CardPreview,
|
||||
HiddenOrganization,
|
||||
PrivacyEventList,
|
||||
PrivacySettings,
|
||||
@@ -54,6 +56,7 @@ import type {
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
@@ -65,6 +68,7 @@ import { candidateViewQueryKeys } from "../../../entities/candidate-view";
|
||||
import styles from "./privacy-page.module.css";
|
||||
|
||||
const pageSize = 100;
|
||||
const noOrganizations: ReadonlySet<string> = new Set();
|
||||
const privateQueryOptions = {
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
@@ -146,114 +150,6 @@ function useConsentHistoryReady(
|
||||
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 <LoadingState label="Загружаем предварительный просмотр..." />;
|
||||
if (error)
|
||||
return (
|
||||
<ErrorState
|
||||
error={error}
|
||||
onRetry={onRetry}
|
||||
title="Не удалось загрузить предварительный просмотр"
|
||||
/>
|
||||
);
|
||||
if (!preview) return <EmptyState title="Предварительный просмотр пока недоступен" />;
|
||||
|
||||
const card = presentCandidatePreview(preview);
|
||||
if (!card) {
|
||||
return (
|
||||
<EmptyState
|
||||
title="Карточка закрыта"
|
||||
description="Компании не видят карточку. Новый C2 не откроет ее автоматически: публикацию нужно включить отдельно."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.preview}>
|
||||
<p className={styles["preview-alias"]}>
|
||||
Предварительный псевдоним: <strong>{card.pseudonym}</strong>
|
||||
</p>
|
||||
<p className={styles.note}>
|
||||
Это отдельный псевдоним предпросмотра. В каждой организации используется свой псевдоним, а
|
||||
ее фильтры и проверка размера группы могут дополнительно скрыть или обобщить данные.
|
||||
</p>
|
||||
<div className={styles["preview-grid"]}>
|
||||
<section aria-labelledby="preview-confirmed-title">
|
||||
<h3 id="preview-confirmed-title">Подтвержденные категории</h3>
|
||||
{card.categories?.length ? (
|
||||
<ul>
|
||||
{card.categories.map((category) => (
|
||||
<li key={`${category.specialization}-${category.grade}`}>
|
||||
{category.specialization}: {category.grade}, {category.strength.toLowerCase()}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Подтвержденных категорий пока нет.</p>
|
||||
)}
|
||||
</section>
|
||||
<section aria-labelledby="preview-self-title">
|
||||
<h3 id="preview-self-title">Самооценка по направлениям</h3>
|
||||
{card.selfAssessments?.length ? (
|
||||
<ul>
|
||||
{card.selfAssessments.map((item) => (
|
||||
<li key={item.specialization}>
|
||||
{item.specialization}: {item.declaredGrade ?? "уровень не указан"};{" "}
|
||||
{item.confirmation.toLowerCase()}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>Самооценка не опубликована или отсутствует.</p>
|
||||
)}
|
||||
</section>
|
||||
<section aria-labelledby="preview-other-title">
|
||||
<h3 id="preview-other-title">Другие выбранные группы</h3>
|
||||
<dl className={styles["preview-facts"]}>
|
||||
{card.stack ? (
|
||||
<>
|
||||
<dt>Технологии</dt>
|
||||
<dd>{card.stack.join(", ") || "Нет данных"}</dd>
|
||||
</>
|
||||
) : null}
|
||||
{card.experience ? (
|
||||
<>
|
||||
<dt>Общий опыт</dt>
|
||||
<dd>{card.experience}</dd>
|
||||
</>
|
||||
) : null}
|
||||
{card.workFormats ? (
|
||||
<>
|
||||
<dt>Форматы работы</dt>
|
||||
<dd>{card.workFormats.join(", ") || "Нет данных"}</dd>
|
||||
</>
|
||||
) : null}
|
||||
{card.salaryCompatibility ? (
|
||||
<>
|
||||
<dt>Совместимость ожиданий</dt>
|
||||
<dd>{card.salaryCompatibility}</dd>
|
||||
</>
|
||||
) : null}
|
||||
{!card.stack && !card.experience && !card.workFormats && !card.salaryCompatibility ? (
|
||||
<dt>Другие группы не содержат значений.</dt>
|
||||
) : null}
|
||||
</dl>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PaginationControl({
|
||||
isLoaded,
|
||||
hasMore,
|
||||
@@ -404,11 +300,7 @@ export function OrganizationVisibility({
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
<p className={styles.note}>
|
||||
Скрытие закрывает будущие чтения этой организации и закрывает действующий контактный доступ
|
||||
в рамках серверной политики. Снятие скрытия само по себе не восстанавливает C4 или доступ к
|
||||
контактам: для нового доступа потребуется отдельное действующее согласие.
|
||||
</p>
|
||||
<p className={styles.note}>{contactAccessAfterVisibilityChange}</p>
|
||||
{actionError ? (
|
||||
<div className={styles.error} role="alert">
|
||||
{actionError}
|
||||
@@ -485,6 +377,7 @@ export function PrivacyHistory({
|
||||
|
||||
export function CardAccessHistory({
|
||||
records,
|
||||
hiddenOrganizationIds = noOrganizations,
|
||||
isLoading,
|
||||
error,
|
||||
hasMore,
|
||||
@@ -492,6 +385,7 @@ export function CardAccessHistory({
|
||||
onLoad,
|
||||
}: {
|
||||
records: readonly CardAccess[];
|
||||
hiddenOrganizationIds?: ReadonlySet<string>;
|
||||
isLoading: boolean;
|
||||
error: unknown;
|
||||
hasMore: boolean;
|
||||
@@ -501,7 +395,7 @@ export function CardAccessHistory({
|
||||
return (
|
||||
<Section
|
||||
title="История доступа к карточке"
|
||||
description="Здесь нет запросов, фильтров, ранжирования или имен сотрудников компаний."
|
||||
description="Для каждого обращения показаны его вид, время и организация, если ее можно назвать. Сотрудники, запросы, фильтры и место в выдаче здесь не сохраняются."
|
||||
>
|
||||
{isLoading && records.length === 0 ? (
|
||||
<LoadingState label="Загружаем историю доступа..." />
|
||||
@@ -515,7 +409,10 @@ export function CardAccessHistory({
|
||||
<li key={record.id}>
|
||||
<strong>{cardAccessLabels[record.kind]}</strong>
|
||||
<time dateTime={record.occurred_at}>{formatPrivacyDate(record.occurred_at)}</time>
|
||||
<span>{record.organization?.name ?? "Компания недоступна"}</span>
|
||||
<span>{describeAccessOrganization(record.organization)}</span>
|
||||
{record.organization && hiddenOrganizationIds.has(record.organization.id) ? (
|
||||
<span>Сейчас профиль скрыт от этой организации</span>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
@@ -546,7 +443,8 @@ export function PrivacyPage() {
|
||||
null,
|
||||
);
|
||||
const previousActorId = useRef<string | null>(null);
|
||||
const previousC2State = useRef<ReturnType<typeof currentC2State>>("checking");
|
||||
// The last C2 state that was not "checking", so a refetch in between cannot hide a revocation.
|
||||
const settledC2State = useRef<ReturnType<typeof currentC2State>>("checking");
|
||||
|
||||
const handleAuthorizationFailure = useCallback(
|
||||
(error: unknown, expected: Session) => {
|
||||
@@ -585,6 +483,7 @@ export function PrivacyPage() {
|
||||
queryClient.removeQueries({ queryKey: candidateViewQueryKeys.actor(previous) });
|
||||
queryClient.removeQueries({ queryKey: candidateViewQueryKeys.activeConsents(previous) });
|
||||
setDraftState(null);
|
||||
settledC2State.current = "checking";
|
||||
setPrivateAccessLost(false);
|
||||
setActionError(null);
|
||||
setActionMessage(null);
|
||||
@@ -710,14 +609,19 @@ export function PrivacyPage() {
|
||||
() => hiddenOrganizationsQuery.data?.pages.flatMap((page) => page.items) ?? [],
|
||||
[hiddenOrganizationsQuery.data],
|
||||
);
|
||||
const hiddenOrganizationIds = useMemo(
|
||||
() => new Set(hiddenOrganizations.map((entry) => entry.organization.id)),
|
||||
[hiddenOrganizations],
|
||||
);
|
||||
const privacyEvents = useMemo(
|
||||
() => privacyHistory.data?.pages.flatMap((page) => page.items) ?? [],
|
||||
[privacyHistory.data],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousC2State.current;
|
||||
previousC2State.current = c2State;
|
||||
if (c2State === "checking") return;
|
||||
const previous = settledC2State.current;
|
||||
settledC2State.current = c2State;
|
||||
if (previous !== "active" || c2State !== "inactive" || !actor) return;
|
||||
|
||||
queryClient.removeQueries({ queryKey: previewKey });
|
||||
@@ -817,6 +721,14 @@ export function PrivacyPage() {
|
||||
);
|
||||
}
|
||||
|
||||
// Moves focus to the C2 block; granting stays a separate, explicit action there.
|
||||
function openConsentBlock(): void {
|
||||
const block = document.getElementById(consentPurposeAnchorId("c2"));
|
||||
if (!block) return;
|
||||
block.focus();
|
||||
block.scrollIntoView({ block: "start" });
|
||||
}
|
||||
|
||||
async function reloadPublicationSettings(): Promise<void> {
|
||||
if (!actor || !isCurrentCandidateSession(queryClient, actor)) return;
|
||||
setFeedbackScope("publication");
|
||||
@@ -866,7 +778,7 @@ export function PrivacyPage() {
|
||||
(currentActor) =>
|
||||
hideOrganization(organization.id, { headers: { "X-CSRF-Token": currentActor.csrf_token } }),
|
||||
undefined,
|
||||
`Профиль скрыт от компании «${organization.name}». Сервер закрывает действующий доступ к контактам.`,
|
||||
`Профиль скрыт от компании «${organization.name}». Ее будущие чтения карточки закрыты. Если компания уже получала контакты, новый доступ возможен только после нового приглашения и нового согласия C4.`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -883,7 +795,7 @@ export function PrivacyPage() {
|
||||
headers: { "X-CSRF-Token": currentActor.csrf_token },
|
||||
}),
|
||||
undefined,
|
||||
`Скрытие компании «${organization.name}» снято. Действующий C4 не восстанавливается.`,
|
||||
`Скрытие компании «${organization.name}» снято. Она читает карточку только пока публикация включена. Прежний доступ к контактам не восстановлен: нужны новое приглашение и новое согласие C4.`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -898,8 +810,9 @@ export function PrivacyPage() {
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
if (session.isPending || session.isFetching)
|
||||
return <LoadingState label="Проверяем доступ к приватным настройкам..." />;
|
||||
// A background session refetch (for example after a rejected consent action) must not unmount
|
||||
// the page and its error message; the queries below pause while the session is refetched.
|
||||
if (session.isPending) return <LoadingState label="Проверяем доступ к приватным настройкам..." />;
|
||||
if (session.data?.account.scenario !== "candidate") {
|
||||
return (
|
||||
<Page title="Настройки приватности" eyebrow="Кабинет кандидата">
|
||||
@@ -938,52 +851,54 @@ export function PrivacyPage() {
|
||||
lead="Согласие, публикация карточки, статус поиска и скрытие от компаний - отдельные настройки. Ни одно действие не включает другое автоматически."
|
||||
>
|
||||
{canShowConsentManagement ? (
|
||||
<ConsentManagement key={actorId} />
|
||||
<>
|
||||
<Section
|
||||
title="Согласия и настройки приватности"
|
||||
description="Каждое согласие хранится и отзывается отдельно. Выдача или отзыв одного не меняет другие, а C2 не включает публикацию без отдельного сохранения ниже."
|
||||
/>
|
||||
<ConsentManagement key={actorId} hiddenOrganizationIds={hiddenOrganizationIds} />
|
||||
</>
|
||||
) : (
|
||||
<Section
|
||||
title="Согласия"
|
||||
title="Согласия и настройки приватности"
|
||||
description="Очищаем прежнюю приватную историю перед загрузкой текущего аккаунта."
|
||||
>
|
||||
<LoadingState label="Подготавливаем историю согласий..." />
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<Section
|
||||
title="Проверка согласия C2"
|
||||
description="Для публикации проверяется действующая запись C2 из серверной истории согласий. Неизвестное состояние не считается согласием."
|
||||
>
|
||||
{c2State === "active" ? (
|
||||
<p role="status">
|
||||
Действующее согласие C2 найдено. Публикация все равно требует отдельного сохранения.
|
||||
</p>
|
||||
) : c2State === "inactive" ? (
|
||||
<p role="status">Проверена вся активная история: действующего C2 нет.</p>
|
||||
) : activeConsents.isError ? (
|
||||
<ErrorState
|
||||
error={activeConsents.error}
|
||||
onRetry={() => void activeConsents.refetch()}
|
||||
title="Не удалось проверить согласие C2"
|
||||
/>
|
||||
) : activeConsents.isPending ? (
|
||||
<LoadingState label="Проверяем активные согласия..." />
|
||||
) : (
|
||||
<p role="status">
|
||||
Полная история активных согласий еще не загружена. Отсутствие C2 на текущей странице не
|
||||
означает, что его нет.
|
||||
</p>
|
||||
)}
|
||||
{activeConsents.hasNextPage ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={activeConsents.isFetchingNextPage}
|
||||
onClick={() => void activeConsents.fetchNextPage()}
|
||||
>
|
||||
{activeConsents.isFetchingNextPage
|
||||
? "Проверяем историю..."
|
||||
: "Проверить следующую страницу активных согласий"}
|
||||
</Button>
|
||||
) : null}
|
||||
</Section>
|
||||
{c2State === "checking" ? (
|
||||
<Section
|
||||
title="Проверка согласия C2"
|
||||
description="Для публикации проверяется действующая запись C2 из серверной истории согласий. Неизвестное состояние не считается согласием."
|
||||
>
|
||||
{activeConsents.isError ? (
|
||||
<ErrorState
|
||||
error={activeConsents.error}
|
||||
onRetry={() => void activeConsents.refetch()}
|
||||
title="Не удалось проверить согласие C2"
|
||||
/>
|
||||
) : activeConsents.isPending ? (
|
||||
<LoadingState label="Проверяем активные согласия..." />
|
||||
) : (
|
||||
<p role="status">
|
||||
Полная история активных согласий еще не загружена. Отсутствие C2 на текущей странице
|
||||
не означает, что его нет.
|
||||
</p>
|
||||
)}
|
||||
{activeConsents.hasNextPage ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
isBusy={activeConsents.isFetchingNextPage}
|
||||
onClick={() => void activeConsents.fetchNextPage()}
|
||||
>
|
||||
{activeConsents.isFetchingNextPage
|
||||
? "Проверяем историю..."
|
||||
: "Проверить следующую страницу активных согласий"}
|
||||
</Button>
|
||||
) : null}
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
<PublicationControls
|
||||
settings={settings}
|
||||
@@ -1001,6 +916,7 @@ export function PrivacyPage() {
|
||||
}}
|
||||
onSave={() => void savePublication()}
|
||||
onReload={() => void reloadPublicationSettings()}
|
||||
onOpenConsent={openConsentBlock}
|
||||
/>
|
||||
|
||||
<SearchStatusControl
|
||||
@@ -1015,7 +931,7 @@ export function PrivacyPage() {
|
||||
title="Предварительный просмотр карточки"
|
||||
description="Показывает отдельный предпросмотр, а не гарантированный вид для каждой организации."
|
||||
>
|
||||
<PrivacyPreview
|
||||
<EmployerCardPreview
|
||||
preview={previewQuery.data}
|
||||
isLoading={previewQuery.isPending || previewQuery.isFetching}
|
||||
error={previewQuery.error}
|
||||
@@ -1054,12 +970,23 @@ export function PrivacyPage() {
|
||||
|
||||
<CardAccessHistory
|
||||
records={accessRecords}
|
||||
hiddenOrganizationIds={hiddenOrganizationIds}
|
||||
isLoading={accessHistory.isPending}
|
||||
error={accessHistory.error}
|
||||
hasMore={Boolean(accessHistory.hasNextPage)}
|
||||
isFetching={accessHistory.isFetchingNextPage}
|
||||
onLoad={() => void accessHistory.fetchNextPage()}
|
||||
/>
|
||||
|
||||
<Section title="Ручная оценка">
|
||||
<p>
|
||||
Можно запросить оценку специалистом до первого теста или после отзыва согласия на
|
||||
автоматическую оценку. Запрос не включает согласие обратно.
|
||||
</p>
|
||||
<ButtonLink to={paths.candidate.supportManual} variant="secondary">
|
||||
Запросить ручную оценку
|
||||
</ButtonLink>
|
||||
</Section>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { faker } from "@faker-js/faker";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import type { ZodType } from "zod";
|
||||
import { fakeFromPattern, type PatternLengthBounds } from "./mock-pattern";
|
||||
import * as schemas from "./schemas";
|
||||
@@ -11,7 +11,12 @@ import * as schemas from "./schemas";
|
||||
// discovered from the generated files, so a new operation is covered without
|
||||
// editing this test.
|
||||
|
||||
// A fixed, bounded set of seeds keeps every run identical. Generating and
|
||||
// validating the large union mocks takes seconds on a loaded machine, so the
|
||||
// default 5 s limit of a test would fail on speed, not on an invalid mock.
|
||||
const seeds = Array.from({ length: 25 }, (_, index) => index + 1);
|
||||
const mockCaseTimeoutMs = 60_000;
|
||||
const fixedReferenceDate = new Date("2026-10-09T12:00:00Z");
|
||||
|
||||
const mockModules = import.meta.glob<Record<string, unknown>>("./endpoints/*/*.msw.ts", {
|
||||
eager: true,
|
||||
@@ -95,6 +100,12 @@ function describeValue(value: unknown): string {
|
||||
const cases = discoverCases();
|
||||
|
||||
describe("generated MSW response mocks", () => {
|
||||
// Date generators are relative to the current time unless a reference date
|
||||
// is set, which would make a run depend on the moment it starts.
|
||||
beforeAll(() => {
|
||||
faker.setDefaultRefDate(fixedReferenceDate);
|
||||
});
|
||||
|
||||
it("discovers a response factory for every generated mock module", () => {
|
||||
expect(Object.keys(mockModules).length).toBeGreaterThan(0);
|
||||
const covered = new Set(cases.map((item) => item.file));
|
||||
@@ -111,24 +122,28 @@ describe("generated MSW response mocks", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it.each(cases)("$factoryName returns a valid $schemaName", ({ factory, schema }) => {
|
||||
const failures: string[] = [];
|
||||
for (const seed of seeds) {
|
||||
faker.seed(seed);
|
||||
const mock = factory();
|
||||
const result = schema.safeParse(mock);
|
||||
if (result.success) {
|
||||
continue;
|
||||
it.each(cases)(
|
||||
"$factoryName returns a valid $schemaName",
|
||||
({ factory, schema }) => {
|
||||
const failures: string[] = [];
|
||||
for (const seed of seeds) {
|
||||
faker.seed(seed);
|
||||
const mock = factory();
|
||||
const result = schema.safeParse(mock);
|
||||
if (result.success) {
|
||||
continue;
|
||||
}
|
||||
for (const issue of result.error.issues) {
|
||||
const path = issue.path.length > 0 ? issue.path.join(".") : "(root)";
|
||||
failures.push(
|
||||
`seed ${seed}: ${path}: ${issue.message}; value ${describeValue(valueAt(mock, issue.path))}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const issue of result.error.issues) {
|
||||
const path = issue.path.length > 0 ? issue.path.join(".") : "(root)";
|
||||
failures.push(
|
||||
`seed ${seed}: ${path}: ${issue.message}; value ${describeValue(valueAt(mock, issue.path))}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(failures).toEqual([]);
|
||||
});
|
||||
expect(failures).toEqual([]);
|
||||
},
|
||||
mockCaseTimeoutMs,
|
||||
);
|
||||
});
|
||||
|
||||
describe("fakeFromPattern", () => {
|
||||
|
||||
Reference in new issue
Block a user