feat(frontend): edit projects and show semantic match evidence

This commit is contained in:
shira committed 2026-10-11 14:03:31 +03:00
1 parent 5a731c25b7
commit bc00d6901f
52 files changed
+2992 -111

No files matched your search

@@ -16,6 +16,7 @@ export {
presentCandidatePreview,
publicationDraftFromSettings,
privacyEventLabels,
projectsPublicationWarning,
publishableCardFields,
specializationLabels,
} from "./model/presentation";
@@ -24,6 +25,7 @@ export { EmployerCardPreview } from "./ui/employer-card-preview";
export type {
C2State,
CandidateViewPresentation,
CardProjectPresentation,
EvidencePresentation,
PublicationClosureNotice,
SelfAssessmentPresentation,
@@ -180,6 +180,62 @@ describe("candidate card presentation", () => {
});
});
describe("published projects", () => {
const card = {
pseudonym: `cv1_${"c".repeat(43)}`,
categories: null,
stack: null,
self_assessment: null,
experience_band: null,
work_formats: null,
salary_compatibility: null,
};
it("presents the title, the description, the tags, and the verification, in the published order", () => {
const result = presentCandidatePreview(
preview({
...card,
projects: [
{
title: "Платежный шлюз",
description: "Проводки и сверки.",
stack: ["Go", "PostgreSQL"],
repository_verified: true,
},
{ title: "Каталог", description: null, stack: [], repository_verified: false },
],
}),
);
expect(result?.projects).toEqual([
{
title: "Платежный шлюз",
description: "Проводки и сверки.",
stack: ["Go", "PostgreSQL"],
repositoryVerified: true,
},
{ title: "Каталог", description: null, stack: [], repositoryVerified: false },
]);
});
it("keeps an unpublished field null, so the card does not tell it from no value", () => {
expect(presentCandidatePreview(preview({ ...card, projects: null }))?.projects).toBeNull();
});
it("carries no repository address even if a response sent one", () => {
const withAddress = {
title: "Каталог",
description: null,
stack: [],
repository_verified: true,
repository_url: "https://github.com/example-org/catalog",
};
const result = presentCandidatePreview(preview({ ...card, projects: [withAddress] }));
expect(JSON.stringify(result)).not.toContain("github.com");
});
});
describe("editable card fields", () => {
it("exposes only safe groups supported by the anonymous-card contract", () => {
const stored: CardField[] = [
@@ -197,8 +253,14 @@ describe("editable card fields", () => {
"experience",
"work_formats",
"salary_compatibility",
"projects",
]);
expect(editableCardFields(stored)).toEqual(["categories", "work_formats"]);
expect(editableCardFields([...stored, "projects"])).toEqual([
"categories",
"work_formats",
"projects",
]);
});
});
@@ -26,6 +26,7 @@ export const publishableCardFields = [
"experience",
"work_formats",
"salary_compatibility",
"projects",
] as const satisfies readonly CardField[];
export type PublishableCardField = (typeof publishableCardFields)[number];
@@ -144,8 +145,20 @@ export const cardFieldLabels: Readonly<Record<PublishableCardField, string>> = {
experience: "Общий опыт",
work_formats: "Форматы работы",
salary_compatibility: "Совместимость по зарплатным ожиданиям",
projects: "Проекты: название, описание и технологии",
};
/**
* What publishing the projects reveals. It is shown beside the choice, before
* the candidate makes it, and again in the card preview.
*/
export const projectsPublicationWarning = {
identify:
"Название и описание проектов пишете вы, и по ним вас могут узнать. Не публикуйте проект, если в тексте есть имя, контакт или название работодателя. Размер группы похожих кандидатов эти тексты не скрывает: карточка с проектами может быть единственной в своем роде.",
repository:
"Адрес репозитория и его владелец компаниям не показываются никогда. Они видят только отметку, что публичный репозиторий проекта найден.",
} as const;
export const specializationLabels = {
backend: "Backend",
frontend: "Frontend",
@@ -215,6 +228,13 @@ export type EvidencePresentation = {
basisLabel: string;
};
export type CardProjectPresentation = {
title: string;
description: string | null;
stack: readonly string[];
repositoryVerified: boolean;
};
export type CandidateViewPresentation = {
pseudonym: string;
categories: readonly CategoryPresentation[] | null;
@@ -223,6 +243,8 @@ export type CandidateViewPresentation = {
experience: string | null;
workFormats: readonly string[] | null;
salaryCompatibility: string | null;
/** Published projects in the candidate's order; null when the field is not published. */
projects: readonly CardProjectPresentation[] | null;
/**
* Supporting assessment facts as an organization reads them. Null while the
* card is closed; an empty list when no visible fact supports a category.
@@ -302,6 +324,13 @@ export function presentCandidatePreview(preview: CardPreview): CandidateViewPres
salaryCompatibility: card.salary_compatibility
? salaryCompatibilityLabels[card.salary_compatibility]
: null,
projects:
card.projects?.map((project) => ({
title: project.title,
description: project.description,
stack: [...project.stack],
repositoryVerified: project.repository_verified,
})) ?? null,
evidence: preview.evidence ? preview.evidence.items.map(evidencePresentation) : null,
};
}
@@ -135,6 +135,39 @@ describe("employer card preview", () => {
expect(markup).toContain("2026");
});
it("shows published projects with their tags, a badge for a verified repository, and no address", () => {
const base = published();
const markup = render({
...base,
fields: ["projects"],
card: {
...(base.card as NonNullable<CardPreview["card"]>),
projects: [
{
title: "Платежный шлюз",
description: "Проводки и сверки.",
stack: ["Go", "PostgreSQL"],
repository_verified: true,
},
{ title: "Каталог", description: null, stack: ["Django"], repository_verified: false },
],
},
});
expect(markup).toContain(">Проекты</h3>");
expect(markup).toContain("Платежный шлюз");
expect(markup).toContain("Проводки и сверки.");
expect(markup).toContain(">PostgreSQL<");
expect(markup.match(/Подтвержден публичным репозиторием/g)).toHaveLength(1);
expect(markup).toContain("Адрес репозитория и его владелец ей не показываются");
expect(markup).not.toContain("github.com");
expect(markup).not.toContain("href=");
});
it("shows no projects block while the field is not published", () => {
expect(render(published())).not.toContain(">Проекты</h3>");
});
it("explains a closed card without offering to open it", () => {
const markup = render({
state: "closed",
@@ -1,5 +1,11 @@
import type { CardPreview } from "../../../shared/api/schemas";
import { EmptyState, ErrorState, LoadingState, TrustLevel } from "../../../shared/ui";
import {
EmptyState,
ErrorState,
LoadingState,
PublishedProjects,
TrustLevel,
} from "../../../shared/ui";
import {
presentCandidatePreview,
type CandidateViewPresentation,
@@ -169,6 +175,19 @@ export function EmployerCardPreview({
)}
</section>
) : null}
{card.projects ? (
<section aria-labelledby="preview-projects-title">
<h3 id="preview-projects-title">Проекты</h3>
{card.projects.length > 0 ? (
<PublishedProjects projects={card.projects} />
) : (
<p>Опубликованных проектов в карточке нет.</p>
)}
<p className={styles.hint}>
Так проекты видит компания. Адрес репозитория и его владелец ей не показываются.
</p>
</section>
) : null}
<OtherGroups card={card} />
</div>
</div>
+18
View File
@@ -1,11 +1,13 @@
export {
addExperience,
addProject,
addRole,
addSoftSkill,
addStack,
buildCandidateProfileUpdate,
mapProfileServerErrors,
moveExperience,
moveProject,
profilePointerField,
removeExperience,
removeItem,
@@ -14,6 +16,7 @@ export {
toCandidateProfileDraft,
updateExperienceDraft,
updateFieldDraft,
updateProjectDraft,
updateRoleDraft,
updateSalaryDraft,
updateSoftSkillDraft,
@@ -21,11 +24,26 @@ export {
type CandidateProfileDraft,
type ExperienceDraft,
type FieldDraft,
type ProjectDraft,
type ProfileFormIssue,
type RoleDraft,
type SoftSkillDraft,
type StackDraft,
} from "./model/profile-form";
export {
describeRepositoryStatus,
hasPendingRepositoryChecks,
maxProjectDescription,
maxProjectStack,
maxProjectStackTag,
maxProjectTitle,
maxProjects,
normalizeRepositoryUrl,
parseGitHubRepository,
repositoryChecksOf,
repositoryKey,
type RepositoryStatusView,
} from "./model/profile-projects";
export {
buildCandidateJourney,
onboardingStepLabels,
@@ -2,14 +2,18 @@ import { describe, expect, it } from "vitest";
import type { CandidateProfile } from "../../../shared/api/schemas";
import {
addExperience,
addProject,
buildCandidateProfileUpdate,
mapProfileServerErrors,
moveExperience,
moveProject,
removeItem,
reviewExperienceOverlaps,
setParallelAcknowledgement,
toCandidateProfileDraft,
updateExperienceDraft,
updateFieldDraft,
updateProjectDraft,
} from "./profile-form";
const unknownClaim = { status: "unknown", value: null, source: null } as const;
@@ -233,3 +237,193 @@ describe("candidate profile draft mapping", () => {
]);
});
});
describe("candidate profile projects", () => {
const now = new Date("2026-06-15T00:00:00Z");
function withProject(
patch: Partial<Parameters<typeof updateProjectDraft>[2]> = {},
id = "new",
draft = toCandidateProfileDraft(blankProfile()),
) {
return updateProjectDraft(addProject(draft, id), id, {
title: "Платежный шлюз",
description: "Проводки и сверки.",
stack: ["Go", "PostgreSQL"],
repository_url: "https://github.com/example-org/payments-ledger",
...patch,
});
}
it("always sends the list, so a saved profile never loses its projects", () => {
const result = buildCandidateProfileUpdate(toCandidateProfileDraft(blankProfile()), now);
expect(result.data?.projects).toEqual([]);
});
it("sends a typed project as confirmed with the canonical repository address", () => {
const result = buildCandidateProfileUpdate(
withProject({
title: " Платежный шлюз ",
repository_url: " https://github.com/example-org/ledger.git ",
}),
now,
);
expect(result.issues).toEqual([]);
expect(result.data?.projects).toEqual([
{
title: "Платежный шлюз",
description: "Проводки и сверки.",
stack: ["Go", "PostgreSQL"],
repository_url: "https://github.com/example-org/ledger",
status: "confirmed",
},
]);
});
it("sends an empty description and an empty address as null", () => {
const result = buildCandidateProfileUpdate(
withProject({ description: " ", repository_url: "", stack: [] }),
now,
);
expect(result.data?.projects).toEqual([
{
title: "Платежный шлюз",
description: null,
stack: [],
repository_url: null,
status: "confirmed",
},
]);
});
it("drops a row without any value and keeps the order of the others", () => {
let draft = withProject({}, "first");
draft = addProject(draft, "blank");
draft = withProject({ title: "Второй", repository_url: "" }, "second", draft);
const result = buildCandidateProfileUpdate(draft, now);
expect(result.data?.projects?.map((item) => item.title)).toEqual(["Платежный шлюз", "Второй"]);
expect(moveProject(draft, 0, 1).projects[1]?.id).toBe("first");
expect(moveProject(draft, 0, -1)).toBe(draft);
expect(removeItem(draft, "projects", "blank").projects).toHaveLength(2);
});
it("requires a title once any other value is given", () => {
const result = buildCandidateProfileUpdate(withProject({ title: "" }), now);
expect(result.data).toBeNull();
expect(result.issues).toEqual([
{ field: "projects.0.title", message: "Укажите название проекта." },
]);
});
it("rejects an address that is not a GitHub repository and names the field", () => {
for (const address of [
"https://gitlab.com/example-org/ledger",
"https://github.com/example-org",
"https://github.com/example-org/ledger?tab=readme",
]) {
const result = buildCandidateProfileUpdate(withProject({ repository_url: address }), now);
expect(result.data).toBeNull();
expect(result.issues.map((issue) => issue.field)).toEqual(["projects.0.repository_url"]);
}
});
it("rejects a repeated repository, also in another letter case or with .git", () => {
let draft = withProject({}, "first");
draft = withProject(
{ title: "Копия", repository_url: "https://github.com/Example-Org/Payments-Ledger.git" },
"second",
draft,
);
const result = buildCandidateProfileUpdate(draft, now);
expect(result.data).toBeNull();
expect(result.issues).toEqual([
{
field: "projects.1.repository_url",
message: "Этот репозиторий уже указан в проекте 1.",
},
]);
});
it("rejects a repeated stack tag without regard to letter case and an oversized tag", () => {
expect(buildCandidateProfileUpdate(withProject({ stack: ["Go", "go"] }), now).issues).toEqual([
{ field: "projects.0.stack", message: "Технология повторяется." },
]);
expect(
buildCandidateProfileUpdate(withProject({ stack: ["a".repeat(51)] }), now).issues[0]?.field,
).toBe("projects.0.stack");
expect(
buildCandidateProfileUpdate(
withProject({ stack: Array.from({ length: 11 }, (_, index) => `tag${index}`) }),
now,
).issues[0]?.field,
).toBe("projects.0.stack");
});
it("limits the text and the number of projects like the contract", () => {
expect(
buildCandidateProfileUpdate(withProject({ description: "я".repeat(501) }), now).issues[0]
?.field,
).toBe("projects.0.description");
expect(
buildCandidateProfileUpdate(withProject({ title: "я".repeat(101) }), now).issues[0]?.field,
).toBe("projects.0.title");
let draft = toCandidateProfileDraft(blankProfile());
for (let index = 0; index < 11; index += 1) {
draft = withProject({ title: `Проект ${index}`, repository_url: "" }, `p${index}`, draft);
}
expect(buildCandidateProfileUpdate(draft, now).data).toBeNull();
});
it("keeps an untouched suggestion unconfirmed and confirms an edited one", () => {
const profile: CandidateProfile = {
...blankProfile(),
version: 2,
projects: [
{
title: "Каталог",
description: null,
stack: ["Django"],
repository_url: "https://github.com/example-org/catalog",
repository_check: { state: "verified", checked_at: "2026-10-05T09:30:00Z" },
status: "extracted",
source: suggestion,
},
],
};
let draft = toCandidateProfileDraft(profile);
expect(buildCandidateProfileUpdate(draft, now).data?.projects).toEqual([
{
title: "Каталог",
description: null,
stack: ["Django"],
repository_url: "https://github.com/example-org/catalog",
status: "extracted",
},
]);
draft = updateProjectDraft(draft, "project-0", { description: "Витрина товаров." });
expect(buildCandidateProfileUpdate(draft, now).data?.projects?.[0]?.status).toBe("confirmed");
// The expected version of the draft travels with the projects.
expect(buildCandidateProfileUpdate(draft, now).data?.expected_version).toBe(2);
});
it("maps server pointers of a project to the field of the form", () => {
expect(
mapProfileServerErrors([
{ pointer: "/projects/1/repository_url" },
{ pointer: "/projects/0/stack/2" },
{ pointer: "/projects/3/title" },
]).map((issue) => issue.field),
).toEqual(["projects.1.repository_url", "projects.0.stack", "projects.3.title"]);
});
});
@@ -3,6 +3,15 @@ import {
type CandidateProfile,
type CandidateProfileUpdate,
} from "../../../shared/api/schemas";
import {
maxProjectDescription,
maxProjectStack,
maxProjectStackTag,
maxProjectTitle,
maxProjects,
normalizeRepositoryUrl,
repositoryKey,
} from "./profile-projects";
type ClaimStatus = CandidateProfile["full_name"]["status"];
type DecisionStatus = Exclude<ClaimStatus, "unknown">;
@@ -39,11 +48,19 @@ type ExperienceValue = Omit<
> & { specialization: CandidateProfile["experience"][number]["specialization"] | "" };
type SoftSkillValue = Pick<CandidateProfile["soft_skills"][number], "skill">;
type SalaryValue = CandidateProfile["terms"]["salary_minimum"]["value"];
/** A project as the form edits it: an empty string stands for no description or repository. */
type ProjectValue = {
title: string;
description: string;
stack: string[];
repository_url: string;
};
export type StackDraft = StackValue & ItemMetadata<StackValue>;
export type RoleDraft = RoleValue & ItemMetadata<RoleValue>;
export type ExperienceDraft = ExperienceValue & ItemMetadata<ExperienceValue>;
export type SoftSkillDraft = SoftSkillValue & ItemMetadata<SoftSkillValue>;
export type ProjectDraft = ProjectValue & ItemMetadata<ProjectValue>;
export type SalaryDraft = {
amount: string;
@@ -66,6 +83,7 @@ export type CandidateProfileDraft = {
roles: RoleDraft[];
experience: ExperienceDraft[];
softSkills: SoftSkillDraft[];
projects: ProjectDraft[];
terms: {
location: FieldDraft<string>;
relocation: FieldDraft<boolean | null>;
@@ -164,6 +182,14 @@ export function toCandidateProfileDraft(profile: CandidateProfile): CandidatePro
softSkills: profile.soft_skills.map((item, index) =>
itemDraft(`soft-skill-${index}`, index, item, { skill: item.skill }),
),
projects: profile.projects.map((item, index) =>
itemDraft(`project-${index}`, index, item, {
title: item.title,
description: item.description ?? "",
stack: [...item.stack],
repository_url: item.repository_url ?? "",
}),
),
terms: {
location: textFieldDraft(profile.terms.location),
relocation: valueFieldDraft(profile.terms.relocation),
@@ -219,6 +245,14 @@ export function updateExperienceDraft(
return dateChanged ? { ...updated, parallelAcknowledgements: {} } : updated;
}
export function updateProjectDraft(
draft: CandidateProfileDraft,
id: string,
patch: Partial<ProjectValue>,
): CandidateProfileDraft {
return updateItem(draft, "projects", id, patch);
}
export function updateSalaryDraft(
draft: CandidateProfileDraft,
patch: Partial<Pick<SalaryDraft, "amount" | "tax_basis">>,
@@ -258,7 +292,7 @@ export function updateSoftSkillDraft(
}
function updateItem<
Key extends "stack" | "roles" | "experience" | "softSkills",
Key extends "stack" | "roles" | "experience" | "softSkills" | "projects",
Item extends CandidateProfileDraft[Key][number],
Patch extends Partial<Omit<Item, keyof ItemMetadata<unknown>>>,
>(draft: CandidateProfileDraft, key: Key, id: string, patch: Patch): CandidateProfileDraft {
@@ -484,7 +518,40 @@ export function addSoftSkill(draft: CandidateProfileDraft, id: string): Candidat
};
}
export function removeItem<Key extends "stack" | "roles" | "softSkills">(
export function addProject(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
return {
...draft,
projects: [
...draft.projects,
{
id,
originalIndex: null,
title: "",
description: "",
stack: [],
repository_url: "",
status: "confirmed",
originalStatus: null,
originalValue: null,
source: null,
},
],
};
}
export function moveProject(
draft: CandidateProfileDraft,
index: number,
direction: -1 | 1,
): CandidateProfileDraft {
const targetIndex = index + direction;
if (targetIndex < 0 || targetIndex >= draft.projects.length) return draft;
const projects = [...draft.projects];
[projects[index], projects[targetIndex]] = [projects[targetIndex]!, projects[index]!];
return { ...draft, projects };
}
export function removeItem<Key extends "stack" | "roles" | "softSkills" | "projects">(
draft: CandidateProfileDraft,
key: Key,
id: string,
@@ -516,6 +583,40 @@ function itemDecision<Value>(
};
}
function isBlankProject(item: ProjectDraft): boolean {
return (
!item.title.trim() &&
!item.description.trim() &&
item.stack.every((tag) => !tag.trim()) &&
!item.repository_url.trim()
);
}
/** The value of a project as the request sends it: trimmed, with the canonical repository address. */
function projectRequestValue(item: ProjectDraft) {
const repositoryUrl = item.repository_url.trim();
return {
title: item.title.trim(),
description: item.description.replaceAll("\r\n", "\n").trim() || null,
stack: item.stack.map((tag) => tag.trim()).filter(Boolean),
repository_url: repositoryUrl ? (normalizeRepositoryUrl(repositoryUrl) ?? repositoryUrl) : null,
};
}
function projectDecision(item: ProjectDraft) {
const value = projectRequestValue(item);
const original = item.originalValue
? {
title: item.originalValue.title,
description: item.originalValue.description || null,
stack: item.originalValue.stack,
repository_url: item.originalValue.repository_url || null,
}
: null;
const extracted = item.status === "extracted" && original !== null && sameValue(value, original);
return { ...value, status: extracted ? "extracted" : "confirmed" };
}
function escapePointerSegment(value: string | number): string {
return String(value).replaceAll("~", "~0").replaceAll("/", "~1");
}
@@ -534,6 +635,7 @@ function fieldForPointer(pointer: string): string {
if (root === "experience" && index !== undefined)
return `experience.${index}.${property ?? "started_on"}`;
if (root === "soft_skills" && index !== undefined) return `softSkills.${index}.skill`;
if (root === "projects" && index !== undefined) return `projects.${index}.${property ?? "title"}`;
if (root === "terms" && index) {
if (index === "salary_minimum") {
return property === "value"
@@ -558,6 +660,76 @@ function monthIsFuture(value: string, now: Date): boolean {
return month > current;
}
/**
* Client checks of the projects that the server repeats: the title, the text
* limits, the stack tags, the GitHub address, and the repeat rules. A project
* row without any value is dropped on save and is not an issue.
*/
function projectIssues(draft: CandidateProfileDraft): ProfileFormIssue[] {
const issues: ProfileFormIssue[] = [];
const add = (index: number, property: string, message: string) =>
issues.push({ field: `projects.${index}.${property}`, message });
const repositories = new Map<string, number>();
const projects = new Map<string, number>();
const used = draft.projects.filter((item) => !isBlankProject(item));
if (used.length > maxProjects) {
issues.push({
field: "projects.0.title",
message: `Можно добавить не больше ${maxProjects} проектов.`,
});
}
draft.projects.forEach((item, index) => {
if (isBlankProject(item)) return;
const value = projectRequestValue(item);
if (!value.title) add(index, "title", "Укажите название проекта.");
else if (value.title.length > maxProjectTitle || /[\r\n]/.test(value.title)) {
add(index, "title", `Название: одна строка, не длиннее ${maxProjectTitle} символов.`);
}
if ((value.description ?? "").length > maxProjectDescription) {
add(index, "description", `Описание не длиннее ${maxProjectDescription} символов.`);
}
if (value.stack.length > maxProjectStack) {
add(index, "stack", `Не больше ${maxProjectStack} технологий в проекте.`);
}
const tags = new Set<string>();
for (const tag of value.stack) {
const key = tag.toLocaleLowerCase("ru");
if (tag.length > maxProjectStackTag || /[\r\n]/.test(tag)) {
add(index, "stack", `Технология: одна строка, не длиннее ${maxProjectStackTag} символов.`);
break;
}
if (tags.has(key)) {
add(index, "stack", "Технология повторяется.");
break;
}
tags.add(key);
}
if (item.repository_url.trim()) {
const key = repositoryKey(item.repository_url);
if (!key) {
add(
index,
"repository_url",
"Нужен адрес вида https://github.com/владелец/репозиторий, без параметров и других сайтов.",
);
} else if (repositories.has(key)) {
add(
index,
"repository_url",
`Этот репозиторий уже указан в проекте ${(repositories.get(key) ?? 0) + 1}.`,
);
} else {
repositories.set(key, index);
}
} else {
const key = JSON.stringify([value.title, value.description, value.stack]);
if (projects.has(key)) add(index, "title", "Такой проект уже добавлен.");
else projects.set(key, index);
}
});
return issues;
}
function customValidationIssues(draft: CandidateProfileDraft, now: Date): ProfileFormIssue[] {
const issues: ProfileFormIssue[] = [];
const duplicates = <Value>(
@@ -612,6 +784,7 @@ function customValidationIssues(draft: CandidateProfileDraft, now: Date): Profil
});
}
});
issues.push(...projectIssues(draft));
if (draft.terms.salaryMinimum.amount.trim() && !draft.terms.salaryMinimum.tax_basis) {
issues.push({
field: "terms.salaryMinimum.tax_basis",
@@ -673,6 +846,7 @@ export function buildCandidateProfileUpdate(
second_period: overlap.secondPeriod,
})),
soft_skills: draft.softSkills.filter((item) => item.skill.trim()).map(itemDecision),
projects: draft.projects.filter((item) => !isBlankProject(item)).map(projectDecision),
terms: {
location: fieldDecision(draft.terms.location, draft.terms.location.value.trim()),
relocation: fieldDecision(draft.terms.relocation),
@@ -692,11 +866,15 @@ export function buildCandidateProfileUpdate(
const issues = customValidationIssues(draft, now);
const parsed = CandidateProfileUpdateSchema.safeParse(data);
if (!parsed.success) {
// The schema repeats what a specific check already said about a field.
const reported = new Set(issues.map((issue) => issue.field));
issues.push(
...parsed.error.issues.map((issue) => ({
field: fieldForPointer(zodPointer(issue.path)),
message: "Проверьте значение и формат этого поля.",
})),
...parsed.error.issues
.map((issue) => ({
field: fieldForPointer(zodPointer(issue.path)),
message: "Проверьте значение и формат этого поля.",
}))
.filter((issue) => !reported.has(issue.field)),
);
}
return {
@@ -0,0 +1,123 @@
import { describe, expect, it } from "vitest";
import type { CandidateProfile } from "../../../shared/api/schemas";
import {
describeRepositoryStatus,
hasPendingRepositoryChecks,
normalizeRepositoryUrl,
parseGitHubRepository,
repositoryChecksOf,
repositoryKey,
} from "./profile-projects";
const source = {
origin: "manual",
trust_level: 0,
quote: null,
extraction_version: null,
confirmed_at: "2026-10-05T09:30:00Z",
} as const;
function projects(
...items: Array<[string | null, "pending" | "verified" | "not_found" | "unavailable" | null]>
): Pick<CandidateProfile, "projects"> {
return {
projects: items.map(([url, state], index) => ({
title: `Проект ${index}`,
description: null,
stack: [],
repository_url: url,
repository_check: state ? { state, checked_at: null } : null,
status: "confirmed" as const,
source,
})),
};
}
describe("GitHub repository address", () => {
it("accepts only https://github.com/<owner>/<repository> and canonicalizes it", () => {
expect(normalizeRepositoryUrl("https://github.com/example-org/payments-ledger")).toBe(
"https://github.com/example-org/payments-ledger",
);
expect(normalizeRepositoryUrl(" https://github.com/Example-Org/Ledger.git ")).toBe(
"https://github.com/Example-Org/Ledger",
);
expect(normalizeRepositoryUrl("https://github.com/example-org/ledger/")).toBe(
"https://github.com/example-org/ledger",
);
expect(parseGitHubRepository("https://github.com/a/b.c_d-e")).toEqual({
owner: "a",
name: "b.c_d-e",
});
});
it.each([
"",
"github.com/example-org/ledger",
"http://github.com/example-org/ledger",
"https://www.github.com/example-org/ledger",
"https://gitlab.com/example-org/ledger",
"https://github.com.evil.example/example-org/ledger",
"https://user:token@github.com/example-org/ledger",
"https://github.com:8443/example-org/ledger",
"https://github.com/example-org",
"https://github.com/example-org/ledger/tree/main",
"https://github.com/example-org/ledger?tab=readme",
"https://github.com/example-org/ledger#readme",
"https://github.com/-owner/ledger",
"https://github.com/own--er/ledger",
"https://github.com/example-org/..",
"https://github.com/example-org/led ger",
])("rejects %j", (value) => {
expect(normalizeRepositoryUrl(value)).toBeNull();
});
it("treats letter case and a .git suffix as the same repository", () => {
expect(repositoryKey("https://github.com/Example-Org/Ledger.git")).toBe(
repositoryKey("https://github.com/example-org/ledger/"),
);
expect(repositoryKey("https://github.com/example-org/ledger")).toBe("example-org/ledger");
});
});
describe("repository checks of saved projects", () => {
it("indexes the checks by repository identity and skips projects without one", () => {
const checks = repositoryChecksOf(
projects(
["https://github.com/example-org/ledger", "verified"],
[null, null],
["https://github.com/example-org/other", null],
),
);
expect([...checks.keys()]).toEqual(["example-org/ledger"]);
expect(checks.get("example-org/ledger")?.state).toBe("verified");
});
it("reports a pending check so the screen keeps reloading the statuses", () => {
expect(
hasPendingRepositoryChecks(projects(["https://github.com/example-org/a", "pending"])),
).toBe(true);
expect(
hasPendingRepositoryChecks(projects(["https://github.com/example-org/a", "verified"])),
).toBe(false);
expect(hasPendingRepositoryChecks(undefined)).toBe(false);
});
it("describes every state in words and never as a proof of authorship", () => {
const states = ["pending", "verified", "not_found", "unavailable"] as const;
const views = states.map((state) => describeRepositoryStatus({ state, checked_at: null }));
expect(views.map((view) => view.label)).toEqual([
"Проверяется",
"Публичный репозиторий найден",
"Не найден или закрыт",
"Лимит GitHub, повторим позже",
]);
expect(views.map((view) => view.tone)).toEqual(["neutral", "success", "danger", "neutral"]);
expect(views[1]?.note).toContain("Авторство не проверяется");
expect(describeRepositoryStatus(undefined)).toMatchObject({
state: "unsaved",
label: "Проверка после сохранения",
});
});
});
@@ -0,0 +1,131 @@
import type { CandidateProfile, ProfileRepositoryCheck } from "../../../shared/api/schemas";
/*
* Project rules of the profile form. They mirror the contract and the server
* so a bad value is caught before the request: the same host, the same owner
* and repository patterns, and the same repeat rules.
*/
export const maxProjects = 10;
export const maxProjectTitle = 100;
export const maxProjectDescription = 500;
export const maxProjectStack = 10;
export const maxProjectStackTag = 50;
const repositoryPrefix = "https://github.com/";
const ownerPattern = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
const namePattern = /^[A-Za-z0-9._-]{1,100}$/;
export type GitHubRepository = { owner: string; name: string };
/**
* Parses https://github.com/<owner>/<repository> with an optional trailing
* slash or `.git` suffix. Any other host, scheme, port, credentials, query,
* fragment, or extra path segment is rejected, as the server does.
*/
export function parseGitHubRepository(raw: string): GitHubRepository | null {
const value = raw.trim();
if (value.length > 160 || !value.startsWith(repositoryPrefix)) return null;
const path = value.slice(repositoryPrefix.length).replace(/\/$/, "");
const parts = path.split("/");
if (parts.length !== 2) return null;
const owner = parts[0] ?? "";
const name = (parts[1] ?? "").replace(/\.git$/, "");
if (!ownerPattern.test(owner) || owner.includes("--")) return null;
if (!namePattern.test(name) || name === "." || name === "..") return null;
return { owner, name };
}
/** The canonical address the server stores, or null for an invalid address. */
export function normalizeRepositoryUrl(raw: string): string | null {
const repository = parseGitHubRepository(raw);
return repository ? `${repositoryPrefix}${repository.owner}/${repository.name}` : null;
}
/** The identity of a repository: GitHub treats letter case as the same repository. */
export function repositoryKey(raw: string): string | null {
const repository = parseGitHubRepository(raw);
return repository ? `${repository.owner}/${repository.name}`.toLowerCase() : null;
}
/** Latest server checks of the saved repositories, by repository identity. */
export function repositoryChecksOf(
profile: Pick<CandidateProfile, "projects">,
): ReadonlyMap<string, ProfileRepositoryCheck> {
const checks = new Map<string, ProfileRepositoryCheck>();
for (const project of profile.projects) {
if (!project.repository_url || !project.repository_check) continue;
const key = repositoryKey(project.repository_url);
if (key) checks.set(key, project.repository_check);
}
return checks;
}
/** True while at least one saved repository waits for its check. */
export function hasPendingRepositoryChecks(
profile: Pick<CandidateProfile, "projects"> | undefined,
): boolean {
return Boolean(
profile?.projects.some((project) => project.repository_check?.state === "pending"),
);
}
export type RepositoryStatusView = {
state: ProfileRepositoryCheck["state"] | "unsaved";
tone: "neutral" | "success" | "danger";
label: string;
note: string;
checkedAt: string | null;
};
/**
* Words for the check of one repository. `unsaved` stands for an address that
* the server has not stored yet, so no check exists for it.
*/
export function describeRepositoryStatus(
check: ProfileRepositoryCheck | undefined,
): RepositoryStatusView {
if (!check) {
return {
state: "unsaved",
tone: "neutral",
label: "Проверка после сохранения",
note: "Адрес проверится в фоне, когда вы сохраните профиль.",
checkedAt: null,
};
}
switch (check.state) {
case "pending":
return {
state: "pending",
tone: "neutral",
label: "Проверяется",
note: "Проверка идет в фоне. Статус обновится сам.",
checkedAt: check.checked_at,
};
case "verified":
return {
state: "verified",
tone: "success",
label: "Публичный репозиторий найден",
note: "Это значит только, что репозиторий существует и открыт. Авторство не проверяется.",
checkedAt: check.checked_at,
};
case "not_found":
return {
state: "not_found",
tone: "danger",
label: "Не найден или закрыт",
note: "GitHub не нашел публичный репозиторий: он может быть закрытым, переименованным или удаленным. Проект остается в профиле без отметки о репозитории.",
checkedAt: check.checked_at,
};
case "unavailable":
return {
state: "unavailable",
tone: "neutral",
label: "Лимит GitHub, повторим позже",
note: "GitHub сейчас не ответил, например из-за лимита запросов. Сервер повторит проверку сам.",
checkedAt: check.checked_at,
};
}
}
+4
View File
@@ -15,6 +15,7 @@ export type {
MatchConfirmedComponentsModel,
MatchGroup,
MatchSearchModel,
MatchSemanticEvidenceModel,
MatchSearchSourceModel,
MatchUnconfirmedCardModel,
} from "./model/adapter";
@@ -37,8 +38,11 @@ export {
evidenceRows,
formatScore,
otherUnknowns,
semanticBlock,
type ComponentRow,
type EvidenceRow,
type SemanticBlock,
type SemanticRow,
} from "./model/explanation";
export {
gradeCodes,
@@ -203,6 +203,82 @@ describe("match response adapter", () => {
expect(matchSearchFromTransport(roundTrip)).toEqual(model);
});
it("round-trips the semantic evidence of an entry in the server order", () => {
const response = matchResponseFixture();
const [candidate] = response.groups.main;
if (!candidate) throw new Error("Fixture main card is missing.");
const evidence = [
{
requirement_kind: "task" as const,
requirement_text: "Разработать сервис сверки платежей",
item_kind: "project" as const,
project_title: "Платежный шлюз",
repository_verified: true,
similarity: "high" as const,
},
{
requirement_kind: "required_skill" as const,
requirement_text: "PostgreSQL",
item_kind: "stack" as const,
project_title: null,
repository_verified: false,
similarity: "medium" as const,
},
];
const withEvidence = {
...response,
groups: { ...response.groups, main: [{ ...candidate, semantic_evidence: evidence }] },
};
const model = matchSearchFromTransport(withEvidence);
expect(model.cards[0]?.semanticEvidence).toEqual([
{
requirementKind: "task",
requirementText: "Разработать сервис сверки платежей",
itemKind: "project",
projectTitle: "Платежный шлюз",
repositoryVerified: true,
similarity: "high",
},
{
requirementKind: "required_skill",
requirementText: "PostgreSQL",
itemKind: "stack",
projectTitle: null,
repositoryVerified: false,
similarity: "medium",
},
]);
expect(matchSearchToTransport(model)).toEqual(withEvidence);
});
it("rejects evidence that carries a repository address or an owner", () => {
const response = matchResponseFixture();
const [candidate] = response.groups.main;
if (!candidate) throw new Error("Fixture main card is missing.");
const item = {
requirement_kind: "task",
requirement_text: "Разработать сервис сверки платежей",
item_kind: "project",
project_title: "Платежный шлюз",
repository_verified: true,
similarity: "high",
};
for (const extra of [
{ repository_url: "https://github.com/example-org/payments-ledger" },
{ repository_owner: "example-org" },
]) {
expectInvalidResponse({
...response,
groups: {
...response.groups,
main: [{ ...candidate, semantic_evidence: [{ ...item, ...extra }] }],
},
});
}
});
it("keeps the truncation flag, which carries no count", () => {
const response = { ...matchResponseFixture(), truncated: true };
const model = matchSearchFromTransport(response);
+49 -4
View File
@@ -43,10 +43,26 @@ type MatchPublicContext = {
};
type MatchEvidence = ConfirmedCandidate["evidence_summary"][number];
type MatchSemanticEvidenceTransport = ConfirmedCandidate["semantic_evidence"][number];
type MatchUnknownFlag = ConfirmedCandidate["unknown_flags"][number];
type ConfirmedComponents = ConfirmedCandidate["components"];
type UnconfirmedComponents = UnconfirmedCandidate["components"];
/**
* Why a requirement of the need matched a published card item. The server
* computes it from stored vectors; it carries only public card values, so it
* has no repository address and no owner.
*/
export type MatchSemanticEvidenceModel = {
readonly requirementKind: MatchSemanticEvidenceTransport["requirement_kind"];
readonly requirementText: string;
readonly itemKind: MatchSemanticEvidenceTransport["item_kind"];
/** Published project title for a project item, otherwise null. */
readonly projectTitle: string | null;
readonly repositoryVerified: boolean;
readonly similarity: MatchSemanticEvidenceTransport["similarity"];
};
export type MatchConfirmedComponentsModel = Omit<ConfirmedComponents, "rank_score"> & {
readonly rankScore: ConfirmedComponents["rank_score"];
};
@@ -61,6 +77,8 @@ export type MatchConfirmedCardModel = {
readonly strength: ConfirmedCandidate["strength"];
readonly publicContext: MatchPublicContext;
readonly evidenceSummary: readonly MatchEvidence[];
/** In the order the server sent: strongest similarity first. */
readonly semanticEvidence: readonly MatchSemanticEvidenceModel[];
readonly components: MatchConfirmedComponentsModel;
readonly unknownFlags: readonly MatchUnknownFlag[];
};
@@ -75,6 +93,7 @@ export type MatchUnconfirmedCardModel = {
readonly strength: null;
readonly publicContext: MatchPublicContext;
readonly evidenceSummary: readonly MatchEvidence[];
readonly semanticEvidence: readonly MatchSemanticEvidenceModel[];
readonly components: UnconfirmedComponents;
readonly unknownFlags: readonly MatchUnknownFlag[];
};
@@ -215,6 +234,32 @@ function publicContextToTransport(
};
}
function semanticEvidenceFromTransport(
items: readonly MatchSemanticEvidenceTransport[],
): MatchSemanticEvidenceModel[] {
return items.map((item) => ({
requirementKind: item.requirement_kind,
requirementText: item.requirement_text,
itemKind: item.item_kind,
projectTitle: item.project_title,
repositoryVerified: item.repository_verified,
similarity: item.similarity,
}));
}
function semanticEvidenceToTransport(
items: readonly MatchSemanticEvidenceModel[],
): MatchSemanticEvidenceTransport[] {
return items.map((item) => ({
requirement_kind: item.requirementKind,
requirement_text: item.requirementText,
item_kind: item.itemKind,
project_title: item.projectTitle,
repository_verified: item.repositoryVerified,
similarity: item.similarity,
}));
}
function confirmedFromTransport(
group: "main" | "near",
candidate: ConfirmedCandidate,
@@ -230,6 +275,7 @@ function confirmedFromTransport(
strength: candidate.strength,
publicContext: publicContextFromTransport(candidate.public_context),
evidenceSummary: candidate.evidence_summary.map(({ code, state }) => ({ code, state })),
semanticEvidence: semanticEvidenceFromTransport(candidate.semantic_evidence),
components: { ...components, rankScore },
unknownFlags: candidate.unknown_flags.map(({ component, reason }) => ({ component, reason })),
};
@@ -246,6 +292,7 @@ function unconfirmedFromTransport(candidate: UnconfirmedCandidate): MatchUnconfi
strength: null,
publicContext: publicContextFromTransport(candidate.public_context),
evidenceSummary: candidate.evidence_summary.map(({ code, state }) => ({ code, state })),
semanticEvidence: semanticEvidenceFromTransport(candidate.semantic_evidence),
components: { fit: candidate.components.fit, coverage: candidate.components.coverage },
unknownFlags: candidate.unknown_flags.map(({ component, reason }) => ({ component, reason })),
};
@@ -275,8 +322,7 @@ function confirmedToTransport(candidate: MatchConfirmedCardModel): ConfirmedCand
strength: candidate.strength,
public_context: publicContextToTransport(candidate.publicContext),
evidence_summary: candidate.evidenceSummary.map(({ code, state }) => ({ code, state })),
// The card model does not carry the semantic explanation yet.
semantic_evidence: [],
semantic_evidence: semanticEvidenceToTransport(candidate.semanticEvidence),
components: { ...components, rank_score: rankScore },
unknown_flags: candidate.unknownFlags.map(({ component, reason }) => ({ component, reason })),
};
@@ -292,8 +338,7 @@ function unconfirmedToTransport(candidate: MatchUnconfirmedCardModel): Unconfirm
strength: null,
public_context: publicContextToTransport(candidate.publicContext),
evidence_summary: candidate.evidenceSummary.map(({ code, state }) => ({ code, state })),
// The card model does not carry the semantic explanation yet.
semantic_evidence: [],
semantic_evidence: semanticEvidenceToTransport(candidate.semanticEvidence),
components: { fit: candidate.components.fit, coverage: candidate.components.coverage },
unknown_flags: candidate.unknownFlags.map(({ component, reason }) => ({ component, reason })),
};
@@ -27,6 +27,15 @@ export type CardDetails = {
experience: string | null;
workFormats: readonly string[] | null;
salaryCompatibility: string | null;
/** Published projects in the candidate's order; null when the card has none to show. */
projects:
| readonly {
title: string;
description: string | null;
stack: readonly string[];
repositoryVerified: boolean;
}[]
| null;
};
/**
@@ -54,6 +63,13 @@ export function presentCard(card: AnonymousCardContent): CardDetails {
salaryCompatibility: card.salary_compatibility
? salaryCompatibilityLabels[card.salary_compatibility]
: null,
projects:
card.projects?.map((project) => ({
title: project.title,
description: project.description,
stack: [...project.stack],
repositoryVerified: project.repository_verified,
})) ?? null,
};
}
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
import { componentRows, evidenceRows, formatScore, otherUnknowns } from "./explanation";
import {
componentRows,
evidenceRows,
formatScore,
otherUnknowns,
semanticBlock,
} from "./explanation";
import { matchModelFixture } from "./match.fixtures";
function cardAt(index: number) {
@@ -79,3 +85,59 @@ describe("match explanation", () => {
]);
});
});
describe("semantic evidence block", () => {
it("lists the rows in the order the server sent, with kind, label, and band", () => {
const block = semanticBlock(cardAt(1));
expect(block?.kind).toBe("evidence");
if (block?.kind !== "evidence") throw new Error("Expected evidence rows.");
expect(
block.rows.map((row) => [
row.requirementLabel,
row.itemKindLabel,
row.itemLabel,
row.similarityLabel,
]),
).toEqual([
["Задача", "Проект", "Платежный шлюз", "Высокое сходство"],
["Обязательный навык", "Стек", "Технологии карточки", "Среднее сходство"],
["Желательный навык", "Проект", "Внутренняя витрина", "Среднее сходство"],
["Задача", "Роль", "Специализации и грейды карточки", "Среднее сходство"],
]);
});
it("marks only a verified project as backed by a public repository", () => {
const block = semanticBlock(cardAt(1));
if (block?.kind !== "evidence") throw new Error("Expected evidence rows.");
expect(block.rows.map((row) => row.repositoryVerified)).toEqual([true, false, false, false]);
});
it("never marks a stack or roles item, even if a verified flag came with it", () => {
const card = cardAt(1);
const forged = {
...card,
semanticEvidence: card.semanticEvidence.map((item) => ({
...item,
repositoryVerified: true,
})),
};
const block = semanticBlock(forged);
if (block?.kind !== "evidence") throw new Error("Expected evidence rows.");
expect(block.rows.map((row) => row.repositoryVerified)).toEqual([true, false, true, false]);
});
it("keeps the unavailable wording when the semantic component is unknown for lack of ML", () => {
expect(semanticBlock(cardAt(0))).toEqual({
kind: "unavailable",
text: "смысловой анализ недоступен",
});
});
it("shows no block when there is nothing to say", () => {
// An unconfirmed entry without evidence and without a semantics flag.
expect(semanticBlock(cardAt(3))).toBeNull();
});
});
@@ -3,6 +3,10 @@ import type { MatchCardModel } from "./adapter";
import {
evidenceCodeLabels,
evidenceStateLabels,
semanticItemKindLabels,
semanticItemPlainLabels,
semanticRequirementLabels,
semanticSimilarityLabels,
unknownComponentLabels,
unknownReasonLabels,
} from "./labels";
@@ -157,3 +161,52 @@ export function evidenceRows(card: MatchCardModel): EvidenceRow[] {
stateLabel: evidenceStateLabels[item.state],
}));
}
export type SemanticRow = {
key: string;
requirementLabel: string;
requirementText: string;
itemKindLabel: string;
/** The title of a published project, or a plain label of the stack or the roles. */
itemLabel: string;
/** True only for a project whose linked repository the server found public. */
repositoryVerified: boolean;
similarity: "high" | "medium";
similarityLabel: string;
};
export type SemanticBlock =
{ kind: "evidence"; rows: SemanticRow[] } | { kind: "unavailable"; text: string };
/**
* The "matches by meaning" block of one entry. The rows keep the order and
* the limit that the server sent. With no rows the block appears only when
* the server names the semantic component unknown because ML was down, with
* the same words as the explanation; an empty list from a bank search or from
* a need without a match shows no block at all.
*/
export function semanticBlock(card: MatchCardModel): SemanticBlock | null {
if (card.semanticEvidence.length > 0) {
return {
kind: "evidence",
rows: card.semanticEvidence.map((item, index) => ({
key: `${index}:${item.requirementKind}:${item.requirementText}`,
requirementLabel: semanticRequirementLabels[item.requirementKind],
requirementText: item.requirementText,
itemKindLabel: semanticItemKindLabels[item.itemKind],
itemLabel:
item.itemKind === "project"
? (item.projectTitle ?? semanticItemKindLabels.project)
: semanticItemPlainLabels[item.itemKind],
repositoryVerified: item.itemKind === "project" && item.repositoryVerified,
similarity: item.similarity,
similarityLabel: semanticSimilarityLabels[item.similarity],
})),
};
}
const flag = flagFor(card, "semantics");
if (flag?.reason === "ml_unavailable") {
return { kind: "unavailable", text: describeUnknownReason(flag) };
}
return null;
}
@@ -5,6 +5,7 @@ import type {
MatchEvidenceCode,
MatchEvidenceState,
MatchSearchStackTag,
MatchSemanticItemKind,
MatchStrength,
MatchUnknownComponent,
MatchUnknownReason,
@@ -154,3 +155,29 @@ export const unknownReasonLabels: Readonly<Record<MatchUnknownReason, string>> =
no_response_history: "нет истории ответов",
percentile_not_computed: "перцентиль пока не рассчитывается",
};
export const semanticRequirementLabels = {
required_skill: "Обязательный навык",
desired_skill: "Желательный навык",
task: "Задача",
} as const;
export const semanticItemKindLabels: Readonly<Record<MatchSemanticItemKind, string>> = {
project: "Проект",
stack: "Стек",
roles: "Роль",
};
/**
* Public labels of the card items that carry no title of their own: the
* stack and the roles are shown as the card shows them to the organization.
*/
export const semanticItemPlainLabels: Readonly<Record<"stack" | "roles", string>> = {
stack: "Технологии карточки",
roles: "Специализации и грейды карточки",
};
export const semanticSimilarityLabels = {
high: "Высокое сходство",
medium: "Среднее сходство",
} as const;
@@ -89,7 +89,40 @@ export function matchResponseFixture(
{ code: "confirmed_category", state: "supports" },
{ code: "required_skill_evidence", state: "partial" },
],
semantic_evidence: [],
semantic_evidence: [
{
requirement_kind: "task",
requirement_text: "Разработать сервис сверки платежей",
item_kind: "project",
project_title: "Платежный шлюз",
repository_verified: true,
similarity: "high",
},
{
requirement_kind: "required_skill",
requirement_text: "Проектирование схем PostgreSQL",
item_kind: "stack",
project_title: null,
repository_verified: false,
similarity: "medium",
},
{
requirement_kind: "desired_skill",
requirement_text: "Наставничество в команде",
item_kind: "project",
project_title: "Внутренняя витрина",
repository_verified: false,
similarity: "medium",
},
{
requirement_kind: "task",
requirement_text: "Поддерживать сервисы доставки",
item_kind: "roles",
project_title: null,
repository_verified: false,
similarity: "medium",
},
],
components: {
fit: 0.4,
coverage: 0.18,
@@ -0,0 +1,70 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderToString } from "react-dom/server";
import { describe, expect, it } from "vitest";
import type { AnonymousCardContent } from "../../../shared/api/schemas";
import { matchCardQueryKeys } from "../api/card";
import { CandidateCardDetails } from "./candidate-card-details";
const accountId = "11111111-1111-4111-8111-111111111111";
const organizationId = "22222222-2222-4222-8222-222222222222";
const handle = "cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
const card: AnonymousCardContent = {
pseudonym: handle,
categories: null,
stack: ["go"],
self_assessment: null,
experience_band: "3_6",
work_formats: null,
salary_compatibility: null,
projects: [
{
title: "Платежный шлюз",
description: "Проводки и сверки.\nВыплаты по расписанию.",
stack: ["Go", "PostgreSQL"],
repository_verified: true,
},
{ title: "Каталог", description: null, stack: [], repository_verified: false },
],
};
function render(content: AnonymousCardContent): string {
const client = new QueryClient();
client.setQueryData(matchCardQueryKeys.card(accountId, organizationId, handle), content);
return renderToString(
<QueryClientProvider client={client}>
<CandidateCardDetails
id="card-panel"
accountId={accountId}
organizationId={organizationId}
candidateHandle={handle}
open
/>
</QueryClientProvider>,
).replaceAll("<!-- -->", "");
}
describe("candidate card details", () => {
it("lists the published projects with tags and a badge for a verified repository", () => {
const html = render(card);
expect(html).toContain(">Проекты</h6>");
expect(html).toContain("Платежный шлюз");
expect(html).toContain("Выплаты по расписанию.");
expect(html).toContain(">PostgreSQL<");
expect(html.match(/Подтвержден публичным репозиторием/g)).toHaveLength(1);
expect(html).toContain("Каталог");
});
it("shows no address or link of a repository", () => {
const html = render(card);
expect(html).not.toContain("github");
expect(html).not.toMatch(/href="https?:/);
});
it("shows no projects block while the card carries none", () => {
expect(render({ ...card, projects: null })).not.toContain(">Проекты</h6>");
expect(render({ ...card, projects: [] })).not.toContain(">Проекты</h6>");
});
});
@@ -4,6 +4,7 @@ import {
ForbiddenState,
isAccessDenied,
LoadingState,
PublishedProjects,
StatusView,
TrustLevel,
} from "../../../shared/ui";
@@ -155,6 +156,12 @@ export function CandidateCardDetails({
<dt>Зарплатные ожидания</dt>
<dd>{details.salaryCompatibility ?? "Нет значения в карточке"}</dd>
</dl>
{details.projects && details.projects.length > 0 ? (
<section aria-label="Проекты кандидата">
<h6 className={styles.subtitle}>Проекты</h6>
<PublishedProjects projects={details.projects} />
</section>
) : null}
{hasCategories ? (
<section aria-label="Подтверждающие факты оценки">
<h6 className={styles.subtitle}>Подтверждающие факты оценки</h6>
@@ -223,3 +223,72 @@
flex: 1 1 100%;
}
}
/* "Matches by meaning": a requirement of the need, an arrow, the card item
* that matched it, and the similarity band as a tag. The words carry the
* meaning; the arrow only repeats the direction. */
.semantic {
display: grid;
gap: var(--space-2);
min-width: 0;
padding-block-start: var(--space-2);
border-block-start: var(--line-thin) solid var(--color-divider);
}
.semantic-title {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-medium);
letter-spacing: var(--letter-spacing-label);
text-transform: uppercase;
}
.semantic-list {
display: grid;
gap: var(--space-3);
margin: 0;
padding: 0;
list-style: none;
}
.semantic-list li {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: var(--space-1) var(--space-3);
min-width: 0;
}
.semantic-side {
display: flex;
flex-wrap: wrap;
gap: 0 var(--space-2);
align-items: baseline;
min-width: 0;
}
.semantic-side .caption {
flex: none;
}
.semantic-text {
min-width: 0;
color: var(--color-text);
overflow-wrap: anywhere;
}
.semantic-arrow {
color: var(--color-text-secondary);
}
.semantic-badge,
.semantic-band {
display: inline-flex;
}
@media (width >= 48rem) {
.semantic-list li {
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr) auto;
align-items: baseline;
}
}
+43 -1
View File
@@ -2,7 +2,7 @@ import type { ReactNode } from "react";
import type { MatchSearchStackTag } from "../../../shared/api/schemas";
import { Card, Mono, Tag, TrustLevel, VisuallyHidden } from "../../../shared/ui";
import type { MatchCardModel } from "../model/adapter";
import { evidenceRows, type EvidenceRow } from "../model/explanation";
import { evidenceRows, semanticBlock, type EvidenceRow } from "../model/explanation";
import {
experienceBandLabels,
gradeLabels,
@@ -61,6 +61,7 @@ export function MatchCardView({
const confirmed = card.confirmationStatus === "confirmed";
const context = card.publicContext;
const sources = evidenceRows(card);
const semantic = semanticBlock(card);
const shortSpecialization = specializationShortLabels[card.specialization];
const compatibility = context.salaryCompatibility;
@@ -180,6 +181,47 @@ export function MatchCardView({
) : (
<p className={styles.unknown}>Сервер не вернул пояснений по источникам.</p>
)}
{semantic ? (
<div className={styles.semantic}>
<h6 id={`${headingId}-semantic`} className={styles["semantic-title"]}>
Совпадения по смыслу
</h6>
{semantic.kind === "evidence" ? (
<ul className={styles["semantic-list"]} aria-labelledby={`${headingId}-semantic`}>
{semantic.rows.map((row) => (
<li key={row.key} data-similarity={row.similarity}>
<span className={styles["semantic-side"]}>
<span className={styles.caption}>{row.requirementLabel}</span>
<span className={styles["semantic-text"]}>{row.requirementText}</span>
</span>
<span className={styles["semantic-arrow"]} aria-hidden="true">
→
</span>
<VisuallyHidden>совпало с:</VisuallyHidden>
<span className={styles["semantic-side"]}>
<span className={styles.caption}>{row.itemKindLabel}</span>
<span className={styles["semantic-text"]}>{row.itemLabel}</span>
{row.repositoryVerified ? (
<span className={styles["semantic-badge"]}>
<Tag tone="success" dot>
Публичный репозиторий
</Tag>
</span>
) : null}
</span>
<span className={styles["semantic-band"]}>
<Tag tone={row.similarity === "high" ? "accent" : "neutral"}>
{row.similarityLabel}
</Tag>
</span>
</li>
))}
</ul>
) : (
<p className={styles.unknown}>Совпадения по смыслу: {semantic.text}.</p>
)}
</div>
) : null}
</Card>
</div>
{actions ? <div className={styles.actions}>{actions}</div> : null}