feat(matches): add the candidate match screen with expandable explanations

This commit is contained in:
shira committed 2026-10-09 13:55:00 +03:00
1 parent 0b11021b16
commit 28337d84cb
50 files changed
+4834 -37

No files matched your search

@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import { appliedFiltersOf, describeAppliedFilters, filtersFromRequest } from "./applied-filters";
import { matchModelFixture, needId } from "./match.fixtures";
describe("applied filters", () => {
it("lists nothing for a search without filters", () => {
expect(appliedFiltersOf(matchModelFixture().source, undefined)).toEqual([]);
});
it("labels declared and confirmed grades as separate filters", () => {
const items = describeAppliedFilters(
filtersFromRequest({
specialization: "backend",
confirmed_grade: "senior",
declared_grade: "middle",
confirmation_status: "confirmed",
stack: ["go", "kafka"],
conditions: { work_formats: ["remote", "hybrid"], salary_compatibility: "compatible" },
}),
);
expect(items).toEqual([
{ label: "Специализация", value: "Backend" },
{ label: "Подтвержденный грейд", value: "Senior" },
{ label: "Статус подтверждения", value: "только подтвержденный грейд" },
{ label: "Заявленный грейд (не подтверждение)", value: "Middle" },
{ label: "Технологии в карточке (нужны все)", value: "Go, Kafka" },
{ label: "Формат работы (достаточно одного общего)", value: "Удаленно, Гибридно" },
{ label: "Зарплатные ожидания", value: "Ожидания совместимы" },
]);
});
it("reads the echoed filters of a bank result and the sent filters of a need result", () => {
const bank = matchModelFixture({
source: {
kind: "bank",
filters: {
specialization: "network_engineer",
confirmed_grade: null,
confirmed_category: { specialization: "backend", grade: "middle" },
confirmation_status: null,
declared_grade: null,
stack: null,
conditions: null,
},
},
});
expect(appliedFiltersOf(bank.source, { specialization: "qa" })).toEqual([
{ label: "Специализация", value: "Сетевое администрирование" },
{ label: "Подтвержденная категория", value: "Backend, Middle" },
]);
const need = matchModelFixture({
source: { kind: "need", need_id: needId, requirements_version: 2 },
});
expect(appliedFiltersOf(need.source, { specialization: "qa" })).toEqual([
{ label: "Специализация", value: "Тестирование" },
]);
});
});
@@ -0,0 +1,104 @@
import type { MatchSearchFilters } from "../../../shared/api/schemas";
import type { MatchSearchSourceModel } from "./adapter";
import {
gradeLabels,
salaryCompatibilityLabels,
specializationLabels,
stackLabels,
workFormatLabels,
} from "./labels";
type BankSource = Extract<MatchSearchSourceModel, { kind: "bank" }>;
/** Filters in the normalized shape of a bank search result. */
export type AppliedFiltersModel = BankSource["filters"];
/** One line of the "current filters" list: what is filtered and by which value. */
export type AppliedFilterItem = { label: string; value: string };
/** Normalizes the filters of a request, so a need search and a bank search read alike. */
export function filtersFromRequest(filters: MatchSearchFilters | undefined): AppliedFiltersModel {
const conditions = filters?.conditions;
return {
specialization: filters?.specialization ?? null,
confirmedGrade: filters?.confirmed_grade ?? null,
confirmedCategory: filters?.confirmed_category ?? null,
confirmationStatus: filters?.confirmation_status ?? null,
declaredGrade: filters?.declared_grade ?? null,
stack: filters?.stack ? [...filters.stack] : null,
conditions: conditions
? {
workFormats: conditions.work_formats ? [...conditions.work_formats] : null,
salaryCompatibility: conditions.salary_compatibility ?? null,
}
: null,
};
}
/**
* Lists the filters that narrowed the result. Confirmed and declared grades
* are separate lines so a declaration is never read as a confirmation.
*/
export function describeAppliedFilters(filters: AppliedFiltersModel): AppliedFilterItem[] {
const items: AppliedFilterItem[] = [];
if (filters.specialization) {
items.push({ label: "Специализация", value: specializationLabels[filters.specialization] });
}
if (filters.confirmedGrade) {
items.push({ label: "Подтвержденный грейд", value: gradeLabels[filters.confirmedGrade] });
}
if (filters.confirmedCategory) {
items.push({
label: "Подтвержденная категория",
value: `${specializationLabels[filters.confirmedCategory.specialization]}, ${gradeLabels[filters.confirmedCategory.grade]}`,
});
}
if (filters.confirmationStatus) {
items.push({
label: "Статус подтверждения",
value:
filters.confirmationStatus === "confirmed"
? "только подтвержденный грейд"
: "только грейд не подтвержден",
});
}
if (filters.declaredGrade) {
items.push({
label: "Заявленный грейд (не подтверждение)",
value: gradeLabels[filters.declaredGrade],
});
}
if (filters.stack && filters.stack.length > 0) {
items.push({
label: "Технологии в карточке (нужны все)",
value: filters.stack.map((tag) => stackLabels[tag]).join(", "),
});
}
if (filters.conditions?.workFormats && filters.conditions.workFormats.length > 0) {
items.push({
label: "Формат работы (достаточно одного общего)",
value: filters.conditions.workFormats.map((format) => workFormatLabels[format]).join(", "),
});
}
if (filters.conditions?.salaryCompatibility) {
items.push({
label: "Зарплатные ожидания",
value: salaryCompatibilityLabels[filters.conditions.salaryCompatibility],
});
}
return items;
}
/**
* The filters of a result. A bank result echoes its normalized filters; a
* need result does not, so the filters of the request that produced it are
* used instead.
*/
export function appliedFiltersOf(
source: MatchSearchSourceModel,
sentFilters: MatchSearchFilters | undefined,
): AppliedFilterItem[] {
return describeAppliedFilters(
source.kind === "bank" ? source.filters : filtersFromRequest(sentFilters),
);
}
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";
import { ApiRequestError } from "../../../shared/api";
import { describeCardFailure } from "./card-failure";
import { formatRetryAfter } from "./retry-after";
function failure(status: number, retryAfterSeconds?: number) {
return new ApiRequestError({
status,
code: status === 429 ? "rate_limited" : "not_found",
title: "problem",
retryAfterSeconds,
});
}
describe("card read failures", () => {
it("shows the Retry-After of a quota refusal", () => {
expect(describeCardFailure(failure(429, 90))).toMatchObject({
kind: "error",
title: "Квота просмотров карточек исчерпана",
description: expect.stringContaining("через 2 мин"),
});
});
it("does not invent a waiting time when the server named none", () => {
const description = describeCardFailure(failure(429))?.description ?? "";
expect(description).toContain("не назвал время");
expect(description).not.toContain("через");
});
it("answers a 404 with one wording that names no hidden case", () => {
const result = describeCardFailure(failure(404));
expect(result?.kind).toBe("forbidden");
expect(result?.description).toContain("Причина не раскрывается");
});
it("leaves other failures to the shared states", () => {
expect(describeCardFailure(failure(500))).toBeNull();
expect(describeCardFailure(new Error("boom"))).toBeNull();
});
it("formats waiting times by magnitude", () => {
expect(formatRetryAfter(undefined)).toBeNull();
expect(formatRetryAfter(0)).toBe("можно повторить сейчас");
expect(formatRetryAfter(45)).toBe("через 45 с");
expect(formatRetryAfter(61)).toBe("через 2 мин");
expect(formatRetryAfter(3600)).toBe("через 1 ч");
expect(formatRetryAfter(3601)).toBe("через 2 ч");
});
});
@@ -0,0 +1,37 @@
import { ApiRequestError } from "../../../shared/api";
import { formatRetryAfter } from "./retry-after";
export type CardFailure = {
kind: "error" | "forbidden";
title: string;
description: string;
};
/**
* Explains a failed card or evidence read in terms of the contract. A 429
* carries the server's Retry-After when it sent one; a 404 stands for every
* hidden case at once, so the screen names none of them. Any other failure
* returns null and is shown by the shared error and forbidden states.
*/
export function describeCardFailure(error: unknown): CardFailure | null {
if (!(error instanceof ApiRequestError)) return null;
if (error.status === 429) {
const wait = formatRetryAfter(error.retryAfterSeconds);
return {
kind: "error",
title: "Квота просмотров карточек исчерпана",
description: wait
? `Новые карточки можно открыть ${wait}. Уже просмотренные кандидаты квоту не расходуют.`
: "Сервер не назвал время, когда квота обновится. Уже просмотренные кандидаты квоту не расходуют.",
};
}
if (error.status === 404) {
return {
kind: "forbidden",
title: "Карточка сейчас недоступна",
description:
"Кандидат мог закрыть публикацию или скрыть профиль от компании, либо карточка не проходит проверки приватности. Причина не раскрывается. Повторите поиск, чтобы увидеть актуальную выдачу.",
};
}
return null;
}
@@ -0,0 +1,94 @@
import type {
AnonymousCardContent,
EvidenceSkillCode,
OrganizationEvidence,
} from "../../../shared/api/schemas";
import type { TrustLevelValue } from "../../../shared/ui";
import {
experienceBandLabels,
gradeLabels,
salaryCompatibilityLabels,
specializationLabels,
stackLabels,
strengthLabels,
workFormatLabels,
} from "./labels";
export type CardDetails = {
categories: readonly { specialization: string; grade: string; strength: string }[] | null;
selfAssessments:
| readonly {
specialization: string;
declaredGrade: string | null;
confirmed: boolean;
}[]
| null;
stack: readonly string[] | null;
experience: string | null;
workFormats: readonly string[] | null;
salaryCompatibility: string | null;
};
/**
* Maps the full anonymous card to display strings. A null value stays null:
* the contract does not say whether the candidate withheld it or has none,
* and the screen does not guess.
*/
export function presentCard(card: AnonymousCardContent): CardDetails {
return {
categories:
card.categories?.map((category) => ({
specialization: specializationLabels[category.specialization],
grade: gradeLabels[category.grade],
strength: strengthLabels[category.strength],
})) ?? null,
selfAssessments:
card.self_assessment?.map((item) => ({
specialization: specializationLabels[item.specialization],
declaredGrade: item.declared_grade ? gradeLabels[item.declared_grade] : null,
confirmed: item.confirmation_status === "confirmed",
})) ?? 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 type EvidenceFact = {
title: string;
trust: TrustLevelValue;
trustLabel: string;
observedYear: number;
basisLabel: string;
calibrationLabel: string;
};
const skillLabels: Readonly<Record<EvidenceSkillCode, string>> = {
...specializationLabels,
...stackLabels,
};
const trustViews: Readonly<Record<number, { level: TrustLevelValue; label: string }>> = {
0: { level: "claimed", label: "Заявлено, не подтверждено отдельно" },
1: { level: "partial", label: "Онлайн-результат без подтверждения личности" },
2: { level: "confirmed", label: "Результат привязан к подтвержденной личности" },
3: { level: "confirmed", label: "Очная проверка" },
};
/** Facts of the evidence section as the server lists them, with its basis and calibration. */
export function presentEvidence(evidence: OrganizationEvidence): EvidenceFact[] {
return evidence.items.map((fact) => {
const trust = trustViews[fact.trust] ?? trustViews[0]!;
return {
title: `${skillLabels[fact.skill]}: ${gradeLabels[fact.grade]}`,
trust: trust.level,
trustLabel: trust.label,
observedYear: fact.observed_year,
basisLabel: "Синтетическая демонстрация, не проверенное измерение",
calibrationLabel: "Пороги не откалиброваны",
};
});
}
@@ -0,0 +1,81 @@
import { describe, expect, it } from "vitest";
import { componentRows, evidenceRows, formatScore, otherUnknowns } from "./explanation";
import { matchModelFixture } from "./match.fixtures";
function cardAt(index: number) {
const card = matchModelFixture().cards[index];
if (!card) throw new Error("Fixture card is missing.");
return card;
}
describe("match explanation", () => {
it("formats scores exactly as the server sent them", () => {
expect(formatScore(0.5)).toBe("0,50");
expect(formatScore(0.853333)).toBe("0,853333");
expect(formatScore(0)).toBe("0,00");
});
it("lists every component of a confirmed entry with its neutral value and reason", () => {
const rows = componentRows(cardAt(0));
const byKey = Object.fromEntries(rows.map((row) => [row.key, row]));
expect(rows.map((row) => row.key)).toEqual([
"fit",
"coverage",
"domain",
"semantics",
"percentile",
"competition",
"freshness",
"responsiveness",
"rank",
]);
expect(byKey.coverage).toMatchObject({ value: 0.853333, display: "0,853333", neutral: false });
expect(byKey.semantics).toMatchObject({ value: 0.5, neutral: true });
expect(byKey.semantics?.note).toContain("смысловой анализ недоступен");
expect(byKey.freshness?.note).toContain("нет истории для оценки свежести");
expect(byKey.rank).toMatchObject({ value: 0.61, neutral: false, note: null });
});
it("states that a missing percentile has no value instead of inventing one", () => {
const percentile = componentRows(cardAt(0)).find((row) => row.key === "percentile");
expect(percentile).toMatchObject({ value: null, display: "Нет значения", neutral: true });
expect(percentile?.note).toContain("меньше 30 человек");
const notComputed = componentRows(cardAt(1)).find((row) => row.key === "percentile");
expect(notComputed?.note).toContain("пока не рассчитывается");
});
it("explains a zero competition value as neither a penalty nor an unknown", () => {
const competition = componentRows(cardAt(0)).find((row) => row.key === "competition");
expect(competition).toMatchObject({ value: 0, neutral: false });
expect(competition?.note).toBe("Вклада от соревнований нет. Это не штраф.");
});
it("shows only Fit and Cov for an unconfirmed entry and lists its unknown assessment", () => {
const network = cardAt(2);
expect(componentRows(network).map((row) => row.key)).toEqual(["fit", "coverage"]);
expect(otherUnknowns(network)).toEqual([
{
component: "Результат проверки",
reason: "для этой специализации нет подтвержденного результата",
},
]);
});
it("does not repeat unknowns that a score row already explains", () => {
expect(otherUnknowns(cardAt(0))).toEqual([]);
expect(otherUnknowns(cardAt(1))).toEqual([
{ component: "Опыт", reason: "значения нет в карточке, доступной компании" },
]);
});
it("keeps the server order of the templated sources and gaps", () => {
expect(evidenceRows(cardAt(2)).map((row) => [row.label, row.stateLabel])).toEqual([
["Заявленный грейд", "Только заявлено кандидатом"],
["Обязательные навыки", "Пробел: подтверждения нет"],
]);
});
});
@@ -0,0 +1,159 @@
import type { MatchUnknownComponent } from "../../../shared/api/schemas";
import type { MatchCardModel } from "./adapter";
import {
evidenceCodeLabels,
evidenceStateLabels,
unknownComponentLabels,
unknownReasonLabels,
} from "./labels";
const scoreFormat = new Intl.NumberFormat("ru-RU", {
minimumFractionDigits: 2,
maximumFractionDigits: 6,
});
/** Formats a server score exactly as sent: no rounding beyond the six decimals the server uses. */
export function formatScore(value: number): string {
return scoreFormat.format(value);
}
export type ComponentKey =
| "fit"
| "coverage"
| "domain"
| "semantics"
| "percentile"
| "competition"
| "freshness"
| "responsiveness"
| "rank";
export type ComponentRow = {
key: ComponentKey;
label: string;
/** The score the server returned, or null when it returned no value. */
value: number | null;
/** Text shown in place of the value: the formatted score, or a statement that none exists. */
display: string;
/** True when the server names this component as unknown and the value is a neutral stand-in. */
neutral: boolean;
/** Explanation of a neutral, missing, or zero value; null for an ordinary measured value. */
note: string | null;
};
function describeUnknownReason(flag: MatchCardModel["unknownFlags"][number]): string {
return unknownReasonLabels[flag.reason];
}
function flagFor(card: MatchCardModel, component: MatchUnknownComponent) {
return card.unknownFlags.find((flag) => flag.component === component);
}
function scoreRow(
card: MatchCardModel,
key: ComponentKey,
label: string,
value: number,
flagComponent?: MatchUnknownComponent,
): ComponentRow {
const flag = flagComponent ? flagFor(card, flagComponent) : undefined;
return {
key,
label,
value,
display: formatScore(value),
neutral: flag !== undefined,
note: flag ? `Нейтральное значение, не измерено: ${describeUnknownReason(flag)}.` : null,
};
}
/**
* Rows of the explanation, built only from the components the server
* returned. A confirmed entry shows every component; an unconfirmed entry
* shows only Fit and Cov, because the server computes nothing else for it.
* Nothing is derived on the client: a missing percentile stays a statement
* that no value exists.
*/
export function componentRows(card: MatchCardModel): ComponentRow[] {
const fit = scoreRow(card, "fit", "Соответствие работе (Fit)", card.components.fit);
const coverage = scoreRow(card, "coverage", "Покрытие навыков (Cov)", card.components.coverage);
if (card.group === "unconfirmed") return [fit, coverage];
const components = card.components;
const percentileFlag = flagFor(card, "percentile");
const percentile: ComponentRow =
components.percentile === null
? {
key: "percentile",
label: "Перцентиль среди сопоставимых",
value: null,
display: "Нет значения",
neutral: true,
note: percentileFlag
? `Перцентиль не показывается: ${describeUnknownReason(percentileFlag)}. В ранжировании использовано нейтральное значение.`
: "Сервер не вернул перцентиль.",
}
: scoreRow(card, "percentile", "Перцентиль среди сопоставимых", components.percentile);
const competition: ComponentRow = {
...scoreRow(card, "competition", "Соревновательный вклад (V)", components.competition),
note: components.competition === 0 ? "Вклада от соревнований нет. Это не штраф." : null,
};
return [
fit,
coverage,
scoreRow(card, "domain", "Предметная область (Dom)", components.domain, "domain"),
scoreRow(card, "semantics", "Смысловая близость (Sem)", components.semantics, "semantics"),
percentile,
competition,
scoreRow(card, "freshness", "Свежесть (Fr)", components.freshness, "freshness"),
scoreRow(
card,
"responsiveness",
"Своевременность ответа (Rsp)",
components.responsiveness,
"responsiveness",
),
scoreRow(card, "rank", "Итоговый балл внутри группы (S)", components.rankScore),
];
}
export type UnknownItem = { component: string; reason: string };
const scoreComponents: ReadonlySet<MatchUnknownComponent> = new Set([
"semantics",
"percentile",
"freshness",
"responsiveness",
"domain",
]);
/**
* Unknown flags that no score row already explains: missing card values and
* the missing confirmation. They are listed by component and bounded reason.
*/
export function otherUnknowns(card: MatchCardModel): UnknownItem[] {
return card.unknownFlags
.filter((flag) => card.group === "unconfirmed" || !scoreComponents.has(flag.component))
.map((flag) => ({
component: unknownComponentLabels[flag.component],
reason: describeUnknownReason(flag),
}));
}
export type EvidenceRow = {
code: string;
state: "supports" | "partial" | "gap" | "declared_only";
label: string;
stateLabel: string;
};
/** The server's templated explanation, one row per evidence item, in server order. */
export function evidenceRows(card: MatchCardModel): EvidenceRow[] {
return card.evidenceSummary.map((item) => ({
code: item.code,
state: item.state,
label: evidenceCodeLabels[item.code],
stateLabel: evidenceStateLabels[item.state],
}));
}
+131
View File
@@ -0,0 +1,131 @@
import type {
CandidateExperienceBand,
CandidateSalaryCompatibility,
GradeCode,
MatchEvidenceCode,
MatchEvidenceState,
MatchSearchStackTag,
MatchStrength,
MatchUnknownComponent,
MatchUnknownReason,
SpecializationCode,
WorkFormat,
} from "../../../shared/api/schemas";
import type { MatchGroup } from "./adapter";
/** Labels of the nine catalog specializations, in catalog order. */
export const specializationLabels: Readonly<Record<SpecializationCode, string>> = {
backend: "Backend",
frontend: "Frontend",
mobile: "Мобильная разработка",
network_engineer: "Сетевое администрирование",
devops_sre: "DevOps/SRE",
data_analyst: "Аналитика данных",
ds_ml: "Data Science и машинное обучение",
information_security: "Информационная безопасность",
qa: "Тестирование",
};
export const specializationCodes = Object.keys(specializationLabels) as SpecializationCode[];
export const gradeLabels: Readonly<Record<GradeCode, string>> = {
intern: "Стажер",
junior: "Junior",
middle: "Middle",
senior: "Senior",
};
export const gradeCodes = Object.keys(gradeLabels) as GradeCode[];
/** The three result groups in the order the screen shows them. */
export const matchGroupOrder = ["main", "near", "unconfirmed"] as const satisfies MatchGroup[];
export const groupLabels: Readonly<Record<MatchGroup, string>> = {
main: "Подтвержденные",
near: "Близкие варианты",
unconfirmed: "Грейд не подтвержден",
};
export const groupDescriptions: Readonly<Record<MatchGroup, string>> = {
main: "Грейд в этой специализации подтвержден проверкой, обязательные навыки покрыты.",
near: "Грейд подтвержден, но один из обязательных навыков покрыт слабо.",
unconfirmed:
"Кандидат назвал специализацию и грейд сам, подтвержденной категории нет. Приглашение доступно.",
};
export const strengthLabels: Readonly<Record<MatchStrength, string>> = {
standard: "Стандартное подтверждение",
strong: "Сильное подтверждение",
};
export const stackLabels: Readonly<Record<MatchSearchStackTag, string>> = {
go: "Go",
postgresql: "PostgreSQL",
kafka: "Kafka",
docker: "Docker",
};
export const stackCodes = Object.keys(stackLabels) as MatchSearchStackTag[];
export const workFormatLabels: Readonly<Record<WorkFormat, string>> = {
remote: "Удаленно",
office: "В офисе",
hybrid: "Гибридно",
};
export const workFormatCodes = Object.keys(workFormatLabels) as WorkFormat[];
export 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 года и больше",
};
export const salaryCompatibilityLabels: Readonly<Record<CandidateSalaryCompatibility, string>> = {
compatible: "Ожидания совместимы",
not_compatible: "Ожидания не совпадают",
};
export const evidenceCodeLabels: Readonly<Record<MatchEvidenceCode, string>> = {
confirmed_category: "Подтвержденная категория",
required_skill_evidence: "Обязательные навыки",
desired_skill_evidence: "Желательные навыки",
domain_alignment: "Предметная область",
task_alignment: "Рабочие задачи",
work_conditions_match: "Условия работы",
salary_compatibility: "Зарплатные ожидания",
declared_grade: "Заявленный грейд",
};
export const evidenceStateLabels: Readonly<Record<MatchEvidenceState, string>> = {
supports: "Подтверждено",
partial: "Подтверждено частично",
gap: "Пробел: подтверждения нет",
declared_only: "Только заявлено кандидатом",
};
export const unknownComponentLabels: Readonly<Record<MatchUnknownComponent, string>> = {
semantics: "Смысловая близость",
percentile: "Перцентиль",
assessment: "Результат проверки",
freshness: "Свежесть",
responsiveness: "Своевременность ответа",
experience_band: "Опыт",
work_formats: "Форматы работы",
salary_compatibility: "Зарплатные ожидания",
domain: "Предметная область",
};
export const unknownReasonLabels: Readonly<Record<MatchUnknownReason, string>> = {
ml_unavailable: "смысловой анализ недоступен",
cohort_below_30: "сопоставимая группа меньше 30 человек, перцентиль не показывается",
no_confirmation_for_specialization: "для этой специализации нет подтвержденного результата",
not_in_public_card: "значения нет в карточке, доступной компании",
need_field_unconfirmed: "соответствующее поле потребности не подтверждено",
no_freshness_history: "нет истории для оценки свежести",
no_response_history: "нет истории ответов",
percentile_not_computed: "перцентиль пока не рассчитывается",
};
@@ -0,0 +1,166 @@
import { MatchSearchResponse, type MatchSearchResponseOutput } from "../../../shared/api/schemas";
import { matchSearchFromTransport, type MatchSearchModel } from "./adapter";
/*
* Contract-shaped search results for tests. They are inputs, not evidence
* that the backend produces the same values.
*/
export const backendHandle = "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
export const nearHandle = "cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
export const unconfirmedHandle = "cv1_CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC";
export const needId = "4d3a4a1b-4f60-44c1-9dc2-6c8e6c9d4c11";
const bankFilters = {
specialization: null,
confirmed_grade: null,
confirmed_category: null,
confirmation_status: null,
declared_grade: null,
stack: null,
conditions: null,
};
/**
* Three groups. The first candidate is confirmed in Backend and unconfirmed in
* Networks, so one handle sits in two groups under two specializations.
*/
export function matchResponseFixture(
overrides: Partial<MatchSearchResponseOutput> = {},
): MatchSearchResponseOutput {
return MatchSearchResponse.parse({
source: { kind: "bank", filters: bankFilters },
groups: {
main: [
{
candidate_handle: backendHandle,
specialization: "backend",
confirmation_status: "confirmed",
declared_grade: "senior",
category: { specialization: "backend", grade: "middle" },
strength: "strong",
public_context: {
stack: ["go", "postgresql"],
experience_band: "3_6",
work_formats: ["remote"],
salary_compatibility: "compatible",
},
evidence_summary: [
{ code: "confirmed_category", state: "supports" },
{ code: "required_skill_evidence", state: "supports" },
{ code: "desired_skill_evidence", state: "declared_only" },
],
components: {
fit: 0.7125,
coverage: 0.853333,
domain: 0.5,
semantics: 0.5,
percentile: null,
competition: 0,
freshness: 0.5,
responsiveness: 0.5,
rank_score: 0.61,
},
unknown_flags: [
{ component: "semantics", reason: "ml_unavailable" },
{ component: "percentile", reason: "cohort_below_30" },
{ component: "domain", reason: "need_field_unconfirmed" },
{ component: "freshness", reason: "no_freshness_history" },
{ component: "responsiveness", reason: "no_response_history" },
],
},
],
near: [
{
candidate_handle: nearHandle,
specialization: "backend",
confirmation_status: "confirmed",
declared_grade: null,
category: { specialization: "backend", grade: "junior" },
strength: "standard",
public_context: {
stack: null,
experience_band: null,
work_formats: null,
salary_compatibility: null,
},
evidence_summary: [
{ code: "confirmed_category", state: "supports" },
{ code: "required_skill_evidence", state: "partial" },
],
components: {
fit: 0.4,
coverage: 0.18,
domain: 0.5,
semantics: 0.5,
percentile: null,
competition: 0,
freshness: 0.5,
responsiveness: 0.5,
rank_score: 0.31,
},
unknown_flags: [
{ component: "percentile", reason: "percentile_not_computed" },
{ component: "experience_band", reason: "not_in_public_card" },
],
},
],
unconfirmed: [
{
candidate_handle: backendHandle,
specialization: "network_engineer",
confirmation_status: "unconfirmed",
declared_grade: "junior",
category: null,
strength: null,
public_context: {
stack: ["docker"],
experience_band: "3_6",
work_formats: ["remote", "hybrid"],
salary_compatibility: "compatible",
},
evidence_summary: [
{ code: "declared_grade", state: "declared_only" },
{ code: "required_skill_evidence", state: "gap" },
],
components: { fit: 0.51, coverage: 0.38 },
unknown_flags: [
{ component: "assessment", reason: "no_confirmation_for_specialization" },
],
},
{
candidate_handle: unconfirmedHandle,
specialization: "backend",
confirmation_status: "unconfirmed",
declared_grade: null,
category: null,
strength: null,
public_context: {
stack: [],
experience_band: null,
work_formats: [],
salary_compatibility: null,
},
evidence_summary: [],
components: { fit: 0.2, coverage: 0 },
unknown_flags: [
{ component: "assessment", reason: "no_confirmation_for_specialization" },
],
},
],
},
truncated: false,
...overrides,
});
}
export function matchModelFixture(overrides: Partial<MatchSearchResponseOutput> = {}) {
return matchSearchFromTransport(matchResponseFixture(overrides));
}
export function emptyMatchModelFixture(truncated = false): MatchSearchModel {
return matchModelFixture({
groups: { main: [], near: [], unconfirmed: [] },
truncated,
});
}
@@ -0,0 +1,13 @@
/**
* Human wording of a Retry-After value in seconds. Returns null when the
* server gave none, so the screen never invents a waiting time.
*/
export function formatRetryAfter(seconds: number | undefined): string | null {
if (seconds === undefined) return null;
if (seconds <= 0) return "можно повторить сейчас";
if (seconds < 60) return `через ${seconds} с`;
const minutes = Math.ceil(seconds / 60);
if (minutes < 60) return `через ${minutes} мин`;
const hours = Math.ceil(minutes / 60);
return `через ${hours} ч`;
}
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import {
allSpecializationsView,
cardsForView,
matchCardKey,
specializationsInResult,
} from "./views";
import { backendHandle, matchModelFixture } from "./match.fixtures";
describe("specialization views", () => {
it("lists the specializations of the result in catalog order", () => {
expect(specializationsInResult(matchModelFixture().cards)).toEqual([
"backend",
"network_engineer",
]);
});
it("shows one specialization of a candidate without borrowing the other's confirmation", () => {
const { cards } = matchModelFixture();
const backend = cardsForView(cards, "backend").filter(
(card) => card.candidateHandle === backendHandle,
);
const networks = cardsForView(cards, "network_engineer");
expect(backend.map((card) => [card.group, card.confirmationStatus])).toEqual([
["main", "confirmed"],
]);
expect(networks.map((card) => [card.group, card.confirmationStatus])).toEqual([
["unconfirmed", "unconfirmed"],
]);
expect(networks[0]?.category).toBeNull();
expect(cardsForView(cards, allSpecializationsView)).toHaveLength(cards.length);
});
it("keys an entry by candidate and specialization", () => {
const keys = matchModelFixture().cards.map(matchCardKey);
expect(new Set(keys).size).toBe(keys.length);
});
});
@@ -0,0 +1,38 @@
import type { SpecializationCode } from "../../../shared/api/schemas";
import type { MatchCardModel } from "./adapter";
import { specializationCodes } from "./labels";
/** The view that shows every specialization, each entry labelled with its own. */
export const allSpecializationsView = "all";
export type SpecializationView = typeof allSpecializationsView | SpecializationCode;
/** Stable key of one entry: one candidate under one specialization. */
export function matchCardKey(card: Pick<MatchCardModel, "candidateHandle" | "specialization">) {
return `${card.candidateHandle}:${card.specialization}`;
}
/** Specializations that occur in the result, in catalog order. */
export function specializationsInResult(cards: readonly MatchCardModel[]): SpecializationCode[] {
const present = new Set(cards.map((card) => card.specialization));
return specializationCodes.filter((code) => present.has(code));
}
/**
* Entries of one specialization view. Selecting a specialization only hides
* the others; the server order inside each group is kept and no entry
* borrows a confirmation from another specialization.
*/
export function cardsForView(
cards: readonly MatchCardModel[],
view: SpecializationView,
): MatchCardModel[] {
return view === allSpecializationsView
? [...cards]
: cards.filter((card) => card.specialization === view);
}
/** Short display form of an opaque handle; the full handle is used for requests only. */
export function shortHandle(handle: string): string {
return `${handle.slice(0, 12)}...`;
}