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

+1 -1
View File
@@ -283,7 +283,7 @@ describe("product readiness", () => {
});
it("labels the remaining cabinet scaffolds as placeholders", async () => {
for (const path of ["/candidate/invitations", "/employer/candidates"]) {
for (const path of ["/candidate/invitations", "/employer/invitations"]) {
expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач");
}
});
+2 -4
View File
@@ -6,6 +6,7 @@ import { CandidateOnboardingPage } from "../../pages/candidate-onboarding";
import { CompanyPage } from "../../pages/company";
import { PrivacyPage } from "../../pages/privacy";
import { SessionGate } from "../../entities/session";
import { MatchesPage } from "../../pages/matches";
import { NotFoundPage } from "../../pages/not-found";
import { NeedEditorPage } from "../../pages/need-editor";
import { NeedListPage } from "../../pages/needs";
@@ -125,10 +126,7 @@ export const routes: RouteObject[] = [
path: `${paths.employer.supportCases}/:caseId`,
element: <SupportCaseDetailPage />,
},
{
path: paths.employer.candidates,
element: <PlaceholderPage screen="employerCandidates" />,
},
{ path: paths.employer.candidates, element: <MatchesPage /> },
{
path: paths.employer.invitations,
element: <PlaceholderPage screen="employerInvitations" />,
+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>
);
}
@@ -0,0 +1,12 @@
// Public API of the filter-matches feature: the filter form of the candidate
// search and the conversion of its state to a search request.
export {
activeFilterCount,
buildMatchRequest,
emptyFilterDraft,
filtersFromDraft,
type MatchBasis,
type MatchFilterDraft,
} from "./model/draft";
export { MatchFilterForm } from "./ui/match-filter-form";
@@ -0,0 +1,83 @@
import { describe, expect, it } from "vitest";
import {
activeFilterCount,
buildMatchRequest,
emptyFilterDraft,
filtersFromDraft,
toggleItem,
type MatchFilterDraft,
} from "./draft";
const needId = "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80";
describe("match filter draft", () => {
it("sends an empty filter object for a bank search without filters", () => {
expect(buildMatchRequest({ mode: "bank" }, emptyFilterDraft)).toEqual({ filters: {} });
expect(activeFilterCount(emptyFilterDraft)).toBe(0);
});
it("sends only the switched-on filters and keeps declared and confirmed grades apart", () => {
const draft: MatchFilterDraft = {
...emptyFilterDraft,
specialization: "backend",
confirmedGrade: "senior",
declaredGrade: "middle",
confirmationStatus: "confirmed",
stack: ["go", "kafka"],
workFormats: ["remote"],
salaryCompatible: true,
};
expect(filtersFromDraft(draft)).toEqual({
specialization: "backend",
confirmed_grade: "senior",
confirmation_status: "confirmed",
declared_grade: "middle",
stack: ["go", "kafka"],
conditions: { work_formats: ["remote"], salary_compatibility: "compatible" },
});
expect(activeFilterCount(draft)).toBe(7);
});
it("builds a need search with its requirements version and no filters key when none are on", () => {
expect(
buildMatchRequest({ mode: "need", needId, requirementsVersion: 3 }, emptyFilterDraft),
).toEqual({ need_id: needId, requirements_version: 3 });
expect(
buildMatchRequest(
{ mode: "need", needId, requirementsVersion: 3 },
{ ...emptyFilterDraft, specialization: "network_engineer" },
),
).toEqual({
need_id: needId,
requirements_version: 3,
filters: { specialization: "network_engineer" },
});
});
it("sends a contradictory pair of filters as it is instead of relaxing one", () => {
const draft: MatchFilterDraft = {
...emptyFilterDraft,
confirmationStatus: "unconfirmed",
confirmedGrade: "senior",
};
expect(filtersFromDraft(draft)).toEqual({
confirmation_status: "unconfirmed",
confirmed_grade: "senior",
});
});
it("sends a work format condition without a salary condition", () => {
expect(filtersFromDraft({ ...emptyFilterDraft, workFormats: ["hybrid", "office"] })).toEqual({
conditions: { work_formats: ["hybrid", "office"] },
});
});
it("toggles list items in catalog order", () => {
const order = ["go", "postgresql", "kafka", "docker"] as const;
expect(toggleItem(["kafka"], "go", true, order)).toEqual(["go", "kafka"]);
expect(toggleItem(["go", "kafka"], "go", false, order)).toEqual(["kafka"]);
});
});
@@ -0,0 +1,93 @@
import type {
GradeCode,
MatchSearchFilters,
MatchSearchRequest,
MatchSearchStackTag,
SpecializationCode,
WorkFormat,
} from "../../../shared/api/schemas";
/** Form state of the search filters. An empty value means the filter is off. */
export type MatchFilterDraft = {
specialization: SpecializationCode | "";
confirmedGrade: GradeCode | "";
confirmationStatus: "" | "confirmed" | "unconfirmed";
declaredGrade: GradeCode | "";
stack: readonly MatchSearchStackTag[];
workFormats: readonly WorkFormat[];
salaryCompatible: boolean;
};
export const emptyFilterDraft: MatchFilterDraft = {
specialization: "",
confirmedGrade: "",
confirmationStatus: "",
declaredGrade: "",
stack: [],
workFormats: [],
salaryCompatible: false,
};
/** What the search is based on: a need's confirmed requirements or the whole visible bank. */
export type MatchBasis =
{ mode: "bank" } | { mode: "need"; needId: string; requirementsVersion: number };
/** Number of filters that are switched on. */
export function activeFilterCount(draft: MatchFilterDraft): number {
return [
draft.specialization !== "",
draft.confirmedGrade !== "",
draft.confirmationStatus !== "",
draft.declaredGrade !== "",
draft.stack.length > 0,
draft.workFormats.length > 0,
draft.salaryCompatible,
].filter(Boolean).length;
}
/**
* Converts the draft to request filters. Only switched-on filters are sent,
* and nothing is added or relaxed: a mandatory filter that the draft holds is
* sent as it is, whatever the result may be.
*/
export function filtersFromDraft(draft: MatchFilterDraft): MatchSearchFilters {
const filters: MatchSearchFilters = {};
if (draft.specialization) filters.specialization = draft.specialization;
if (draft.confirmedGrade) filters.confirmed_grade = draft.confirmedGrade;
if (draft.confirmationStatus) filters.confirmation_status = draft.confirmationStatus;
if (draft.declaredGrade) filters.declared_grade = draft.declaredGrade;
if (draft.stack.length > 0) filters.stack = [...draft.stack];
if (draft.workFormats.length > 0 || draft.salaryCompatible) {
filters.conditions = {
...(draft.workFormats.length > 0 ? { work_formats: [...draft.workFormats] } : {}),
...(draft.salaryCompatible ? { salary_compatibility: "compatible" as const } : {}),
};
}
return filters;
}
/** Builds the search body for the chosen basis and filters. */
export function buildMatchRequest(basis: MatchBasis, draft: MatchFilterDraft): MatchSearchRequest {
const filters = filtersFromDraft(draft);
if (basis.mode === "need") {
return {
need_id: basis.needId,
requirements_version: basis.requirementsVersion,
...(Object.keys(filters).length > 0 ? { filters } : {}),
};
}
return { filters };
}
/** Adds or removes one item of a list, keeping the order of the catalog. */
export function toggleItem<T extends string>(
items: readonly T[],
item: T,
checked: boolean,
catalogOrder: readonly T[],
): T[] {
const next = new Set(items);
if (checked) next.add(item);
else next.delete(item);
return catalogOrder.filter((candidate) => next.has(candidate));
}
@@ -0,0 +1,108 @@
.form {
display: grid;
gap: var(--space-5);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr));
gap: var(--space-4);
min-width: 0;
}
.field {
display: grid;
gap: var(--space-1);
align-content: start;
min-width: 0;
}
.field label,
.group legend {
font-weight: var(--font-weight-bold);
}
.field select {
width: 100%;
min-width: 0;
min-height: 2.75rem;
padding: var(--space-2) var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
}
.field select:focus-visible {
outline: var(--line-strong) solid var(--color-accent);
outline-offset: 2px;
}
.hint {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.group {
display: grid;
gap: var(--space-2);
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.group legend {
padding: 0;
}
.choices {
display: flex;
flex-wrap: wrap;
gap: var(--space-1) var(--space-4);
}
.choice {
display: inline-flex;
gap: var(--space-2);
align-items: center;
min-height: 2.75rem;
}
.choice input {
width: 1.25rem;
height: 1.25rem;
margin: 0;
accent-color: var(--color-accent);
}
.quota {
margin: 0;
padding: var(--space-3);
border-inline-start: var(--space-1) solid var(--color-accent);
background: var(--color-canvas);
font-size: var(--font-size-s);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: center;
}
@media (width < 30rem) {
.form {
padding: var(--space-3);
}
.actions > * {
flex: 1 1 100%;
}
}
@@ -0,0 +1,53 @@
import { renderToString } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { emptyFilterDraft } from "../model/draft";
import { MatchFilterForm } from "./match-filter-form";
function render(props: { blockedReason?: string | null; isSearching?: boolean } = {}): string {
return renderToString(
<MatchFilterForm
value={{ ...emptyFilterDraft, confirmedGrade: "senior" }}
onChange={() => undefined}
onSubmit={() => undefined}
isSearching={props.isSearching ?? false}
blockedReason={props.blockedReason ?? null}
basis={<p>basis slot</p>}
/>,
);
}
describe("match filter form", () => {
it("says before the search that it spends card view quota", () => {
const html = render();
expect(html).toContain("Поиск расходует квоту просмотров карточек");
expect(html).toContain("Найти кандидатов");
});
it("separates the confirmed grade from the grade the candidate declared", () => {
const html = render();
expect(html).toContain("Подтвержденный грейд");
expect(html).toContain("Заявленный кандидатом грейд");
expect(html).toContain("Это не подтверждение");
});
it("offers the reset only while a filter is on and keeps the basis slot", () => {
expect(render()).toContain("Сбросить фильтры");
expect(render()).toContain("basis slot");
});
it("names why the search cannot start", () => {
const html = render({ blockedReason: "Выберите потребность." });
expect(html).toContain("Выберите потребность.");
expect(html).toContain('aria-disabled="true"');
});
it("marks a running search as busy", () => {
const html = render({ isSearching: true });
expect(html).toContain("Ищем...");
expect(html).toContain('aria-busy="true"');
});
});
@@ -0,0 +1,228 @@
import { useId, type FormEvent, type ReactNode } from "react";
import {
gradeCodes,
gradeLabels,
specializationCodes,
specializationLabels,
stackCodes,
stackLabels,
workFormatCodes,
workFormatLabels,
} from "../../../entities/match";
import { Button } from "../../../shared/ui";
import {
activeFilterCount,
emptyFilterDraft,
toggleItem,
type MatchFilterDraft,
} from "../model/draft";
import styles from "./match-filter-form.module.css";
type MatchFilterFormProps = {
value: MatchFilterDraft;
onChange: (next: MatchFilterDraft) => void;
onSubmit: () => void;
isSearching: boolean;
/** Why the search cannot start, or null when it can. */
blockedReason: string | null;
/** Controls above the filters that choose the basis of the search. */
basis: ReactNode;
};
/**
* The filters of the candidate search. Every filter is mandatory while it is
* switched on: nothing relaxes it automatically, and an empty answer keeps the
* values here for the employer to change. The form says before it runs that a
* search spends card view quota.
*/
export function MatchFilterForm({
value,
onChange,
onSubmit,
isSearching,
blockedReason,
basis,
}: MatchFilterFormProps) {
const ids = useId();
const quotaId = `${ids}-quota`;
const blockedId = `${ids}-blocked`;
const active = activeFilterCount(value);
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!isSearching && !blockedReason) onSubmit();
}
function set<K extends keyof MatchFilterDraft>(key: K, next: MatchFilterDraft[K]) {
onChange({ ...value, [key]: next });
}
return (
<form className={styles.form} onSubmit={handleSubmit} aria-label="Поиск кандидатов">
{basis}
<div className={styles.grid}>
<div className={styles.field}>
<label htmlFor={`${ids}-specialization`}>Специализация</label>
<select
id={`${ids}-specialization`}
value={value.specialization}
onChange={(event) =>
set("specialization", event.currentTarget.value as MatchFilterDraft["specialization"])
}
>
<option value="">Все специализации</option>
{specializationCodes.map((code) => (
<option key={code} value={code}>
{specializationLabels[code]}
</option>
))}
</select>
</div>
<div className={styles.field}>
<label htmlFor={`${ids}-confirmed-grade`}>Подтвержденный грейд</label>
<select
id={`${ids}-confirmed-grade`}
aria-describedby={`${ids}-confirmed-grade-hint`}
value={value.confirmedGrade}
onChange={(event) =>
set("confirmedGrade", event.currentTarget.value as MatchFilterDraft["confirmedGrade"])
}
>
<option value="">Любой</option>
{gradeCodes.map((code) => (
<option key={code} value={code}>
{gradeLabels[code]}
</option>
))}
</select>
<p id={`${ids}-confirmed-grade-hint`} className={styles.hint}>
Исключает профили без подтвержденной категории.
</p>
</div>
<div className={styles.field}>
<label htmlFor={`${ids}-status`}>Статус подтверждения</label>
<select
id={`${ids}-status`}
value={value.confirmationStatus}
onChange={(event) =>
set(
"confirmationStatus",
event.currentTarget.value as MatchFilterDraft["confirmationStatus"],
)
}
>
<option value="">Любой</option>
<option value="confirmed">Только подтвержденный грейд</option>
<option value="unconfirmed">Только грейд не подтвержден</option>
</select>
</div>
<div className={styles.field}>
<label htmlFor={`${ids}-declared-grade`}>Заявленный кандидатом грейд</label>
<select
id={`${ids}-declared-grade`}
aria-describedby={`${ids}-declared-grade-hint`}
value={value.declaredGrade}
onChange={(event) =>
set("declaredGrade", event.currentTarget.value as MatchFilterDraft["declaredGrade"])
}
>
<option value="">Любой</option>
{gradeCodes.map((code) => (
<option key={code} value={code}>
{gradeLabels[code]}
</option>
))}
</select>
<p id={`${ids}-declared-grade-hint`} className={styles.hint}>
Слова кандидата. Это не подтверждение и не заменяет подтвержденный грейд.
</p>
</div>
</div>
<div className={styles.grid}>
<fieldset className={styles.group}>
<legend>Технологии в карточке</legend>
<p className={styles.hint}>Нужны все отмеченные технологии.</p>
<div className={styles.choices}>
{stackCodes.map((code) => (
<label key={code} className={styles.choice}>
<input
type="checkbox"
checked={value.stack.includes(code)}
onChange={(event) =>
set(
"stack",
toggleItem(value.stack, code, event.currentTarget.checked, stackCodes),
)
}
/>
{stackLabels[code]}
</label>
))}
</div>
</fieldset>
<fieldset className={styles.group}>
<legend>Формат работы</legend>
<p className={styles.hint}>Достаточно одного общего формата.</p>
<div className={styles.choices}>
{workFormatCodes.map((code) => (
<label key={code} className={styles.choice}>
<input
type="checkbox"
checked={value.workFormats.includes(code)}
onChange={(event) =>
set(
"workFormats",
toggleItem(
value.workFormats,
code,
event.currentTarget.checked,
workFormatCodes,
),
)
}
/>
{workFormatLabels[code]}
</label>
))}
</div>
</fieldset>
<fieldset className={styles.group}>
<legend>Зарплатные ожидания</legend>
<p className={styles.hint}>Сумма кандидата недоступна, только совместимость.</p>
<label className={styles.choice}>
<input
type="checkbox"
checked={value.salaryCompatible}
onChange={(event) => set("salaryCompatible", event.currentTarget.checked)}
/>
Только совместимые ожидания
</label>
</fieldset>
</div>
<p id={quotaId} className={styles.quota}>
Поиск расходует квоту просмотров карточек: каждый впервые показанный кандидат считается
одним просмотром. Кандидаты, уже показанные в текущем окне, повторно не списываются.
</p>
{blockedReason ? (
<p id={blockedId} className={styles.hint}>
{blockedReason}
</p>
) : null}
<div className={styles.actions}>
<Button
type="submit"
isBusy={isSearching}
aria-describedby={blockedReason ? `${quotaId} ${blockedId}` : quotaId}
aria-disabled={isSearching || blockedReason !== null ? true : undefined}
>
{isSearching ? "Ищем..." : "Найти кандидатов"}
</Button>
{active > 0 ? (
<Button variant="quiet" onClick={() => onChange({ ...emptyFilterDraft })}>
Сбросить фильтры
</Button>
) : null}
</div>
</form>
);
}
+1
View File
@@ -0,0 +1 @@
export { MatchesPage } from "./ui/matches-page";
@@ -0,0 +1,104 @@
.content {
display: grid;
gap: var(--space-6);
min-width: 0;
}
.selector {
display: grid;
gap: var(--space-2);
min-width: min(100%, 20rem);
max-width: 28rem;
}
.selector label,
.basis legend {
font-weight: var(--font-weight-bold);
}
.selector select {
width: 100%;
min-width: 0;
min-height: 2.75rem;
padding: var(--space-2) var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
}
.selector select:focus-visible {
outline: var(--line-strong) solid var(--color-accent);
outline-offset: 2px;
}
.workspace {
display: grid;
gap: var(--space-6);
align-items: start;
min-width: 0;
}
.basis {
display: grid;
gap: var(--space-3);
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.basis legend {
padding: 0;
}
.choices {
display: flex;
flex-wrap: wrap;
gap: var(--space-1) var(--space-4);
}
.choice {
display: inline-flex;
gap: var(--space-2);
align-items: center;
min-height: 2.75rem;
}
.choice input {
width: 1.25rem;
height: 1.25rem;
margin: 0;
accent-color: var(--color-accent);
}
.hint {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.results {
display: grid;
gap: var(--space-4);
min-width: 0;
}
.idle {
margin: 0;
padding: var(--space-5);
border: var(--line-thin) dashed var(--color-border-strong);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.load-more {
display: flex;
justify-content: center;
}
@media (width >= 64rem) {
.workspace {
grid-template-columns: minmax(19rem, 24rem) minmax(0, 1fr);
}
}
@@ -0,0 +1,397 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { ApiRequestError } from "../../../shared/api";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import {
getOrganizationNeed,
listOrganizationNeeds,
} from "../../../shared/api/endpoints/need/need";
import type { MatchSearchRequest, Session } from "../../../shared/api/schemas";
import {
Button,
EmptyState,
ErrorState,
ForbiddenState,
isAccessDenied,
LoadingState,
Page,
StatusView,
} from "../../../shared/ui";
import { formatRetryAfter, searchMatches } from "../../../entities/match";
import {
activeNeedOrganizations,
isNeedSessionCurrent,
needQueryKeys,
useNeedOrganizationDirectory,
type NeedOrganization,
} from "../../../entities/need";
import {
buildMatchRequest,
emptyFilterDraft,
filtersFromDraft,
MatchFilterForm,
type MatchBasis,
type MatchFilterDraft,
} from "../../../features/filter-matches";
import { MatchList } from "../../../widgets/match-list";
import styles from "./matches-page.module.css";
const needPickerLimit = 100;
type BasisMode = "need" | "bank";
type SearchVariables = {
request: MatchSearchRequest;
sentFilters: ReturnType<typeof filtersFromDraft>;
needTitle: string | null;
};
function sessionChanged(): Error {
return new Error("The session changed during the search.");
}
function SearchFailure({
error,
onRetry,
isRetrying,
}: {
error: unknown;
onRetry: () => void;
isRetrying: boolean;
}) {
if (isAccessDenied(error)) return <ForbiddenState error={error} />;
if (error instanceof ApiRequestError && error.status === 429) {
const wait = formatRetryAfter(error.retryAfterSeconds);
return (
<StatusView
kind="error"
title="Слишком много запросов"
description={
wait
? `Повторить поиск можно ${wait}.`
: "Сервер не назвал время повтора. Подождите и повторите поиск."
}
/>
);
}
return (
<ErrorState
error={error}
title={
error instanceof ApiRequestError && error.status === 404
? "Потребность или компания не найдены"
: "Не удалось выполнить поиск"
}
isRetrying={isRetrying}
onRetry={onRetry}
/>
);
}
type WorkspaceProps = {
session: Session;
organization: NeedOrganization;
initialNeedId: string | null;
};
/** The search form and the result for one organization; remounted when the organization changes. */
function MatchWorkspace({ session, organization, initialNeedId }: WorkspaceProps) {
const queryClient = useQueryClient();
const accountId = session.account.id;
const organizationId = organization.organization.id;
const sessionCurrent = isNeedSessionCurrent(queryClient, session);
const resultRef = useRef<HTMLDivElement>(null);
const needs = useQuery({
queryKey: [...needQueryKeys.list(accountId, organizationId), "match-picker"],
queryFn: ({ signal }) =>
listOrganizationNeeds(organizationId, { limit: needPickerLimit }, { signal }),
enabled: sessionCurrent,
gcTime: 0,
staleTime: 0,
retry: false,
});
const needItems = needs.data?.items ?? [];
const [basisChoice, setBasisChoice] = useState<BasisMode | null>(initialNeedId ? "need" : null);
const [needId, setNeedId] = useState(initialNeedId ?? "");
const [draft, setDraft] = useState<MatchFilterDraft>(emptyFilterDraft);
const mode: BasisMode = basisChoice ?? (needItems.length > 0 ? "need" : "bank");
const selectedNeed = needItems.find((item) => item.id === needId);
const needDetail = useQuery({
queryKey: [...needQueryKeys.detail(accountId, organizationId, needId), "match-basis"],
queryFn: ({ signal }) => getOrganizationNeed(organizationId, needId, { signal }),
enabled: sessionCurrent && mode === "need" && selectedNeed !== undefined,
gcTime: 0,
staleTime: 0,
retry: false,
});
const basis: MatchBasis | null =
mode === "bank"
? { mode: "bank" }
: needDetail.data
? { mode: "need", needId, requirementsVersion: needDetail.data.requirements_version }
: null;
let blockedReason: string | null = null;
if (mode === "need") {
if (needs.isPending) blockedReason = "Загружаем потребности...";
else if (needItems.length === 0) {
blockedReason = "Потребностей нет. Создайте потребность или ищите по всем профилям.";
} else if (!selectedNeed) blockedReason = "Выберите потребность.";
else if (needDetail.isError) blockedReason = "Не удалось загрузить потребность. Повторите.";
else if (!needDetail.data) blockedReason = "Загружаем версию требований...";
}
const search = useMutation({
mutationFn: async (variables: SearchVariables) => {
if (!isNeedSessionCurrent(queryClient, session)) throw sessionChanged();
const result = await searchMatches(organizationId, variables.request, session.csrf_token);
if (!isNeedSessionCurrent(queryClient, session)) throw sessionChanged();
return result;
},
});
function runSearch() {
if (!basis) return;
search.mutate({
request: buildMatchRequest(basis, draft),
sentFilters: filtersFromDraft(draft),
needTitle: basis.mode === "need" ? (needDetail.data?.title ?? null) : null,
});
}
const currentRequest = basis ? JSON.stringify(buildMatchRequest(basis, draft)) : null;
const stale =
search.isSuccess &&
search.variables !== undefined &&
currentRequest !== JSON.stringify(search.variables.request);
// After a search finishes, the result region is the reading position.
useEffect(() => {
if (search.isError) resultRef.current?.focus();
}, [search.isError]);
return (
<div className={styles.workspace}>
<MatchFilterForm
value={draft}
onChange={setDraft}
onSubmit={runSearch}
isSearching={search.isPending}
blockedReason={blockedReason}
basis={
<fieldset className={styles.basis}>
<legend>Основание поиска</legend>
<div className={styles.choices}>
<label className={styles.choice}>
<input
type="radio"
name="match-basis"
checked={mode === "need"}
onChange={() => setBasisChoice("need")}
/>
По потребности
</label>
<label className={styles.choice}>
<input
type="radio"
name="match-basis"
checked={mode === "bank"}
onChange={() => setBasisChoice("bank")}
/>
По всем профилям
</label>
</div>
{mode === "need" ? (
<div className={styles.selector}>
<label htmlFor="match-need">Потребность</label>
<select
id="match-need"
value={selectedNeed ? needId : ""}
onChange={(event) => setNeedId(event.currentTarget.value)}
>
<option value="">Выберите потребность</option>
{needItems.map((item) => (
<option key={item.id} value={item.id}>
{item.title}
</option>
))}
</select>
{needs.isError ? (
<p className={styles.hint}>
Не удалось загрузить потребности. Можно искать по всем профилям.
</p>
) : null}
{needs.data?.page.has_more ? (
<p className={styles.hint}>Показаны первые {needPickerLimit} потребностей.</p>
) : null}
{needDetail.data ? (
<p className={styles.hint}>
Версия требований: {needDetail.data.requirements_version}. Грейд потребности
фильтром не служит.
</p>
) : null}
</div>
) : (
<p className={styles.hint}>
Ищем среди всех профилей, доступных компании. Каждая специализация кандидата
показывается отдельной записью.
</p>
)}
</fieldset>
}
/>
<div className={styles.results} ref={resultRef} tabIndex={-1}>
{search.isPending ? <LoadingState label="Ищем кандидатов..." /> : null}
{search.isError ? (
<SearchFailure error={search.error} isRetrying={search.isPending} onRetry={runSearch} />
) : null}
{search.isSuccess && search.variables ? (
<MatchList
accountId={accountId}
organizationId={organizationId}
result={search.data}
sentFilters={search.variables.sentFilters}
needTitle={search.variables.needTitle}
stale={stale}
/>
) : null}
{search.isIdle ? (
<p className={styles.idle}>
Поиск еще не запускался. Задайте условия и нажмите «Найти кандидатов»: выдача появится
здесь, а перезагрузка страницы не повторяет поиск сама.
</p>
) : null}
</div>
</div>
);
}
function isAccessLoss(error: unknown): error is ApiRequestError {
return (
error instanceof ApiRequestError &&
(error.status === 401 || error.status === 403 || error.status === 404)
);
}
/**
* The candidate search of an organization owner. The page picks the
* organization from the address, loads the owner's organizations, and hands
* the search itself to the workspace. A search starts only on the employer's
* action, because it spends card view quota.
*/
export function MatchesPage() {
const queryClient = useQueryClient();
const sessionQuery = useGetCurrentSession({ query: { retry: false } });
const session = sessionQuery.data;
const sessionReady =
Boolean(session && session.account.scenario === "employer") &&
isNeedSessionCurrent(queryClient, session);
const directory = useNeedOrganizationDirectory(session, sessionReady);
const [searchParams, setSearchParams] = useSearchParams();
const requestedOrganizationId = searchParams.get("organization_id");
const requestedNeedId = searchParams.get("need_id");
const pages = directory.data?.pages;
const organizations = useMemo(() => activeNeedOrganizations(pages ?? []), [pages]);
const selected =
organizations.find((item) => item.organization.id === requestedOrganizationId) ??
(requestedOrganizationId ? undefined : organizations[0]);
const hasMore = directory.hasNextPage;
const fetchNext = directory.fetchNextPage;
const fetching = directory.isFetchingNextPage;
// A requested organization may sit on a later page of the directory.
useEffect(() => {
if (!directory.data || directory.isError || fetching) return;
if (hasMore && (!selected || organizations.length === 0)) void fetchNext();
}, [directory.data, directory.isError, fetchNext, fetching, hasMore, organizations, selected]);
const loading =
!sessionQuery.isError &&
(!sessionReady || directory.isPending || (hasMore && !selected && !directory.isError));
return (
<Page
title="Кандидаты"
eyebrow="Кабинет работодателя"
lead="Ищите анонимные карточки по потребности или среди всех профилей. Объяснение строит сервер: подтвержденные источники и пробелы показаны отдельно, неизвестное не выдается за ноль."
width="wide"
>
{sessionQuery.isError ? (
isAccessLoss(sessionQuery.error) ? (
<ForbiddenState error={sessionQuery.error} title="Текущий вход не подтвержден" />
) : (
<ErrorState
error={sessionQuery.error}
isRetrying={sessionQuery.isFetching}
onRetry={() => void sessionQuery.refetch()}
/>
)
) : null}
{directory.isError ? (
isAccessLoss(directory.error) ? (
<ForbiddenState error={directory.error} />
) : (
<ErrorState
error={directory.error}
isRetrying={directory.isFetching}
onRetry={() => void directory.refetch()}
/>
)
) : null}
{loading ? <LoadingState label="Проверяем компанию..." /> : null}
{session && sessionReady && directory.data && !directory.isError && !loading ? (
<div className={styles.content}>
{organizations.length === 0 ? (
<ForbiddenState
title="Нужны права владельца компании"
description="Искать кандидатов в этой версии может только владелец компании."
/>
) : !selected ? (
<EmptyState
title="Компания не найдена среди ваших"
description="Выберите компанию, где вы владелец."
action={
<Button variant="secondary" onClick={() => setSearchParams({}, { replace: true })}>
Выбрать другую компанию
</Button>
}
/>
) : (
<>
{organizations.length > 1 ? (
<div className={styles.selector}>
<label htmlFor="match-organization">Компания</label>
<select
id="match-organization"
value={selected.organization.id}
onChange={(event) =>
setSearchParams({ organization_id: event.currentTarget.value })
}
>
{organizations.map((item) => (
<option key={item.organization.id} value={item.organization.id}>
{item.organization.name}
</option>
))}
</select>
</div>
) : null}
<MatchWorkspace
key={selected.organization.id}
session={session}
organization={selected}
initialNeedId={requestedOrganizationId ? requestedNeedId : null}
/>
</>
)}
</div>
) : null}
</Page>
);
}
@@ -109,6 +109,13 @@
padding-inline-start: var(--space-5);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-3);
align-items: center;
}
.load-more {
display: flex;
justify-content: center;
@@ -95,9 +95,14 @@ function NeedCard({ item, organizationId }: { item: NeedSummary; organizationId:
))}
</ul>
) : null}
<ButtonLink to={paths.employer.need(item.id, organizationId)} variant="secondary">
Открыть потребность
</ButtonLink>
<div className={styles.actions}>
<ButtonLink to={paths.employer.need(item.id, organizationId)} variant="secondary">
Открыть потребность
</ButtonLink>
<ButtonLink to={paths.employer.candidatesForNeed(item.id, organizationId)} variant="quiet">
Подобрать кандидатов
</ButtonLink>
</div>
</article>
);
}
@@ -119,15 +119,6 @@ export const screens = {
"Фильтры поиска кандидатов",
],
},
employerCandidates: {
area: "employer",
title: "Кандидаты",
planned: [
"Объяснимая выдача по потребности",
"Шортлист",
"Псевдонимы вместо контактов до принятия приглашения",
],
},
employerInvitations: {
area: "employer",
title: "Приглашения",
+21
View File
@@ -38,7 +38,28 @@ export const paths = {
need: (needId: string, organizationId: string) =>
`/employer/needs/${encodeURIComponent(needId)}?organization_id=${encodeURIComponent(organizationId)}`,
candidates: "/employer/candidates",
/** The candidate search with one need of the organization preselected. */
candidatesForNeed: (needId: string, organizationId: string) =>
`/employer/candidates?organization_id=${encodeURIComponent(organizationId)}&need_id=${encodeURIComponent(needId)}`,
invitations: "/employer/invitations",
/**
* Opens the invitations section for one search result. The handle is the
* organization-scoped alias from the search, never a candidate identifier.
*/
inviteCandidate: (input: {
organizationId: string;
candidateHandle: string;
specialization: string;
needId?: string | undefined;
}) => {
const query = new URLSearchParams({
organization_id: input.organizationId,
candidate_handle: input.candidateHandle,
specialization: input.specialization,
});
if (input.needId) query.set("need_id", input.needId);
return `/employer/invitations?${query.toString()}`;
},
notifications: "/employer/notifications",
supportCases: "/employer/support/cases",
supportNew: "/employer/support/cases/new",
+4
View File
@@ -0,0 +1,4 @@
// Public API of the match-list widget: the result of one candidate search in
// its three groups, with the explanation and the full card of each entry.
export { MatchList } from "./ui/match-list";
@@ -0,0 +1,187 @@
.root {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.title {
margin: 0;
font-size: var(--font-size-xl);
font-weight: var(--font-weight-bold);
}
.title:focus-visible {
outline-offset: 4px;
}
.basis {
display: grid;
grid-template-columns: minmax(9rem, max-content) minmax(0, 1fr);
gap: var(--space-2) var(--space-4);
margin: 0;
padding: var(--space-3) var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
background: var(--color-surface);
}
.basis dt {
color: var(--color-text-secondary);
}
.basis dd {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.filters {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
margin: 0;
padding: 0;
list-style: none;
}
.filter {
padding: var(--space-1) var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-pill);
background: var(--color-canvas);
font-size: var(--font-size-s);
overflow-wrap: anywhere;
}
.notice {
margin: 0;
padding: var(--space-3) var(--space-4);
border-inline-start: var(--space-1) solid var(--color-accent);
background: var(--color-surface);
}
.notice[data-kind="truncated"] {
border-inline-start-style: double;
}
.switcher {
display: grid;
gap: var(--space-2);
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.switcher legend {
padding: 0;
font-weight: var(--font-weight-bold);
}
.views {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.view {
position: relative;
}
.view input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
cursor: pointer;
}
.view span {
display: inline-flex;
align-items: center;
min-height: 2.75rem;
padding: var(--space-2) var(--space-4);
border: var(--line-strong) solid var(--color-border-strong);
border-radius: var(--radius-pill);
background: var(--color-surface);
font-weight: var(--font-weight-medium);
overflow-wrap: anywhere;
}
.view input:checked + span {
border-color: var(--color-accent);
color: var(--color-on-accent);
background: var(--color-accent);
font-weight: var(--font-weight-bold);
}
.view input:focus-visible + span {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.hint {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.group {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.group-heading {
display: flex;
flex-wrap: wrap;
gap: var(--space-1) var(--space-3);
align-items: baseline;
}
.group-title {
margin: 0;
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
}
.group-count {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.group-description {
margin: 0;
color: var(--color-text-secondary);
}
.cards {
display: grid;
gap: var(--space-4);
margin: 0;
padding: 0;
list-style: none;
}
.cards > li {
min-width: 0;
}
.empty-reasons {
display: grid;
gap: var(--space-2);
margin: var(--space-2) 0 0;
padding-inline-start: var(--space-5);
}
@media (width < 30rem) {
.basis {
grid-template-columns: minmax(0, 1fr);
}
.basis dd + dt {
padding-block-start: var(--space-2);
}
}
@@ -0,0 +1,160 @@
import { renderToString } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import type { MatchSearchModel } from "../../../entities/match";
import {
backendHandle,
emptyMatchModelFixture,
matchFixtureNeedId as needId,
matchModelFixture,
} from "../../../entities/match/testing";
import { MatchList } from "./match-list";
const organizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccddee01";
function render(
result: MatchSearchModel,
props: { stale?: boolean; needTitle?: string | null } = {},
): string {
return renderToString(
<MemoryRouter>
<MatchList
accountId="0199b4f2-7c1e-7d3a-9f00-aabbccddee02"
organizationId={organizationId}
result={result}
sentFilters={undefined}
needTitle={props.needTitle ?? null}
stale={props.stale ?? false}
/>
</MemoryRouter>,
);
}
describe("match list", () => {
it("prints the three groups in the product order with their labels", () => {
const html = render(matchModelFixture());
const positions = ["Подтвержденные", "Близкие варианты", "Грейд не подтвержден"].map((label) =>
html.indexOf(`>${label}</h3>`),
);
expect(positions.every((position) => position > 0)).toBe(true);
expect([...positions].sort((a, b) => a - b)).toEqual(positions);
});
it("keeps the confirmed and the declared grade on separate lines", () => {
const html = render(matchModelFixture());
expect(html).toContain("Подтвержденная категория");
expect(html).toContain("Заявленный кандидатом грейд");
expect(html).toContain("Грейд подтвержден: Middle");
expect(html).toContain("Backend, Middle. Сильное подтверждение");
});
it("offers a specialization switch when the result holds several specializations", () => {
const html = render(matchModelFixture());
expect(html).toContain("Представление по специализациям");
expect(html).toContain("Все специализации");
expect(html).toContain("Сетевое администрирование");
expect(html).toContain("Подтверждение не переносится");
});
it("offers no switch for a single specialization", () => {
const base = matchModelFixture();
const single = {
...base,
cards: base.cards.filter((card) => card.specialization === "backend"),
};
expect(render(single)).not.toContain("Представление по специализациям");
});
it("links every entry to the invitation with the organization-scoped handle, also unconfirmed ones", () => {
const html = render(matchModelFixture());
const links = [...html.matchAll(/href="(\/employer\/invitations\?[^"]+)"/g)].map(
(match) => new URL((match[1] ?? "").replaceAll("&amp;", "&"), "http://x"),
);
expect(links).toHaveLength(matchModelFixture().cards.length);
const network = links.find(
(url) => url.searchParams.get("specialization") === "network_engineer",
);
expect(network?.searchParams.get("candidate_handle")).toBe(backendHandle);
expect(network?.searchParams.get("organization_id")).toBe(organizationId);
expect(html).toContain("Пригласить кандидата");
});
it("passes the need to the invitation link when the search was based on a need", () => {
const model = matchModelFixture({
source: { kind: "need", need_id: needId, requirements_version: 4 },
});
const html = render(model, { needTitle: "Платежный backend" });
expect(html).toContain(`need_id=${needId}`);
expect(html).toContain("Платежный backend");
expect(html).toContain("версия требований 4");
});
it("shows no contact, no stable identifier and no failure reason", () => {
const html = render(matchModelFixture());
expect(html).not.toMatch(/@|\+7|telegram|email/i);
expect(html).not.toContain("candidate_id");
expect(html).not.toContain("account");
// Only the shortened alias is printed; the full handle goes into links only.
expect(html).not.toContain(`>${backendHandle}<`);
expect(html).not.toMatch(/провал|неудач/i);
});
it("keeps the explanation and the card closed until the employer asks", () => {
const html = render(matchModelFixture());
expect(html).not.toContain("Как получена позиция");
expect(html).not.toContain("Карточка кандидата</h5>");
expect(html).toContain('aria-expanded="false"');
expect(html).toContain("Показать объяснение");
expect(html).toContain("Открыть карточку");
});
it("explains a partial output without a count", () => {
const html = render(matchModelFixture({ truncated: true }));
expect(html).toContain("Показана часть выдачи; квота просмотров или предел группы");
expect(render(matchModelFixture())).not.toContain("Показана часть выдачи");
});
it("explains an empty result and keeps the filters in view", () => {
const html = render(emptyMatchModelFixture());
expect(html).toContain("По этим условиям никого не нашли");
expect(html).toContain("поиск не ослабляет их сам");
expect(html).not.toContain("Подтвержденные</h3>");
});
it("lists the filters of an empty result that the employer can change", () => {
const model = emptyMatchModelFixture();
const html = render({
...model,
source: {
kind: "bank",
filters: {
specialization: "qa",
confirmedGrade: "senior",
confirmedCategory: null,
confirmationStatus: null,
declaredGrade: null,
stack: ["kafka"],
conditions: null,
},
},
});
expect(html).toContain("Подтвержденный грейд: Senior");
expect(html).toContain("Технологии в карточке (нужны все): Kafka");
});
it("warns that the form changed after the shown result", () => {
expect(render(matchModelFixture(), { stale: true })).toContain("Условия поиска изменены");
expect(render(matchModelFixture())).not.toContain("Условия поиска изменены");
});
});
@@ -0,0 +1,319 @@
import { useEffect, useId, useRef, useState } from "react";
import {
allSpecializationsView,
appliedFiltersOf,
CandidateCardDetails,
cardsForView,
groupDescriptions,
groupLabels,
matchCardKey,
matchGroupOrder,
MatchCardView,
MatchExplanation,
shortHandle,
specializationLabels,
specializationsInResult,
type MatchCardModel,
type MatchGroup,
type MatchSearchModel,
type SpecializationView,
} from "../../../entities/match";
import type { MatchSearchFilters } from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import { Button, ButtonLink, EmptyState } from "../../../shared/ui";
import styles from "./match-list.module.css";
type MatchListProps = {
accountId: string;
organizationId: string;
result: MatchSearchModel;
/** Filters of the request that produced the result; a need result does not echo them. */
sentFilters: MatchSearchFilters | undefined;
/** Title of the searched need, when the search was based on a need. */
needTitle: string | null;
/** True when the form changed after this result was produced. */
stale: boolean;
};
type EntryState = { explanation: boolean; cardRequested: boolean; cardOpen: boolean };
const closedEntry: EntryState = { explanation: false, cardRequested: false, cardOpen: false };
type EntryProps = {
card: MatchCardModel;
state: EntryState;
accountId: string;
organizationId: string;
needId: string | undefined;
onChange: (next: EntryState) => void;
};
function Entry({ card, state, accountId, organizationId, needId, onChange }: EntryProps) {
const ids = useId();
const headingId = `${ids}-heading`;
const explanationId = `${ids}-explanation`;
const detailsId = `${ids}-details`;
const specialization = specializationLabels[card.specialization];
const short = shortHandle(card.candidateHandle);
return (
<MatchCardView
card={card}
headingId={headingId}
actions={
<>
<Button
variant="secondary"
aria-expanded={state.explanation}
aria-controls={state.explanation ? explanationId : undefined}
aria-describedby={headingId}
onClick={() => onChange({ ...state, explanation: !state.explanation })}
>
{state.explanation ? "Скрыть объяснение" : "Показать объяснение"}
</Button>
<Button
variant="secondary"
aria-expanded={state.cardOpen}
aria-controls={state.cardRequested ? detailsId : undefined}
aria-describedby={headingId}
onClick={() => onChange({ ...state, cardRequested: true, cardOpen: !state.cardOpen })}
>
{state.cardOpen ? "Закрыть карточку" : "Открыть карточку"}
</Button>
<ButtonLink
to={paths.employer.inviteCandidate({
organizationId,
candidateHandle: card.candidateHandle,
specialization: card.specialization,
needId,
})}
aria-label={`Пригласить кандидата ${short}, ${specialization}`}
>
Пригласить
</ButtonLink>
</>
}
>
{state.explanation ? <MatchExplanation card={card} id={explanationId} /> : null}
{state.cardRequested ? (
<CandidateCardDetails
id={detailsId}
accountId={accountId}
organizationId={organizationId}
candidateHandle={card.candidateHandle}
open={state.cardOpen}
/>
) : null}
</MatchCardView>
);
}
type GroupProps = {
group: MatchGroup;
cards: readonly MatchCardModel[];
entryStates: Readonly<Record<string, EntryState>>;
accountId: string;
organizationId: string;
needId: string | undefined;
onEntryChange: (key: string, next: EntryState) => void;
};
function Group({
group,
cards,
entryStates,
accountId,
organizationId,
needId,
onEntryChange,
}: GroupProps) {
const headingId = useId();
return (
<section className={styles.group} aria-labelledby={headingId} data-group={group}>
<div className={styles["group-heading"]}>
<h3 id={headingId} className={styles["group-title"]}>
{groupLabels[group]}
</h3>
<span className={styles["group-count"]}>{`Записей: ${cards.length}`}</span>
</div>
<p className={styles["group-description"]}>{groupDescriptions[group]}</p>
{cards.length === 0 ? (
<p className={styles.hint}>В этой группе записей нет.</p>
) : (
<ul className={styles.cards}>
{cards.map((card) => {
const key = matchCardKey(card);
return (
<li key={key}>
<Entry
card={card}
state={entryStates[key] ?? closedEntry}
accountId={accountId}
organizationId={organizationId}
needId={needId}
onChange={(next) => onEntryChange(key, next)}
/>
</li>
);
})}
</ul>
)}
</section>
);
}
/**
* The result of one search: the basis and the filters it ran with, a notice
* when the output is only part of the ranked result, a switch between the
* specializations of the result, and the three groups in the fixed order of
* the product. The widget shows what the server returned and calculates
* nothing; a result that is empty is explained without touching the filters.
*/
export function MatchList({
accountId,
organizationId,
result,
sentFilters,
needTitle,
stale,
}: MatchListProps) {
const headingRef = useRef<HTMLHeadingElement>(null);
const switcherId = useId();
const [view, setView] = useState<SpecializationView>(allSpecializationsView);
const [entryStates, setEntryStates] = useState<Record<string, EntryState>>({});
// A new result moves the reading position to its heading.
useEffect(() => {
headingRef.current?.focus();
}, [result]);
const applied = appliedFiltersOf(result.source, sentFilters);
const specializations = specializationsInResult(result.cards);
const activeView: SpecializationView =
view !== allSpecializationsView && !specializations.includes(view)
? allSpecializationsView
: view;
const visible = cardsForView(result.cards, activeView);
const needId = result.source.kind === "need" ? result.source.needId : undefined;
const basis =
result.source.kind === "need"
? `Потребность${needTitle ? ` «${needTitle}»` : ""}, версия требований ${result.source.requirementsVersion}`
: "Все профили, доступные компании";
return (
<div className={styles.root}>
<h2 ref={headingRef} tabIndex={-1} className={styles.title}>
Результат поиска
</h2>
<dl className={styles.basis}>
<dt>Основание</dt>
<dd>{basis}</dd>
<dt>Текущие фильтры</dt>
<dd>
{applied.length === 0 ? (
"Не заданы"
) : (
<ul className={styles.filters}>
{applied.map((item) => (
<li key={item.label} className={styles.filter}>
{`${item.label}: ${item.value}`}
</li>
))}
</ul>
)}
</dd>
</dl>
{stale ? (
<p className={styles.notice} role="status">
Условия поиска изменены после этого результата. Нажмите «Найти кандидатов», чтобы обновить
выдачу.
</p>
) : null}
{result.truncated ? (
<p className={styles.notice} data-kind="truncated">
Показана часть выдачи; квота просмотров или предел группы. Остальные кандидаты не
показаны, их число сервер не сообщает. Сузьте фильтры, чтобы увидеть меньше записей
целиком.
</p>
) : null}
{result.cards.length === 0 ? (
<EmptyState
title="По этим условиям никого не нашли"
description={
<>
<p>
Фильтры остаются включенными: поиск не ослабляет их сам. Измените или снимите
условия в форме и повторите поиск.
</p>
{applied.length > 0 ? (
<ul className={styles["empty-reasons"]}>
{applied.map((item) => (
<li key={item.label}>{`${item.label}: ${item.value}`}</li>
))}
</ul>
) : (
<p>
Фильтры не заданы: сейчас в банке, доступном компании, нет подходящих
опубликованных профилей.
</p>
)}
{result.source.kind === "need" ? (
<p>Грейд потребности фильтром не служит; задайте фильтр грейда сами.</p>
) : null}
</>
}
/>
) : (
<>
{specializations.length > 1 ? (
<fieldset className={styles.switcher}>
<legend>Представление по специализациям</legend>
<div className={styles.views}>
{([allSpecializationsView, ...specializations] as SpecializationView[]).map(
(option) => (
<label key={option} className={styles.view}>
<input
type="radio"
name={switcherId}
value={option}
checked={activeView === option}
onChange={() => setView(option)}
/>
<span>
{option === allSpecializationsView
? "Все специализации"
: specializationLabels[option]}
</span>
</label>
),
)}
</div>
<p className={styles.hint}>
Один кандидат может быть в нескольких специализациях. Подтверждение не переносится
между ними: у каждой записи свой статус и своя группа.
</p>
</fieldset>
) : null}
<p className={styles.hint} role="status">
{`Показано записей: ${visible.length}`}
</p>
{matchGroupOrder.map((group) => (
<Group
key={group}
group={group}
cards={visible.filter((card) => card.group === group)}
entryStates={entryStates}
accountId={accountId}
organizationId={organizationId}
needId={needId}
onEntryChange={(key, next) =>
setEntryStates((current) => ({ ...current, [key]: next }))
}
/>
))}
</>
)}
</div>
);
}