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

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

No files matched your search

@@ -0,0 +1,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>
);
}