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

+98
View File
@@ -0,0 +1,98 @@
import { useQuery } from "@tanstack/react-query";
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
import { getOrganizationCandidateEvidence } from "../../../shared/api/endpoints/evidence/evidence";
import { getOrganizationCandidateCard } from "../../../shared/api/endpoints/privacy/privacy";
import {
AnonymousCardContent as anonymousCardSchema,
OrganizationEvidence as organizationEvidenceSchema,
type AnonymousCardContent,
type OrganizationEvidence,
} from "../../../shared/api/schemas";
function invalidResponse(): ApiRequestError {
return new ApiRequestError({
status: 200,
code: invalidResponseCode,
title: "The response does not match the API contract.",
});
}
/** Reads the current anonymous card of one search result and checks it against the contract. */
export async function readCandidateCard(
organizationId: string,
candidateHandle: string,
signal: AbortSignal | undefined = undefined,
): Promise<AnonymousCardContent> {
const parsed = anonymousCardSchema.safeParse(
await getOrganizationCandidateCard(organizationId, candidateHandle, signal ? { signal } : {}),
);
if (!parsed.success) throw invalidResponse();
return parsed.data;
}
/** Reads the permitted evidence of one candidate card and checks it against the contract. */
export async function readCandidateEvidence(
organizationId: string,
candidateHandle: string,
signal: AbortSignal | undefined = undefined,
): Promise<OrganizationEvidence> {
const parsed = organizationEvidenceSchema.safeParse(
await getOrganizationCandidateEvidence(
organizationId,
candidateHandle,
signal ? { signal } : {},
),
);
if (!parsed.success) throw invalidResponse();
return parsed.data;
}
/**
* Private keys of the card reads: scoped to the account and the organization,
* dropped as soon as nothing shows them, and never refetched in the background,
* because every read is an entry in the candidate's access history.
*/
export const matchCardQueryKeys = {
card: (accountId: string, organizationId: string, candidateHandle: string) =>
["match-card", accountId, organizationId, candidateHandle] as const,
evidence: (accountId: string, organizationId: string, candidateHandle: string) =>
["match-card-evidence", accountId, organizationId, candidateHandle] as const,
};
const readOnceOptions = {
gcTime: 0,
staleTime: Number.POSITIVE_INFINITY,
refetchOnMount: false,
refetchOnWindowFocus: false,
retry: false,
} as const;
/** Loads the full card of a result when `enabled`; a 404 or 429 is returned as the query error. */
export function useMatchCandidateCard(
accountId: string,
organizationId: string,
candidateHandle: string,
enabled: boolean,
) {
return useQuery({
queryKey: matchCardQueryKeys.card(accountId, organizationId, candidateHandle),
queryFn: ({ signal }) => readCandidateCard(organizationId, candidateHandle, signal),
enabled,
...readOnceOptions,
});
}
/** Loads the evidence section of a card; the server refuses it for a card without categories. */
export function useMatchCandidateEvidence(
accountId: string,
organizationId: string,
candidateHandle: string,
enabled: boolean,
) {
return useQuery({
queryKey: matchCardQueryKeys.evidence(accountId, organizationId, candidateHandle),
queryFn: ({ signal }) => readCandidateEvidence(organizationId, candidateHandle, signal),
enabled,
...readOnceOptions,
});
}
@@ -0,0 +1,54 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { matchResponseFixture } from "../model/match.fixtures";
import { searchMatches } from "./search";
afterEach(() => {
vi.unstubAllGlobals();
});
describe("searchMatches", () => {
it("posts the body with the CSRF token to the organization path and validates the answer", async () => {
const fetchMock = vi.fn(async () =>
Response.json(matchResponseFixture(), { headers: { "content-type": "application/json" } }),
);
vi.stubGlobal("fetch", fetchMock);
const result = await searchMatches(
"01928f7a-0000-7000-8000-00000000a001",
{ filters: { declared_grade: "senior" } },
"T".repeat(43),
);
expect(result.cards.map((card) => card.group)).toEqual([
"main",
"near",
"unconfirmed",
"unconfirmed",
]);
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
expect(url).toBe("/api/v1/organizations/01928f7a-0000-7000-8000-00000000a001/matches");
expect(init.method).toBe("POST");
expect(new Headers(init.headers).get("X-CSRF-Token")).toBe("T".repeat(43));
expect(JSON.parse(String(init.body))).toEqual({ filters: { declared_grade: "senior" } });
});
it("rejects an answer that carries a field outside the contract", async () => {
const withContact = {
...matchResponseFixture(),
groups: {
...matchResponseFixture().groups,
main: matchResponseFixture().groups.main.map((card) => ({ ...card, email: "a@b.test" })),
},
};
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Response.json(withContact, { headers: { "content-type": "application/json" } }),
),
);
await expect(
searchMatches("01928f7a-0000-7000-8000-00000000a001", { filters: {} }, "T".repeat(43)),
).rejects.toMatchObject({ code: "invalid_response" });
});
});
+10 -1
View File
@@ -4,11 +4,20 @@ import { matchSearchFromTransport, type MatchSearchModel } from "../model/adapte
type SearchRequestOptions = Parameters<typeof searchOrganizationMatches>[2];
/**
* Runs one search for the organization and validates the response against the
* contract. The search is a POST that charges card views, so it carries the
* CSRF token of the session and is never repeated by the client by itself.
*/
export async function searchMatches(
organizationId: string,
request: MatchSearchRequest,
csrfToken: string,
options?: SearchRequestOptions,
): Promise<MatchSearchModel> {
const response = await searchOrganizationMatches(organizationId, request, options);
const response = await searchOrganizationMatches(organizationId, request, {
...options,
headers: { ...options?.headers, "X-CSRF-Token": csrfToken },
});
return matchSearchFromTransport(response);
}
+52
View File
@@ -1,3 +1,8 @@
// Public API of the match entity: the search transport adapter, the card
// reads, the presentation of server-computed results, and the presentational
// parts of one result. The slice holds no search state; the page owns it.
export { matchCardQueryKeys, useMatchCandidateCard, useMatchCandidateEvidence } from "./api/card";
export { searchMatches } from "./api/search";
export {
matchSearchFromTransport,
@@ -13,3 +18,50 @@ export type {
MatchSearchSourceModel,
MatchUnconfirmedCardModel,
} from "./model/adapter";
export {
appliedFiltersOf,
describeAppliedFilters,
filtersFromRequest,
type AppliedFilterItem,
type AppliedFiltersModel,
} from "./model/applied-filters";
export { describeCardFailure, type CardFailure } from "./model/card-failure";
export {
presentCard,
presentEvidence,
type CardDetails,
type EvidenceFact,
} from "./model/card-presentation";
export {
componentRows,
evidenceRows,
formatScore,
otherUnknowns,
type ComponentRow,
type EvidenceRow,
} from "./model/explanation";
export {
gradeCodes,
gradeLabels,
groupDescriptions,
groupLabels,
matchGroupOrder,
specializationCodes,
specializationLabels,
stackCodes,
stackLabels,
workFormatCodes,
workFormatLabels,
} from "./model/labels";
export { formatRetryAfter } from "./model/retry-after";
export {
allSpecializationsView,
cardsForView,
matchCardKey,
shortHandle,
specializationsInResult,
type SpecializationView,
} from "./model/views";
export { CandidateCardDetails } from "./ui/candidate-card-details";
export { MatchCardView } from "./ui/match-card";
export { MatchExplanation } from "./ui/match-explanation";
@@ -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)}...`;
}
+11
View File
@@ -0,0 +1,11 @@
// Test-only entry of the match entity. Tests of the layers above import the
// contract-shaped results from here. The fixtures are inputs, not evidence
// about the backend. The lint configuration lets only test files import this
// file, so production code cannot reach it.
export {
backendHandle,
emptyMatchModelFixture,
matchModelFixture,
needId as matchFixtureNeedId,
} from "./model/match.fixtures";
@@ -0,0 +1,96 @@
.panel {
display: grid;
gap: var(--space-4);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
background: var(--color-surface);
}
.panel[hidden] {
display: none;
}
.title {
margin: 0;
font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
}
.subtitle {
margin: 0;
font-size: var(--font-size-s);
font-weight: var(--font-weight-bold);
}
.list {
display: grid;
gap: var(--space-2);
margin: 0;
padding: 0;
list-style: none;
}
.list li {
display: flex;
flex-wrap: wrap;
gap: var(--space-1) var(--space-3);
align-items: center;
min-width: 0;
overflow-wrap: anywhere;
}
.facts {
display: grid;
grid-template-columns: minmax(9rem, max-content) minmax(0, 1fr);
gap: var(--space-2) var(--space-4);
margin: 0;
}
.facts dt {
color: var(--color-text-secondary);
}
.facts dd {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.unknown,
.note {
margin: 0;
color: var(--color-text-secondary);
}
.note {
font-size: var(--font-size-s);
}
.evidence-facts {
display: grid;
grid-template-columns: minmax(7rem, max-content) minmax(0, 1fr);
gap: var(--space-1) var(--space-4);
margin: 0;
font-size: var(--font-size-s);
}
.evidence-facts dd {
margin: 0;
}
@media (width < 30rem) {
.panel {
padding: var(--space-3);
}
.facts,
.evidence-facts {
grid-template-columns: minmax(0, 1fr);
}
.facts dd + dt {
padding-block-start: var(--space-2);
}
}
@@ -0,0 +1,197 @@
import {
Button,
ErrorState,
ForbiddenState,
isAccessDenied,
LoadingState,
StatusView,
TrustLevel,
} from "../../../shared/ui";
import { useMatchCandidateCard, useMatchCandidateEvidence } from "../api/card";
import { describeCardFailure } from "../model/card-failure";
import { presentCard, presentEvidence } from "../model/card-presentation";
import styles from "./candidate-card-details.module.css";
type CandidateCardDetailsProps = {
id: string;
accountId: string;
organizationId: string;
candidateHandle: string;
/** False keeps the panel mounted but out of the page, so closing does not read the card again. */
open: boolean;
};
function ReadFailure({
error,
isRetrying,
onRetry,
fallbackTitle,
}: {
error: unknown;
isRetrying: boolean;
onRetry: () => void;
fallbackTitle: string;
}) {
const failure = describeCardFailure(error);
if (failure) {
return (
<StatusView
kind={failure.kind}
title={failure.title}
description={failure.description}
action={
failure.kind === "error" ? (
<Button variant="secondary" isBusy={isRetrying} onClick={onRetry}>
{isRetrying ? "Повторяем..." : "Повторить"}
</Button>
) : null
}
/>
);
}
if (isAccessDenied(error)) return <ForbiddenState error={error} />;
return (
<ErrorState error={error} title={fallbackTitle} isRetrying={isRetrying} onRetry={onRetry} />
);
}
/**
* The full anonymous card of one result and its evidence section, read from
* the card endpoints when the employer opens it. The card belongs to the
* whole candidate, so it lists every specialization the candidate published,
* each with its own confirmation status.
*/
export function CandidateCardDetails({
id,
accountId,
organizationId,
candidateHandle,
open,
}: CandidateCardDetailsProps) {
const card = useMatchCandidateCard(accountId, organizationId, candidateHandle, true);
const hasCategories = Boolean(card.data?.categories && card.data.categories.length > 0);
const evidence = useMatchCandidateEvidence(
accountId,
organizationId,
candidateHandle,
card.isSuccess && hasCategories,
);
const details = card.data ? presentCard(card.data) : null;
const facts = evidence.data ? presentEvidence(evidence.data) : null;
return (
<section id={id} className={styles.panel} aria-label="Карточка кандидата" hidden={!open}>
<h5 className={styles.title}>Карточка кандидата</h5>
<p className={styles.note}>
Карточка относится к кандидату целиком и без контактов. Подтверждение задается для каждой
специализации отдельно. Открытие учитывается в просмотрах, кандидат, уже показанный в этом
окне, второй раз не списывается.
</p>
{card.isPending ? <LoadingState label="Открываем карточку..." /> : null}
{card.isError ? (
<ReadFailure
error={card.error}
isRetrying={card.isFetching}
onRetry={() => void card.refetch()}
fallbackTitle="Не удалось открыть карточку"
/>
) : null}
{details ? (
<>
<section aria-label="Подтвержденные категории">
<h6 className={styles.subtitle}>Подтвержденные категории</h6>
{details.categories === null ? (
<p className={styles.unknown}>Нет значения в карточке.</p>
) : details.categories.length === 0 ? (
<p className={styles.unknown}>Подтвержденных категорий нет.</p>
) : (
<ul className={styles.list}>
{details.categories.map((category) => (
<li key={category.specialization}>
{category.specialization}: {category.grade}. {category.strength}
</li>
))}
</ul>
)}
</section>
<section aria-label="Заявленные специализации">
<h6 className={styles.subtitle}>Заявленные специализации</h6>
{details.selfAssessments === null ? (
<p className={styles.unknown}>Нет значения в карточке.</p>
) : details.selfAssessments.length === 0 ? (
<p className={styles.unknown}>Специализации не названы.</p>
) : (
<ul className={styles.list}>
{details.selfAssessments.map((item) => (
<li key={item.specialization}>
<strong>{item.specialization}</strong>
<span>
{item.declaredGrade ? `Заявлено: ${item.declaredGrade}` : "Уровень не указан"}
</span>
<TrustLevel
level={item.confirmed ? "confirmed" : "none"}
label={item.confirmed ? "Грейд подтвержден" : "Грейд не подтвержден"}
/>
</li>
))}
</ul>
)}
</section>
<dl className={styles.facts}>
<dt>Технологии</dt>
<dd>
{details.stack === null
? "Нет значения в карточке"
: details.stack.join(", ") || "Не названы"}
</dd>
<dt>Общий опыт</dt>
<dd>{details.experience ?? "Нет значения в карточке"}</dd>
<dt>Форматы работы</dt>
<dd>
{details.workFormats === null
? "Нет значения в карточке"
: details.workFormats.join(", ") || "Не названы"}
</dd>
<dt>Зарплатные ожидания</dt>
<dd>{details.salaryCompatibility ?? "Нет значения в карточке"}</dd>
</dl>
{hasCategories ? (
<section aria-label="Подтверждающие факты оценки">
<h6 className={styles.subtitle}>Подтверждающие факты оценки</h6>
{evidence.isPending ? <LoadingState label="Загружаем факты оценки..." /> : null}
{evidence.isError ? (
<ReadFailure
error={evidence.error}
isRetrying={evidence.isFetching}
onRetry={() => void evidence.refetch()}
fallbackTitle="Не удалось загрузить факты оценки"
/>
) : null}
{facts && facts.length === 0 ? (
<p className={styles.unknown}>Для категорий карточки нет видимого факта оценки.</p>
) : null}
{facts && facts.length > 0 ? (
<ul className={styles.list}>
{facts.map((fact) => (
<li key={fact.title}>
<strong>{fact.title}</strong>
<TrustLevel level={fact.trust} label={fact.trustLabel} />
<dl className={styles["evidence-facts"]}>
<dt>Год оценки</dt>
<dd>{fact.observedYear}</dd>
<dt>Основа</dt>
<dd>{fact.basisLabel}</dd>
<dt>Калибровка</dt>
<dd>{fact.calibrationLabel}</dd>
</dl>
</li>
))}
</ul>
) : null}
</section>
) : null}
</>
) : null}
</section>
);
}
@@ -0,0 +1,128 @@
.card {
display: grid;
gap: var(--space-4);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-inline-start: var(--space-1) solid var(--color-border-strong);
border-radius: var(--radius-m);
background: var(--color-surface);
}
/* The confirmed and the unconfirmed state differ in the edge style and the
* text of the badge, so the difference never relies on color alone. */
.card[data-confirmed="false"] {
border-inline-start-style: dashed;
}
.header {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-4);
align-items: baseline;
justify-content: space-between;
min-width: 0;
}
.specialization {
margin: 0;
overflow-wrap: anywhere;
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
}
.handle {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
overflow-wrap: anywhere;
}
.status {
display: flex;
flex-wrap: wrap;
gap: var(--space-1) var(--space-4);
align-items: center;
}
.facts {
display: grid;
grid-template-columns: minmax(9rem, max-content) minmax(0, 1fr);
gap: var(--space-2) var(--space-4);
margin: 0;
}
.facts dt {
color: var(--color-text-secondary);
}
.facts dd {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.unknown {
color: var(--color-text-secondary);
}
.sources {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.sources-title {
margin: 0;
font-size: var(--font-size-s);
font-weight: var(--font-weight-bold);
}
.sources ul {
display: grid;
gap: var(--space-2);
margin: 0;
padding: 0;
list-style: none;
}
.sources li {
display: flex;
flex-wrap: wrap;
gap: var(--space-1) var(--space-3);
align-items: center;
min-width: 0;
}
.source-label {
font-weight: var(--font-weight-medium);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-3);
}
.panels {
display: grid;
gap: var(--space-4);
min-width: 0;
}
@media (width < 30rem) {
.card {
padding: var(--space-3);
}
.facts {
grid-template-columns: minmax(0, 1fr);
}
.facts dd + dt {
padding-block-start: var(--space-2);
}
.actions > * {
flex: 1 1 100%;
}
}
@@ -0,0 +1,132 @@
import type { ReactNode } from "react";
import { Mono, TrustLevel, type TrustLevelValue } from "../../../shared/ui";
import type { MatchCardModel } from "../model/adapter";
import { evidenceRows, type EvidenceRow } from "../model/explanation";
import {
experienceBandLabels,
gradeLabels,
salaryCompatibilityLabels,
specializationLabels,
stackLabels,
strengthLabels,
workFormatLabels,
} from "../model/labels";
import { shortHandle } from "../model/views";
import styles from "./match-card.module.css";
const stateLevels: Readonly<Record<EvidenceRow["state"], TrustLevelValue>> = {
supports: "confirmed",
partial: "partial",
declared_only: "claimed",
gap: "none",
};
const noValue = "Нет значения в карточке";
function Unknown() {
return <span className={styles.unknown}>{noValue}</span>;
}
type MatchCardViewProps = {
card: MatchCardModel;
/** Id of the heading, so the surrounding group can label the article. */
headingId: string;
/** Buttons and links under the card facts. */
actions?: ReactNode;
/** Expandable panels under the actions. */
children?: ReactNode;
};
/**
* One search result: a candidate under one specialization. It prints the
* confirmed category and the declared grade on separate lines, the safe card
* context, and the server's templated sources and gaps. Nothing here is
* calculated: the status comes from the group and the fields of the entry.
*/
export function MatchCardView({ card, headingId, actions, children }: MatchCardViewProps) {
const confirmed = card.confirmationStatus === "confirmed";
const context = card.publicContext;
const sources = evidenceRows(card);
return (
<article className={styles.card} data-confirmed={confirmed} aria-labelledby={headingId}>
<header className={styles.header}>
<h4 id={headingId} className={styles.specialization}>
{specializationLabels[card.specialization]}
</h4>
<p className={styles.handle}>
Кандидат <Mono>{shortHandle(card.candidateHandle)}</Mono>
</p>
</header>
<div className={styles.status}>
{card.category && card.strength ? (
<TrustLevel
level="confirmed"
label={`Грейд подтвержден: ${gradeLabels[card.category.grade]}`}
/>
) : (
<TrustLevel level="none" label="Грейд не подтвержден" />
)}
</div>
<dl className={styles.facts}>
<dt>Подтвержденная категория</dt>
<dd>
{card.category && card.strength
? `${specializationLabels[card.category.specialization]}, ${gradeLabels[card.category.grade]}. ${strengthLabels[card.strength]}`
: "Нет"}
</dd>
<dt>Заявленный кандидатом грейд</dt>
<dd>{card.declaredGrade ? gradeLabels[card.declaredGrade] : "Не указан"}</dd>
<dt>Технологии</dt>
<dd>
{context.stack === null ? (
<Unknown />
) : context.stack.length === 0 ? (
"Не названы"
) : (
context.stack.map((tag) => stackLabels[tag]).join(", ")
)}
</dd>
<dt>Общий опыт</dt>
<dd>
{context.experienceBand ? experienceBandLabels[context.experienceBand] : <Unknown />}
</dd>
<dt>Форматы работы</dt>
<dd>
{context.workFormats === null ? (
<Unknown />
) : context.workFormats.length === 0 ? (
"Не названы"
) : (
context.workFormats.map((format) => workFormatLabels[format]).join(", ")
)}
</dd>
<dt>Зарплатные ожидания</dt>
<dd>
{context.salaryCompatibility ? (
salaryCompatibilityLabels[context.salaryCompatibility]
) : (
<Unknown />
)}
</dd>
</dl>
<section className={styles.sources} aria-label="Источники подтверждения и пробелы">
<h5 className={styles["sources-title"]}>Источники подтверждения и пробелы</h5>
{sources.length > 0 ? (
<ul>
{sources.map((item) => (
<li key={item.code}>
<span className={styles["source-label"]}>{item.label}</span>
<TrustLevel level={stateLevels[item.state]} label={item.stateLabel} />
</li>
))}
</ul>
) : (
<p className={styles.unknown}>Сервер не вернул пояснений по источникам.</p>
)}
</section>
{actions ? <div className={styles.actions}>{actions}</div> : null}
{children ? <div className={styles.panels}>{children}</div> : null}
</article>
);
}
@@ -0,0 +1,73 @@
.panel {
display: grid;
gap: var(--space-3);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
background: var(--color-canvas);
}
.title {
margin: 0;
font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
}
.rows {
display: grid;
grid-template-columns: minmax(10rem, max-content) minmax(0, 1fr);
gap: var(--space-2) var(--space-4);
margin: 0;
}
/* Wrapper of one term and its value; the grid lays out its children. */
.row {
display: contents;
}
.rows dt {
color: var(--color-text-secondary);
}
.rows dd {
display: flex;
flex-wrap: wrap;
gap: var(--space-1) var(--space-3);
align-items: baseline;
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.neutral {
font-size: var(--font-size-s);
color: var(--color-text-secondary);
}
.unknowns {
display: grid;
gap: var(--space-1);
margin: 0;
padding-inline-start: var(--space-5);
}
.note {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
@media (width < 30rem) {
.panel {
padding: var(--space-3);
}
.rows {
grid-template-columns: minmax(0, 1fr);
}
.row + .row dt {
padding-block-start: var(--space-2);
}
}
@@ -0,0 +1,67 @@
import { Mono } from "../../../shared/ui";
import type { MatchCardModel } from "../model/adapter";
import { componentRows, otherUnknowns } from "../model/explanation";
import styles from "./match-explanation.module.css";
type MatchExplanationProps = {
card: MatchCardModel;
/** Id that the disclosure button points at through aria-controls. */
id: string;
};
/**
* The explanation of one entry: every component exactly as the server
* returned it, the neutral values with their stated reasons, and the
* components that are unknown. The client adds no numbers, so a neutral value
* is never presented as a measurement and a missing percentile is never
* replaced by an estimate.
*/
export function MatchExplanation({ card, id }: MatchExplanationProps) {
const rows = componentRows(card);
const unknowns = otherUnknowns(card);
const unconfirmed = card.group === "unconfirmed";
return (
<section id={id} className={styles.panel} aria-label="Объяснение позиции">
<h5 className={styles.title}>Как получена позиция</h5>
<dl className={styles.rows}>
{rows.map((row) => (
<div key={row.key} className={styles.row}>
<dt>{row.label}</dt>
<dd data-component={row.key} data-neutral={row.neutral}>
<Mono strong={row.key === "rank"}>{row.display}</Mono>
{row.note ? <span className={styles.neutral}>{row.note}</span> : null}
</dd>
</div>
))}
</dl>
{unconfirmed ? (
<p className={styles.note}>
Для профиля без подтвержденного грейда считаются только Fit и Cov. Балл ранжирования,
тестовый перцентиль и подтвержденная категория не рассчитываются, а баллы разных групп не
являются одной шкалой.
</p>
) : (
<p className={styles.note}>
Баллы от 0 до 1 посчитал сервер, интерфейс их не пересчитывает. Итоговый балл сравним
только внутри своей группы.
</p>
)}
{unknowns.length > 0 ? (
<>
<h5 className={styles.title}>Что неизвестно</h5>
<ul className={styles.unknowns}>
{unknowns.map((item) => (
<li key={`${item.component}:${item.reason}`}>
{item.component}: {item.reason}.
</li>
))}
</ul>
<p className={styles.note}>
Неизвестное значение не означает отсутствие способности: нет данных, чтобы его оценить.
</p>
</>
) : null}
</section>
);
}