import type { CardAccess, CardCategory, CardField, CardPreview, CardSelfAssessment, CandidateExperienceBand, EvidenceBasis, EvidenceSkillCode, CandidateSalaryCompatibility, CandidateWorkFormat, ConsentRecord, HiddenOrganization, OrganizationEvidenceFact, PrivacySettings, Publication, PublicationUpdate, SearchStatusUpdate, } from "../../../shared/api/schemas"; import type { TrustLevelValue } from "../../../shared/ui"; export const publishableCardFields = [ "categories", "self_assessment", "stack", "experience", "work_formats", "salary_compatibility", "projects", ] as const satisfies readonly CardField[]; export type PublishableCardField = (typeof publishableCardFields)[number]; export type PublicationDraft = { state: "closed" | "published"; fields: PublishableCardField[]; expectedVersion: number; }; export type PublicationSubmission = { ok: true; body: PublicationUpdate } | { ok: false; reason: "select_field" | "c2_required" }; export type OrganizationReference = { id: string; name: string }; export type C2State = "active" | "inactive" | "checking"; export function publicationDraftFromSettings(settings: PrivacySettings): PublicationDraft { return { state: settings.publication.state, fields: editableCardFields(settings.publication.fields), expectedVersion: settings.publication.version, }; } export function buildPublicationSubmission( draft: PublicationDraft, hasActiveC2: boolean, ): PublicationSubmission { if (draft.state === "closed") { return { ok: true, body: { expected_version: draft.expectedVersion, state: "closed", fields: [], }, }; } const fields = editableCardFields(draft.fields); if (fields.length === 0) return { ok: false, reason: "select_field" }; if (!hasActiveC2) return { ok: false, reason: "c2_required" }; return { ok: true, body: { expected_version: draft.expectedVersion, state: "published", fields, }, }; } export function buildSearchStatusSubmission( settings: PrivacySettings, value: SearchStatusUpdate["value"], ): SearchStatusUpdate { return { expected_version: settings.search_status.version, value }; } export function isSamePublicationDraft(first: PublicationDraft, second: PublicationDraft): boolean { return ( first.state === second.state && first.expectedVersion === second.expectedVersion && first.fields.length === second.fields.length && first.fields.every((field, index) => field === second.fields[index]) ); } export function organizationsAvailableToHide( accessRecords: readonly CardAccess[], hiddenOrganizations: readonly HiddenOrganization[], ): OrganizationReference[] { const hiddenIds = new Set(hiddenOrganizations.map((item) => item.organization.id)); const visibleOrganizations = new Map(); for (const record of accessRecords) { const organization = record.organization; if ( !organization || hiddenIds.has(organization.id) || visibleOrganizations.has(organization.id) ) { continue; } visibleOrganizations.set(organization.id, { id: organization.id, name: organization.name, }); } return [...visibleOrganizations.values()]; } export function currentC2State( records: readonly ConsentRecord[], historyIsComplete: boolean, ): C2State { if (records.some((record) => record.purpose === "c2" && record.state === "active")) { return "active"; } return historyIsComplete ? "inactive" : "checking"; } export function hasUnsupportedPublishedFields(settings: PrivacySettings): boolean { return settings.publication.fields.some( (field) => !publishableCardFields.includes(field as PublishableCardField), ); } export const cardFieldLabels: Readonly> = { categories: "Подтвержденная категория и уровень", self_assessment: "Самооценка по направлениям", stack: "Технологии из подтвержденного профиля", experience: "Общий опыт", work_formats: "Форматы работы", salary_compatibility: "Совместимость по зарплатным ожиданиям", projects: "Проекты: название, описание и технологии", }; /** * What publishing the projects reveals. It is shown beside the choice, before * the candidate makes it, and again in the card preview. */ export const projectsPublicationWarning = { identify: "Название и описание проектов пишете вы, и по ним вас могут узнать. Не публикуйте проект, если в тексте есть имя, контакт или название работодателя. Размер группы похожих кандидатов эти тексты не скрывает: карточка с проектами может быть единственной в своем роде.", repository: "Адрес репозитория и его владелец компаниям не показываются никогда. Они видят только отметку, что публичный репозиторий проекта найден.", } as const; export const specializationLabels = { backend: "Backend", frontend: "Frontend", mobile: "Мобильная разработка", network_engineer: "Сетевое администрирование", devops_sre: "DevOps/SRE", data_analyst: "Аналитика данных", ds_ml: "Data Science и машинное обучение", information_security: "Информационная безопасность", qa: "Тестирование", } as const; const gradeLabels = { intern: "Стажер", junior: "Junior", middle: "Middle", senior: "Senior", } as const; const stackLabels = { go: "Go", postgresql: "PostgreSQL", kafka: "Kafka", docker: "Docker", } as const; const workFormatLabels: Readonly> = { remote: "Удаленно", office: "В офисе", hybrid: "Гибридно", }; const experienceBandLabels: Readonly> = { "0_1": "До 1 года", "1_3": "1-3 года", "3_6": "3-6 лет", "6_plus": "6 лет и больше", "0_3": "0-3 года", "3_plus": "3 года и больше", }; const salaryCompatibilityLabels: Readonly> = { compatible: "Ожидания совместимы", not_compatible: "Ожидания не совпадают", }; export type CategoryPresentation = { specialization: string; grade: string; strength: string; }; export type SelfAssessmentPresentation = { specialization: string; declaredGrade: string | null; /** 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; }; export type CardProjectPresentation = { title: string; description: string | null; stack: readonly string[]; repositoryVerified: boolean; }; 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; /** Published projects in the candidate's order; null when the field is not published. */ projects: readonly CardProjectPresentation[] | 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 confirmationLabelOf(category: CardCategory): string { return category.strength === "strong" ? "Сильное подтверждение" : "Стандартное подтверждение"; } function categoryPresentation(category: CardCategory): CategoryPresentation { return { specialization: specializationLabels[category.specialization], grade: gradeLabels[category.grade], strength: confirmationLabelOf(category), }; } function selfAssessmentPresentation(item: CardSelfAssessment): SelfAssessmentPresentation { 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> = { ...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> = { 0: claimedEvidence, 1: { level: "partial", label: "Онлайн-результат без подтверждения личности" }, 2: { level: "confirmed", label: "Результат привязан к подтвержденной личности" }, 3: { level: "confirmed", label: "Очная проверка" }, }; export const evidenceBasisLabels: Readonly> = { synthetic_demo: "Результат теста", }; 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], }; } 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, projects: card.projects?.map((project) => ({ title: project.title, description: project.description, stack: [...project.stack], repositoryVerified: project.repository_verified, })) ?? null, evidence: preview.evidence ? preview.evidence.items.map(evidencePresentation) : 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; 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, ): 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 : "Организация не раскрывается"; }