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}
@@ -0,0 +1,23 @@
import type { ProfileFormIssue } from "../../../entities/candidate";
/* Small helpers of the form fields: issue lookup and aria-describedby ids. */
export function errorFor(issues: readonly ProfileFormIssue[], field: string): string | undefined {
return issues.find((issue) => issue.field === field)?.message;
}
export function describedBy(
id: string,
error?: string,
suggestion?: boolean,
hint?: boolean,
): string | undefined {
const values = [
hint ? `${id}-hint` : "",
suggestion ? `${id}-suggestion` : "",
error ? `${id}-error` : "",
]
.filter(Boolean)
.join(" ");
return values || undefined;
}
@@ -8,6 +8,8 @@ describe("profile steps", () => {
expect(profileStepOfField("roles.1.self_assessed_grade")).toBe("roles");
expect(profileStepOfField("experience.2.ended_on")).toBe("experience");
expect(profileStepOfField("experience.overlaps")).toBe("experience");
expect(profileStepOfField("projects.1.repository_url")).toBe("projects");
expect(profileStepOfField("projects")).toBe("projects");
expect(profileStepOfField("stack.0.tag")).toBe("skills");
expect(profileStepOfField("softSkills.3.skill")).toBe("skills");
expect(profileStepOfField("terms.salaryMinimum.amount")).toBe("terms");
@@ -1,5 +1,6 @@
/** Steps of the profile form, in order. */
export type ProfileStepId = "contacts" | "roles" | "experience" | "skills" | "terms" | "review";
export type ProfileStepId =
"contacts" | "roles" | "experience" | "projects" | "skills" | "terms" | "review";
/**
* The step that owns a profile form field, so a client or server issue opens
@@ -15,6 +16,8 @@ export function profileStepOfField(field: string): ProfileStepId {
return "roles";
case "experience":
return "experience";
case "projects":
return "projects";
case "stack":
case "softSkills":
return "skills";
@@ -0,0 +1,137 @@
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { ApiRequestError } from "../../../shared/api";
import { requestMyRepositoryChecks } from "../../../shared/api/endpoints/candidate/candidate";
import {
describeRecheckFailure,
describeScheduled,
formatCountdown,
secondsLeft,
} from "./repository-recheck";
const checksUrl = "http://localhost/api/v1/me/profile/repository-checks";
const server = setupServer();
beforeAll(() => server.listen({ onUnhandledFrame: "error" }));
afterEach(() => {
vi.unstubAllGlobals();
server.resetHandlers();
});
afterAll(() => server.close());
function useServerOrigin() {
const interceptedFetch = globalThis.fetch;
// Node has no document origin for the relative URLs of the browser client.
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
interceptedFetch(new URL(input, "http://localhost"), init),
);
}
function rateLimited(retryAfter: string | null) {
return HttpResponse.json(
{
type: "urn:lincodex:problem:rate_limited",
title: "Too many requests",
status: 429,
code: "rate_limited",
detail: "Repository checks run at most once in 10 minutes.",
},
{
status: 429,
headers: {
"content-type": "application/problem+json",
...(retryAfter === null ? {} : { "retry-after": retryAfter }),
},
},
);
}
describe("repository recheck against the API", () => {
it("posts the request with the CSRF token and reads the number of scheduled checks", async () => {
let csrf: string | null = null;
server.use(
http.post(checksUrl, ({ request }) => {
csrf = request.headers.get("X-CSRF-Token");
return HttpResponse.json({ scheduled: 2 }, { status: 202 });
}),
);
useServerOrigin();
const result = await requestMyRepositoryChecks({ headers: { "X-CSRF-Token": "T".repeat(43) } });
expect(result).toEqual({ scheduled: 2 });
expect(csrf).toBe("T".repeat(43));
expect(describeScheduled(result.scheduled)).toBe(
"Проверка запланирована: репозиториев 2. Статусы обновятся сами.",
);
});
it("turns a 429 into a countdown from Retry-After and keeps the problem detail", async () => {
server.use(http.post(checksUrl, () => rateLimited("125")));
useServerOrigin();
const error = await requestMyRepositoryChecks().catch((caught: unknown) => caught);
const failure = describeRecheckFailure(error);
expect(error).toBeInstanceOf(ApiRequestError);
expect(failure).toEqual({
title: "Репозитории уже проверялись недавно",
detail: "Repository checks run at most once in 10 minutes.",
cooldownSeconds: 125,
});
expect(formatCountdown(failure.cooldownSeconds ?? 0)).toBe("2 мин 05 с");
});
it("invents no waiting time when the server named none", async () => {
server.use(http.post(checksUrl, () => rateLimited(null)));
useServerOrigin();
const error = await requestMyRepositoryChecks().catch((caught: unknown) => caught);
expect(describeRecheckFailure(error).cooldownSeconds).toBeNull();
});
it("explains an unavailable service by its problem code, without a countdown", async () => {
server.use(
http.post(checksUrl, () =>
HttpResponse.json(
{
type: "urn:lincodex:problem:service_unavailable",
title: "Service unavailable",
status: 503,
code: "service_unavailable",
},
{ status: 503, headers: { "content-type": "application/problem+json" } },
),
),
);
useServerOrigin();
const failure = describeRecheckFailure(
await requestMyRepositoryChecks().catch((caught: unknown) => caught),
);
expect(failure.title).toBe("Сервис пока не готов");
expect(failure.cooldownSeconds).toBeNull();
});
});
describe("recheck countdown", () => {
it("counts whole seconds down to zero and never below", () => {
expect(secondsLeft(null, 1000)).toBe(0);
expect(secondsLeft(11_500, 1000)).toBe(11);
expect(secondsLeft(11_000, 11_000)).toBe(0);
expect(secondsLeft(11_000, 20_000)).toBe(0);
});
it("formats seconds and minutes", () => {
expect(formatCountdown(5)).toBe("5 с");
expect(formatCountdown(60)).toBe("1 мин 00 с");
expect(formatCountdown(599)).toBe("9 мин 59 с");
});
it("says that nothing was scheduled for a profile without saved repositories", () => {
expect(describeScheduled(0)).toContain("Нет сохраненных репозиториев");
});
});
@@ -0,0 +1,54 @@
import { ApiRequestError } from "../../../shared/api";
import { describeError } from "../../../shared/ui";
export type RecheckFailure = {
/** Short statement of what went wrong. */
title: string;
/** The problem detail of the server, shown as text, or null. */
detail: string | null;
/** Seconds the server asks to wait, or null when it named no time. */
cooldownSeconds: number | null;
};
/**
* Explains a failed request to check the repositories again. A 429 carries
* the Retry-After of the server and becomes a countdown; the client never
* invents a waiting time when the server named none.
*/
export function describeRecheckFailure(error: unknown): RecheckFailure {
if (error instanceof ApiRequestError && error.status === 429) {
return {
title: "Репозитории уже проверялись недавно",
detail: error.detail ?? null,
cooldownSeconds: error.retryAfterSeconds ?? null,
};
}
const description = describeError(error);
return {
title: description.title,
detail: error instanceof ApiRequestError ? (error.detail ?? description.description) : null,
cooldownSeconds: null,
};
}
/** Whole seconds left until `deadline` (epoch milliseconds); 0 when it has passed or is unset. */
export function secondsLeft(deadline: number | null, now: number): number {
if (deadline === null) return 0;
return Math.max(0, Math.ceil((deadline - now) / 1000));
}
/** Countdown text such as "5 с" or "2 мин 05 с". */
export function formatCountdown(seconds: number): string {
if (seconds < 60) return `${seconds} с`;
const minutes = Math.floor(seconds / 60);
const rest = String(seconds % 60).padStart(2, "0");
return `${minutes} мин ${rest} с`;
}
/** What the screen says after the server accepted a request to check again. */
export function describeScheduled(scheduled: number): string {
if (scheduled === 0) {
return "Нет сохраненных репозиториев для проверки. Сохраните профиль с адресом репозитория.";
}
return `Проверка запланирована: репозиториев ${scheduled}. Статусы обновятся сами.`;
}
@@ -0,0 +1,73 @@
import { useEffect, useRef, useState } from "react";
import { useRequestMyRepositoryChecks } from "../../../shared/api/endpoints/candidate/candidate";
import {
describeRecheckFailure,
describeScheduled,
secondsLeft,
type RecheckFailure,
} from "./repository-recheck";
export type RepositoryRecheck = {
/** Asks the server to check every saved repository again. */
request: () => void;
isPending: boolean;
/** Seconds before the next request is allowed; 0 when it is allowed now. */
cooldown: number;
failure: RecheckFailure | null;
/** Result text of the last accepted request, or null. */
message: string | null;
};
type Options = {
csrfToken: string | undefined;
/** Called after the server accepted the request, so the screen can reload statuses. */
onScheduled: () => void;
};
/** The "check again" action of the projects step with its rate-limit countdown. */
export function useRepositoryRecheck({ csrfToken, onScheduled }: Options): RepositoryRecheck {
const [deadline, setDeadline] = useState<number | null>(null);
const [now, setNow] = useState(() => Date.now());
const [failure, setFailure] = useState<RecheckFailure | null>(null);
const [message, setMessage] = useState<string | null>(null);
const scheduled = useRef(onScheduled);
const mutation = useRequestMyRepositoryChecks({
request: { headers: csrfToken ? { "X-CSRF-Token": csrfToken } : {} },
mutation: { gcTime: 0 },
});
useEffect(() => {
scheduled.current = onScheduled;
}, [onScheduled]);
const cooldown = secondsLeft(deadline, now);
const counting = cooldown > 0;
useEffect(() => {
if (!counting) return;
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, [counting]);
function request() {
if (mutation.isPending || cooldown > 0 || !csrfToken) return;
setFailure(null);
setMessage(null);
mutation.mutate(undefined, {
onSuccess: (result) => {
setMessage(describeScheduled(result.scheduled));
scheduled.current();
},
onError: (error) => {
const described = describeRecheckFailure(error);
setFailure(described);
if (described.cooldownSeconds !== null) {
const current = Date.now();
setNow(current);
setDeadline(current + described.cooldownSeconds * 1000);
}
},
});
}
return { request, isPending: mutation.isPending, cooldown, failure, message };
}
@@ -1,8 +1,10 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useQueryClient, type UseQueryResult } from "@tanstack/react-query";
import {
buildCandidateProfileUpdate,
hasPendingRepositoryChecks,
mapProfileServerErrors,
repositoryChecksOf,
toCandidateProfileDraft,
type CandidateProfileDraft,
type ProfileFormIssue,
@@ -33,6 +35,7 @@ import {
Skeleton,
TrustLevel,
} from "../../../shared/ui";
import { useRepositoryRecheck } from "../model/use-repository-recheck";
import { ProfileForm } from "./profile-form";
import styles from "./edit-profile.module.css";
@@ -184,6 +187,38 @@ function ProfileEditor({ profile, profileQuery }: ProfileEditorProps) {
mutation: { gcTime: 0 },
});
// Saved repositories are checked in the background: reload their states
// while one is pending, and for a short while after a new check was asked.
const [recentlyRequested, setRecentlyRequested] = useState(false);
const recheck = useRepositoryRecheck({
csrfToken: session.data?.csrf_token,
onScheduled: () => {
setRecentlyRequested(true);
void profileQuery.refetch();
},
});
const repositoryChecks = useMemo(
() => repositoryChecksOf(profileQuery.data ?? profile),
[profileQuery.data, profile],
);
const refreshChecks = hasPendingRepositoryChecks(profileQuery.data) || recentlyRequested;
const refetchProfile = profileQuery.refetch;
useEffect(() => {
if (!refreshChecks) return;
const started = Date.now();
const refresh = setInterval(() => {
// A worker that never answers must not keep the page polling.
if (Date.now() - started > 120_000) clearInterval(refresh);
else void refetchProfile();
}, 4000);
return () => clearInterval(refresh);
}, [refreshChecks, refetchProfile]);
useEffect(() => {
if (!recentlyRequested) return;
const stop = setTimeout(() => setRecentlyRequested(false), 20_000);
return () => clearTimeout(stop);
}, [recentlyRequested]);
const changeDraft = (next: CandidateProfileDraft) => {
setDraft(next);
setIssues([]);
@@ -369,6 +404,8 @@ function ProfileEditor({ profile, profileQuery }: ProfileEditorProps) {
issues={issues}
isSaving={savingState === "saving"}
savingState={savingState}
repositoryChecks={repositoryChecks}
recheck={recheck}
onDraftChange={changeDraft}
onSubmit={() => void handleSubmit()}
/>
@@ -0,0 +1,56 @@
import type { ReactNode } from "react";
import styles from "./profile-form.module.css";
/* Field helpers shared by the steps of the profile form. */
export function ErrorText({ id, children }: { id: string; children?: string | undefined }) {
return children ? (
<p className={styles.error} id={id}>
{children}
</p>
) : null;
}
export function Suggestion({
source,
}: {
source: { quote: string | null; origin: string } | null;
}) {
if (!source || source.origin === "manual") return null;
const origin = source.origin === "imported" ? "Импортировано" : "Предложено из документа";
return (
<details className={styles.suggestion}>
<summary>{origin}. Значение пока не подтверждено.</summary>
{source.quote ? <blockquote>{source.quote}</blockquote> : <p>Цитата не сохранена.</p>}
</details>
);
}
export type FieldProps = {
id: string;
label: string;
error?: string | undefined;
description?: ReactNode | undefined;
suggestion?: { quote: string | null; origin: string } | null | undefined;
children: ReactNode;
};
export function Field({ id, label, error, description, suggestion, children }: FieldProps) {
return (
<div className={styles.field}>
<label htmlFor={id}>{label}</label>
{description ? (
<p className={styles.hint} id={`${id}-hint`}>
{description}
</p>
) : null}
{children}
{suggestion ? (
<div id={`${id}-suggestion`}>
<Suggestion source={suggestion} />
</div>
) : null}
<ErrorText id={`${id}-error`}>{error}</ErrorText>
</div>
);
}
@@ -1,9 +1,19 @@
import { renderToString } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
import { toCandidateProfileDraft } from "../../../entities/candidate";
import type { CandidateProfile } from "../../../shared/api/schemas";
import { repositoryChecksOf, toCandidateProfileDraft } from "../../../entities/candidate";
import type { CandidateProfile, ProfileRepositoryCheck } from "../../../shared/api/schemas";
import type { RepositoryRecheck } from "../model/use-repository-recheck";
import { ProfileForm } from "./profile-form";
const idleRecheck: RepositoryRecheck = {
request: vi.fn(),
isPending: false,
cooldown: 0,
failure: null,
message: null,
};
const noChecks = new Map<string, ProfileRepositoryCheck>();
const emptyProfile: CandidateProfile = {
version: 0,
full_name: { status: "unknown", value: null, source: null },
@@ -69,6 +79,8 @@ describe("ProfileForm", () => {
issues={[]}
isSaving={false}
savingState="idle"
repositoryChecks={noChecks}
recheck={idleRecheck}
onDraftChange={vi.fn()}
onSubmit={vi.fn()}
/>,
@@ -92,6 +104,8 @@ describe("ProfileForm", () => {
issues: [],
isSaving: false,
savingState: "idle" as const,
repositoryChecks: noChecks,
recheck: idleRecheck,
onDraftChange: vi.fn(),
onSubmit: vi.fn(),
};
@@ -115,26 +129,164 @@ describe("ProfileForm", () => {
expect(unconfirmedText).not.toContain("подтверждена ранее");
});
it("walks six steps and keeps the save action on the last one", () => {
it("walks seven steps and keeps the save action on the last one", () => {
const html = renderToString(
<ProfileForm
draft={toCandidateProfileDraft(emptyProfile)}
issues={[]}
isSaving={false}
savingState="idle"
repositoryChecks={noChecks}
recheck={idleRecheck}
onDraftChange={vi.fn()}
onSubmit={vi.fn()}
/>,
);
expect(html).toContain("Шаг 1 из 6");
for (const step of ["Контакты", "Роли", "Опыт", "Навыки", "Условия", "Проверка"]) {
expect(html).toContain("Шаг 1 из 7");
for (const step of ["Контакты", "Роли", "Опыт", "Проекты", "Навыки", "Условия", "Проверка"]) {
expect(html).toContain(step);
}
expect(html.match(/<section[^>]*hidden=""/g)).toHaveLength(5);
expect(html.match(/<section[^>]*hidden=""/g)).toHaveLength(6);
expect(html).toContain(">Далее<");
expect(html).not.toContain("Сохранить профиль");
// An unsaved profile has no shortcut to the review step.
expect(html).not.toContain("К проверке и сохранению");
});
});
const manualSource = {
origin: "manual" as const,
trust_level: 0 as const,
quote: null,
extraction_version: null,
confirmed_at: "2026-10-05T09:30:00Z",
};
function project(
title: string,
repositoryUrl: string | null,
state: ProfileRepositoryCheck["state"] | null,
): CandidateProfile["projects"][number] {
return {
title,
description: "Проводки, сверки и выплаты.",
stack: ["Go", "PostgreSQL"],
repository_url: repositoryUrl,
repository_check: state ? { state, checked_at: "2026-10-05T09:30:00Z" } : null,
status: "confirmed",
source: manualSource,
};
}
const projectProfile: CandidateProfile = {
...emptyProfile,
version: 3,
projects: [
project("Платежный шлюз", "https://github.com/example-org/payments-ledger", "verified"),
project("Закрытый сервис", "https://github.com/example-org/private-one", "not_found"),
project("Каталог", "https://github.com/example-org/catalog", "unavailable"),
project("Поиск", "https://github.com/example-org/search", "pending"),
project("Без репозитория", null, null),
],
};
function renderProjects(
profile: CandidateProfile,
recheck: Partial<RepositoryRecheck> = {},
): string {
return renderToString(
<ProfileForm
draft={toCandidateProfileDraft(profile)}
issues={[]}
isSaving={false}
savingState="idle"
repositoryChecks={repositoryChecksOf(profile)}
recheck={{ ...idleRecheck, ...recheck }}
onDraftChange={vi.fn()}
onSubmit={vi.fn()}
/>,
).replaceAll("<!-- -->", "");
}
describe("ProfileForm projects step", () => {
it("offers to add a project and warns what the title and the description can reveal", () => {
const html = renderProjects(emptyProfile);
expect(html).toContain("Добавить проект");
expect(html).toContain("могут выдать вас");
expect(html).toContain("Адрес репозитория компании не получают никогда");
// Without a repository there is nothing to check again.
expect(html).not.toContain("Проверить снова");
});
it("shows the title, the stack tags, and the repository field of a saved project", () => {
const html = renderProjects(projectProfile);
expect(html).toContain('value="Платежный шлюз"');
expect(html).toContain("Проводки, сверки и выплаты.");
expect(html).toContain(">PostgreSQL<");
expect(html).toContain('value="https://github.com/example-org/payments-ledger"');
expect(html).toContain("Убрать технологию Go из проекта 1");
});
it("states each repository check in words as well as in a tag", () => {
const html = renderProjects(projectProfile);
expect(html).toContain("Публичный репозиторий найден");
expect(html).toContain("Не найден или закрыт");
expect(html).toContain("Лимит GitHub, повторим позже");
expect(html).toContain(">Проверяется<");
expect(html).toContain("Авторство не проверяется");
// A project without an address has no status.
expect(html.match(/data-state="/g)).toHaveLength(4);
});
it("marks an address that the server has not stored yet", () => {
const html = renderProjects({
...emptyProfile,
projects: [project("Новый", "https://github.com/example-org/fresh", null)],
});
expect(html).toContain("Проверка после сохранения");
expect(html).toContain("Сначала сохраните профиль с адресом");
});
it("offers the recheck, and disables it with a countdown after a rate limit", () => {
const ready = renderProjects(projectProfile);
expect(ready).toContain("Проверить снова");
expect(ready).not.toContain("Следующий запрос можно отправить");
const limited = renderProjects(projectProfile, {
cooldown: 65,
failure: {
title: "Репозитории уже проверялись недавно",
detail: "Повторить можно через 65 секунд.",
cooldownSeconds: 65,
},
});
expect(limited).toMatch(/<button[^>]*disabled=""[^>]*>Проверить снова<\/button>/);
expect(limited).toContain("Следующий запрос можно отправить через 1 мин 05 с");
expect(limited).toContain("Репозитории уже проверялись недавно");
expect(limited).toContain("Повторить можно через 65 секунд.");
});
it("stops adding projects at the limit", () => {
const many: CandidateProfile = {
...emptyProfile,
projects: Array.from({ length: 10 }, (_, index) => project(`Проект ${index}`, null, null)),
};
const html = renderProjects(many);
expect(html).toMatch(/<button[^>]*disabled=""[^>]*>Добавить проект<\/button>/);
expect(html).toContain("Достигнут предел: 10 проектов");
});
it("lists the projects on the review step, or says that there are none", () => {
const html = renderProjects(projectProfile);
expect(html).not.toContain("Проекты не добавлены.");
expect(html).toContain("example-org/payments-ledger");
expect(renderProjects(emptyProfile)).toContain("Проекты не добавлены.");
});
});
@@ -6,6 +6,7 @@ import {
addStack,
buildCandidateProfileUpdate,
moveExperience,
parseGitHubRepository,
removeExperience,
removeItem,
reviewExperienceOverlaps,
@@ -19,9 +20,10 @@ import {
type CandidateProfileDraft,
type ProfileFormIssue,
} from "../../../entities/candidate";
import type { CandidateProfile } from "../../../shared/api/schemas";
import type { CandidateProfile, ProfileRepositoryCheck } from "../../../shared/api/schemas";
import { Button, Mono, Notice, SavingStatus, Tag, TrustLevel } from "../../../shared/ui";
import { profileStepOfField, type ProfileStepId } from "../model/profile-steps";
import type { RepositoryRecheck } from "../model/use-repository-recheck";
import {
FormProgress,
FormStepFooter,
@@ -29,6 +31,9 @@ import {
ReviewBlock,
type FormStep,
} from "./form-steps";
import { describedBy, errorFor } from "../model/field-helpers";
import { ErrorText, Field } from "./form-field";
import { ProjectsStep } from "./projects-step";
import { useFormSteps } from "./use-form-steps";
import styles from "./profile-form.module.css";
@@ -36,6 +41,7 @@ const profileSteps: readonly FormStep<ProfileStepId>[] = [
{ id: "contacts", label: "Контакты" },
{ id: "roles", label: "Роли" },
{ id: "experience", label: "Опыт" },
{ id: "projects", label: "Проекты" },
{ id: "skills", label: "Навыки" },
{ id: "terms", label: "Условия" },
{ id: "review", label: "Проверка" },
@@ -68,78 +74,13 @@ type ProfileFormProps = {
issues: readonly ProfileFormIssue[];
isSaving: boolean;
savingState: "idle" | "saving" | "saved" | "failed";
/** Latest server checks of the saved project repositories, by repository identity. */
repositoryChecks: ReadonlyMap<string, ProfileRepositoryCheck>;
recheck: RepositoryRecheck;
onDraftChange: (draft: CandidateProfileDraft) => void;
onSubmit: () => void;
};
function errorFor(issues: readonly ProfileFormIssue[], field: string): string | undefined {
return issues.find((issue) => issue.field === field)?.message;
}
function ErrorText({ id, children }: { id: string; children?: string | undefined }) {
return children ? (
<p className={styles.error} id={id}>
{children}
</p>
) : null;
}
function Suggestion({ source }: { source: { quote: string | null; origin: string } | null }) {
if (!source || source.origin === "manual") return null;
const origin = source.origin === "imported" ? "Импортировано" : "Предложено из документа";
return (
<details className={styles.suggestion}>
<summary>{origin}. Значение пока не подтверждено.</summary>
{source.quote ? <blockquote>{source.quote}</blockquote> : <p>Цитата не сохранена.</p>}
</details>
);
}
type FieldProps = {
id: string;
label: string;
error?: string | undefined;
description?: ReactNode | undefined;
suggestion?: { quote: string | null; origin: string } | null | undefined;
children: ReactNode;
};
function Field({ id, label, error, description, suggestion, children }: FieldProps) {
return (
<div className={styles.field}>
<label htmlFor={id}>{label}</label>
{description ? (
<p className={styles.hint} id={`${id}-hint`}>
{description}
</p>
) : null}
{children}
{suggestion ? (
<div id={`${id}-suggestion`}>
<Suggestion source={suggestion} />
</div>
) : null}
<ErrorText id={`${id}-error`}>{error}</ErrorText>
</div>
);
}
function describedBy(
id: string,
error?: string,
suggestion?: boolean,
hint?: boolean,
): string | undefined {
const values = [
hint ? `${id}-hint` : "",
suggestion ? `${id}-suggestion` : "",
error ? `${id}-error` : "",
]
.filter(Boolean)
.join(" ");
return values || undefined;
}
const fieldLabels: Readonly<Record<string, string>> = {
fullName: "имя и фамилия",
"contacts.email": "контактный email",
@@ -154,7 +95,7 @@ const fieldLabels: Readonly<Record<string, string>> = {
/** The field named in an issue of the summary, when it has a short name. */
function fieldLabel(field: string): string | null {
if (fieldLabels[field]) return fieldLabels[field];
const row = /^(experience|roles|stack|softSkills)\.(\d+)/.exec(field);
const row = /^(experience|roles|stack|softSkills|projects)\.(\d+)/.exec(field);
if (!row) return null;
const position = Number(row[2]) + 1;
switch (row[1]) {
@@ -162,6 +103,8 @@ function fieldLabel(field: string): string | null {
return `место работы ${position}`;
case "roles":
return `роль ${position}`;
case "projects":
return `проект ${position}`;
case "stack":
return `навык ${position}`;
default:
@@ -192,6 +135,8 @@ export function ProfileForm({
issues,
isSaving,
savingState,
repositoryChecks,
recheck,
onDraftChange,
onSubmit,
}: ProfileFormProps) {
@@ -786,6 +731,22 @@ export function ProfileForm({
) : null}
</FormStepPanel>
<FormStepPanel
{...panel("projects")}
description="Необязательный шаг. Расскажите о проектах и при желании укажите публичный репозиторий на GitHub: так подбор точнее находит ваш опыт."
>
<ProjectsStep
draft={draft}
issues={shownIssues}
isSaving={isSaving}
fieldId={fieldId}
newRowId={newRowId}
checks={repositoryChecks}
recheck={recheck}
onDraftChange={setDraft}
/>
</FormStepPanel>
<FormStepPanel
{...panel("skills")}
description="Технологии и гибкие навыки по одному в строке. Пустые строки не сохраняются."
@@ -1083,6 +1044,7 @@ function ProfileReview({
onEdit: (step: ProfileStepId) => void;
}) {
const stack = draft.stack.filter((item) => item.tag.trim());
const projects = draft.projects.filter((item) => item.title.trim());
const softSkills = draft.softSkills.filter((item) => item.skill.trim());
const salary = draft.terms.salaryMinimum;
const salaryAmount = Number(salary.amount);
@@ -1177,6 +1139,33 @@ function ProfileReview({
</p>
) : null}
</ReviewBlock>
<ReviewBlock
title="Проекты"
editLabel="проекты"
disabled={disabled}
onEdit={() => onEdit("projects")}
>
{projects.length > 0 ? (
<ol className={styles["review-list"]}>
{projects.map((item) => (
<li key={item.id}>
<span className={styles["review-strong"]}>{item.title.trim()}</span>
<span className={styles["review-meta"]}>
{item.stack.length > 0 ? item.stack.join(", ") : "Технологии не указаны"}
{item.repository_url.trim() ? (
<>
{" "}
- репозиторий: <Mono>{repositoryLabel(item.repository_url)}</Mono>
</>
) : null}
</span>
</li>
))}
</ol>
) : (
<p className={styles["review-empty"]}>Проекты не добавлены.</p>
)}
</ReviewBlock>
<ReviewBlock
title="Навыки"
editLabel="навыки"
@@ -1251,6 +1240,12 @@ function ProfileReview({
);
}
/** The owner and name of a repository for the owner's own review; any other text is shown as typed. */
function repositoryLabel(address: string): string {
const repository = parseGitHubRepository(address);
return repository ? `${repository.owner}/${repository.name}` : address.trim();
}
function formatPeriod(period: { started_on: string; ended_on: string | null }): string {
return `${period.started_on} - ${period.ended_on ?? "сейчас"}`;
}
@@ -0,0 +1,139 @@
/* The projects step. A repeated project is a nested surface, as roles and
* workplaces are in the profile form. */
.item {
display: grid;
gap: var(--space-4);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
background: var(--color-canvas);
}
.item-header,
.item-actions,
.add-row,
.recheck-actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-3);
align-items: center;
min-width: 0;
}
.item-header {
justify-content: space-between;
}
.item-header h4,
.recheck h4 {
color: var(--color-text-strong);
font-size: var(--font-size-m);
}
.fields {
display: grid;
gap: var(--space-4);
min-width: 0;
}
.limit,
.countdown {
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
/* Tags of a project: chips above one field that adds the next tag. */
.tag-input {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
margin: 0;
padding: 0;
list-style: none;
}
.chip {
display: inline-flex;
align-items: center;
min-width: 0;
}
.chip-remove {
min-width: 1.75rem;
min-height: 1.75rem;
margin-inline-start: calc(var(--space-1) * -1);
padding: 0;
border: 0;
border-radius: var(--radius-pill);
color: var(--color-text-secondary);
font-size: var(--font-size-m);
line-height: 1;
background: transparent;
cursor: pointer;
}
.chip-remove:hover:not(:disabled) {
color: var(--color-text-strong);
background: var(--color-surface-tint-hover);
}
.tag-entry {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
align-items: center;
min-width: 0;
}
/* The two-class selectors win over the width rule of the form field. */
.tag-input .tag-entry input {
flex: 1 1 12rem;
width: auto;
min-width: 0;
border: var(--line-thin) solid var(--color-border-strong);
}
.tag-input .tag-entry input[aria-invalid="true"] {
border-color: var(--color-danger);
}
/* Repository check: the state in a tag and the same state in words. */
.status {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-3);
align-items: baseline;
min-width: 0;
}
.status-note {
flex: 1 1 16rem;
min-width: 0;
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
line-height: var(--line-height-body);
overflow-wrap: anywhere;
}
.recheck {
display: grid;
gap: var(--space-3);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) dashed var(--color-border-hover);
border-radius: var(--radius-s);
}
@media (width < 30rem) {
.item {
padding: var(--space-3);
}
}
@@ -0,0 +1,298 @@
import type { ProfileRepositoryCheck } from "../../../shared/api/schemas";
import {
addProject,
describeRepositoryStatus,
maxProjectDescription,
maxProjectStack,
maxProjectStackTag,
maxProjectTitle,
maxProjects,
moveProject,
removeItem,
repositoryKey,
updateProjectDraft,
type CandidateProfileDraft,
type ProfileFormIssue,
} from "../../../entities/candidate";
import { Button, Notice, Tag } from "../../../shared/ui";
import { describedBy, errorFor } from "../model/field-helpers";
import { formatCountdown } from "../model/repository-recheck";
import type { RepositoryRecheck } from "../model/use-repository-recheck";
import { Field } from "./form-field";
import { TagListInput } from "./tag-list-input";
import styles from "./projects-step.module.css";
const checkedAtFormat = new Intl.DateTimeFormat("ru-RU", {
dateStyle: "medium",
timeStyle: "short",
});
/** The status of the repository check of one project, in words and a tag. */
export function RepositoryStatus({
address,
checks,
}: {
address: string;
checks: ReadonlyMap<string, ProfileRepositoryCheck>;
}) {
const key = repositoryKey(address);
if (!key) return null;
const view = describeRepositoryStatus(checks.get(key));
return (
<div className={styles.status} data-state={view.state} aria-live="polite">
<Tag tone={view.tone} dot={view.state === "pending"}>
{view.label}
</Tag>
<p className={styles["status-note"]}>
{view.note}
{view.checkedAt ? ` Проверено: ${checkedAtFormat.format(new Date(view.checkedAt))}.` : ""}
</p>
</div>
);
}
type ProjectsStepProps = {
draft: CandidateProfileDraft;
issues: readonly ProfileFormIssue[];
isSaving: boolean;
/** Ids of the fields, built by the form so every step shares one prefix. */
fieldId: (field: string) => string;
newRowId: (kind: string) => string;
/** Latest server checks of the saved repositories. */
checks: ReadonlyMap<string, ProfileRepositoryCheck>;
recheck: RepositoryRecheck;
onDraftChange: (draft: CandidateProfileDraft) => void;
};
/** The "Проекты" step: up to ten projects with an optional GitHub repository each. */
export function ProjectsStep({
draft,
issues,
isSaving,
fieldId,
newRowId,
checks,
recheck,
onDraftChange,
}: ProjectsStepProps) {
const issue = (field: string) => errorFor(issues, field);
const hasRepository = draft.projects.some((item) => item.repository_url.trim() !== "");
const hasSavedRepository = draft.projects.some((item) => {
const key = repositoryKey(item.repository_url);
return key !== null && checks.has(key);
});
const waiting = recheck.cooldown > 0;
return (
<>
<Notice tone="info">
<p>
Название и описание могут выдать вас, если вы отдельно опубликуете проекты в карточке. Не
пишите в них имя, контакты и адрес репозитория. Адрес репозитория компании не получают
никогда.
</p>
</Notice>
{draft.projects.map((item, index) => {
const base = `projects.${index}`;
const titleId = fieldId(`${base}.title`);
const descriptionId = fieldId(`${base}.description`);
const stackId = fieldId(`${base}.stack`);
const urlId = fieldId(`${base}.repository_url`);
return (
<section
className={styles.item}
key={item.id}
aria-labelledby={`${titleId}-heading`}
data-project={index}
>
<div className={styles["item-header"]}>
<h4 id={`${titleId}-heading`}>Проект {index + 1}</h4>
<div className={styles["item-actions"]}>
<Button
variant="quiet"
aria-label={`Переместить проект ${index + 1} выше`}
disabled={index === 0 || isSaving}
onClick={() => onDraftChange(moveProject(draft, index, -1))}
>
Выше
</Button>
<Button
variant="quiet"
aria-label={`Переместить проект ${index + 1} ниже`}
disabled={index === draft.projects.length - 1 || isSaving}
onClick={() => onDraftChange(moveProject(draft, index, 1))}
>
Ниже
</Button>
<Button
variant="quiet"
aria-label={`Удалить проект ${index + 1}`}
disabled={isSaving}
onClick={() => onDraftChange(removeItem(draft, "projects", item.id))}
>
Удалить
</Button>
</div>
</div>
<div className={styles.fields}>
<Field
id={titleId}
label="Название"
error={issue(`${base}.title`)}
suggestion={item.source}
>
<input
id={titleId}
name={`project_title_${index}`}
maxLength={maxProjectTitle}
value={item.title}
aria-invalid={Boolean(issue(`${base}.title`))}
aria-describedby={describedBy(
titleId,
issue(`${base}.title`),
Boolean(item.source),
)}
onChange={(event) =>
onDraftChange(
updateProjectDraft(draft, item.id, { title: event.currentTarget.value }),
)
}
/>
</Field>
<Field
id={descriptionId}
label="Что делает проект и что делали вы"
error={issue(`${base}.description`)}
description={`До ${maxProjectDescription} символов. Показывается как обычный текст.`}
>
<textarea
id={descriptionId}
name={`project_description_${index}`}
rows={4}
maxLength={maxProjectDescription}
value={item.description}
aria-invalid={Boolean(issue(`${base}.description`))}
aria-describedby={describedBy(
descriptionId,
issue(`${base}.description`),
false,
true,
)}
onChange={(event) =>
onDraftChange(
updateProjectDraft(draft, item.id, {
description: event.currentTarget.value,
}),
)
}
/>
</Field>
<Field
id={stackId}
label="Технологии проекта"
error={issue(`${base}.stack`)}
description={`До ${maxProjectStack} тегов. Enter или запятая добавляют тег.`}
>
<TagListInput
id={stackId}
tags={item.stack}
maxTags={maxProjectStack}
maxLength={maxProjectStackTag}
disabled={isSaving}
invalid={Boolean(issue(`${base}.stack`))}
describedBy={describedBy(stackId, issue(`${base}.stack`), false, true)}
removeLabel={(tag) => `Убрать технологию ${tag} из проекта ${index + 1}`}
onChange={(stack) => onDraftChange(updateProjectDraft(draft, item.id, { stack }))}
/>
</Field>
<Field
id={urlId}
label="Репозиторий на GitHub, необязательно"
error={issue(`${base}.repository_url`)}
description="Только публичный адрес вида https://github.com/владелец/репозиторий. Компании его не видят."
>
<input
id={urlId}
name={`project_repository_${index}`}
inputMode="url"
autoComplete="off"
spellCheck={false}
maxLength={160}
placeholder="https://github.com/владелец/репозиторий"
value={item.repository_url}
aria-invalid={Boolean(issue(`${base}.repository_url`))}
aria-describedby={describedBy(
urlId,
issue(`${base}.repository_url`),
false,
true,
)}
onChange={(event) =>
onDraftChange(
updateProjectDraft(draft, item.id, {
repository_url: event.currentTarget.value,
}),
)
}
/>
</Field>
<RepositoryStatus address={item.repository_url} checks={checks} />
</div>
</section>
);
})}
<div className={styles["add-row"]}>
<Button
variant="secondary"
disabled={draft.projects.length >= maxProjects || isSaving}
onClick={() => onDraftChange(addProject(draft, newRowId("project")))}
>
Добавить проект
</Button>
{draft.projects.length >= maxProjects ? (
<span className={styles.limit}>Достигнут предел: {maxProjects} проектов.</span>
) : null}
</div>
{hasRepository ? (
<section className={styles.recheck} aria-labelledby={`${fieldId("recheck")}-title`}>
<h4 id={`${fieldId("recheck")}-title`}>Проверка репозиториев</h4>
<p className={styles["status-note"]}>
Сервер читает только публичные данные на GitHub и отмечает, что репозиторий существует и
открыт. Это не доказывает авторство. Проверяются сохраненные адреса; сделали репозиторий
публичным - проверьте снова.
</p>
<div className={styles["recheck-actions"]}>
<Button
variant="secondary"
isBusy={recheck.isPending}
disabled={waiting || !hasSavedRepository || isSaving}
onClick={recheck.request}
>
{recheck.isPending ? "Запрашиваем проверку..." : "Проверить снова"}
</Button>
{waiting ? (
<span className={styles.countdown}>
Следующий запрос можно отправить через {formatCountdown(recheck.cooldown)}.
</span>
) : null}
{!hasSavedRepository ? (
<span className={styles.countdown}>Сначала сохраните профиль с адресом.</span>
) : null}
</div>
{recheck.failure ? (
<div role="alert">
<Notice tone="danger" title={recheck.failure.title}>
{recheck.failure.detail ? <p>{recheck.failure.detail}</p> : null}
</Notice>
</div>
) : null}
{recheck.message ? (
<p className={styles["status-note"]} role="status">
{recheck.message}
</p>
) : null}
</section>
) : null}
</>
);
}
@@ -0,0 +1,102 @@
import { useState, type KeyboardEvent } from "react";
import { Button, Tag } from "../../../shared/ui";
import styles from "./projects-step.module.css";
type TagListInputProps = {
id: string;
tags: readonly string[];
maxTags: number;
maxLength: number;
disabled: boolean;
invalid: boolean;
describedBy: string | undefined;
/** Accessible name of the button that removes one tag. */
removeLabel: (tag: string) => string;
onChange: (tags: string[]) => void;
};
/**
* Technology tags of one project: the tags added so far as removable chips and
* one field for the next tag. Enter, a comma, the add button, and leaving the
* field all add the typed text, so a tag typed before "Далее" is never lost.
* Tags compare without regard to letter case, as the server does.
*/
export function TagListInput({
id,
tags,
maxTags,
maxLength,
disabled,
invalid,
describedBy,
removeLabel,
onChange,
}: TagListInputProps) {
const [text, setText] = useState("");
const full = tags.length >= maxTags;
function commit() {
const next = [...tags];
for (const part of text.split(/[,\n]/)) {
const tag = part.trim();
if (!tag || next.length >= maxTags) continue;
if (
next.some((existing) => existing.toLocaleLowerCase("ru") === tag.toLocaleLowerCase("ru"))
) {
continue;
}
next.push(tag.slice(0, maxLength));
}
setText("");
if (next.length !== tags.length) onChange(next);
}
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {
// Enter belongs to this field: it must not submit the surrounding step.
if (event.key === "Enter" || event.key === ",") {
event.preventDefault();
commit();
}
}
return (
<div className={styles["tag-input"]}>
{tags.length > 0 ? (
<ul className={styles.chips}>
{tags.map((tag) => (
<li key={tag.toLocaleLowerCase("ru")} className={styles.chip}>
<Tag tone="stack">{tag}</Tag>
<button
type="button"
className={styles["chip-remove"]}
aria-label={removeLabel(tag)}
disabled={disabled}
onClick={() => onChange(tags.filter((item) => item !== tag))}
>
<span aria-hidden="true">×</span>
</button>
</li>
))}
</ul>
) : null}
<div className={styles["tag-entry"]}>
<input
id={id}
value={text}
maxLength={maxLength}
placeholder={full ? "Достигнут предел тегов" : "Например, PostgreSQL"}
autoComplete="off"
disabled={disabled || full}
aria-invalid={invalid}
aria-describedby={describedBy}
onChange={(event) => setText(event.currentTarget.value)}
onKeyDown={handleKeyDown}
onBlur={commit}
/>
<Button variant="secondary" disabled={disabled || full || !text.trim()} onClick={commit}>
Добавить
</Button>
</div>
</div>
);
}
@@ -147,3 +147,35 @@
padding: var(--space-3);
}
}
/* A choice with a warning under it: the warning belongs to the checkbox. */
.choice-group {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.warning {
display: grid;
gap: var(--space-2);
margin-inline-start: calc(1.15rem + var(--space-3));
padding: var(--space-3) var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-inline-start: var(--line-strong) solid var(--color-border-strong);
border-radius: var(--radius-s);
background: var(--color-canvas);
color: var(--color-text-secondary);
font-size: var(--font-size-s);
line-height: var(--line-height-body);
}
.warning p {
margin: 0;
overflow-wrap: anywhere;
}
/* Once the field is chosen the warning turns from a hint into a caution. */
.warning[data-selected="true"] {
border-inline-start-color: var(--color-danger);
color: var(--color-text);
}
@@ -1,5 +1,6 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
import type { PublicationDraft } from "../../../entities/candidate-view";
import type { PrivacySettings } from "../../../shared/api/schemas";
import { PublicationControls, SearchStatusControl } from "./visibility-controls";
@@ -89,6 +90,47 @@ describe("profile visibility controls", () => {
});
});
describe("projects publication choice", () => {
function render(fields: PublicationDraft["fields"]) {
return renderToStaticMarkup(
<PublicationControls
settings={settings}
c2State="active"
draft={{ state: "published", fields, expectedVersion: 0 }}
isDirty
isStale={false}
hasUnsupportedFields={false}
canSave
isSaving={false}
message={null}
error={null}
onDraftChange={vi.fn()}
onSave={vi.fn()}
onReload={vi.fn()}
onOpenConsent={vi.fn()}
/>,
).replaceAll("<!-- -->", "");
}
it("offers the projects as their own choice with a warning that is read before choosing", () => {
const markup = render(["categories"]);
expect(markup).toContain("Проекты: название, описание и технологии");
expect(markup).toContain("по ним вас могут узнать");
expect(markup).toContain("Размер группы похожих кандидатов эти тексты не скрывает");
expect(markup).toContain("Адрес репозитория и его владелец компаниям не показываются никогда");
expect(markup).toContain('data-selected="false"');
// The checkbox points at the warning, so assistive technology reads it with the choice.
const warningId = /id="([^"]+)" class="[^"]*warning[^"]*"/.exec(markup)?.[1];
expect(warningId).toBeTruthy();
expect(markup).toContain(`aria-describedby="${warningId}"`);
});
it("marks the warning as a caution once the projects are chosen", () => {
expect(render(["categories", "projects"])).toContain('data-selected="true"');
});
});
describe("publication closure notice", () => {
const closedByRevocation: PrivacySettings = {
...settings,
@@ -2,6 +2,7 @@ import { useId } from "react";
import {
cardFieldLabels,
describePublicationClosure,
projectsPublicationWarning,
publishableCardFields,
type C2State,
type PublicationDraft,
@@ -54,6 +55,7 @@ export function PublicationControls({
const stateId = useId();
const fieldsId = useId();
const c2Id = useId();
const projectsWarningId = useId();
const closure = describePublicationClosure(settings.publication);
function toggleField(field: PublicationDraft["fields"][number], checked: boolean) {
@@ -137,15 +139,28 @@ export function PublicationControls({
самооценка показываются раздельно.
</p>
{publishableCardFields.map((field) => (
<label className={styles.choice} key={field}>
<input
type="checkbox"
checked={draft.fields.includes(field)}
disabled={isSaving}
onChange={(event) => toggleField(field, event.currentTarget.checked)}
/>
<span>{cardFieldLabels[field]}</span>
</label>
<div className={styles["choice-group"]} key={field}>
<label className={styles.choice}>
<input
type="checkbox"
checked={draft.fields.includes(field)}
disabled={isSaving}
aria-describedby={field === "projects" ? projectsWarningId : undefined}
onChange={(event) => toggleField(field, event.currentTarget.checked)}
/>
<span>{cardFieldLabels[field]}</span>
</label>
{field === "projects" ? (
<div
id={projectsWarningId}
className={styles.warning}
data-selected={draft.fields.includes("projects")}
>
<p>{projectsPublicationWarning.identify}</p>
<p>{projectsPublicationWarning.repository}</p>
</div>
) : null}
</div>
))}
</fieldset>
+1
View File
@@ -37,3 +37,4 @@ export { AttentionDot, Tag, type TagTone } from "./tag/tag";
export { TrustLevel } from "./trust-level/trust-level";
export { trustLevelLabels, type TrustLevelValue } from "./trust-level/trust-level-labels";
export { VisuallyHidden } from "./visually-hidden/visually-hidden";
export { PublishedProjects, type PublishedProject } from "./published-projects/published-projects";
@@ -0,0 +1,71 @@
.root {
display: grid;
gap: var(--space-3);
min-width: 0;
}
.list,
.chips {
margin: 0;
padding: 0;
list-style: none;
}
.list {
display: grid;
gap: var(--space-3);
}
.project {
display: grid;
gap: var(--space-2);
min-width: 0;
padding-block-end: var(--space-3);
border-block-end: var(--line-thin) solid var(--color-divider);
}
.project:last-child {
padding-block-end: 0;
border-block-end: 0;
}
.header {
display: flex;
flex-wrap: wrap;
gap: var(--space-1) var(--space-3);
align-items: center;
min-width: 0;
}
.title {
color: var(--color-text-strong);
overflow-wrap: anywhere;
}
/* The candidate's own line breaks stay; long words wrap. */
.description {
margin: 0;
color: var(--color-text);
font-size: var(--font-size-s);
line-height: var(--line-height-body);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.chips li {
min-width: 0;
max-width: 100%;
}
.note {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-xs);
line-height: var(--line-height-body);
}
@@ -0,0 +1,61 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { PublishedProjects } from "./published-projects";
describe("PublishedProjects", () => {
it("shows the title, the description, and the tags of a project", () => {
const html = renderToStaticMarkup(
<PublishedProjects
projects={[
{
title: "Платежный шлюз",
description: "Проводки и сверки.",
stack: ["Go", "PostgreSQL"],
repositoryVerified: false,
},
]}
/>,
);
expect(html).toContain("Платежный шлюз");
expect(html).toContain("Проводки и сверки.");
expect(html).toContain(">PostgreSQL<");
expect(html).not.toContain("Подтвержден публичным репозиторием");
expect(html).not.toContain("Авторство она не доказывает");
});
it("marks a verified project and says what the mark proves", () => {
const html = renderToStaticMarkup(
<PublishedProjects
projects={[
{ title: "Каталог", description: null, stack: [], repositoryVerified: true },
{ title: "Поиск", description: null, stack: [], repositoryVerified: false },
]}
/>,
);
expect(html.match(/Подтвержден публичным репозиторием/g)).toHaveLength(1);
expect(html).toContain("Авторство она не доказывает");
expect(html).not.toContain("github.com");
});
it("renders candidate text as text, never as markup", () => {
const html = renderToStaticMarkup(
<PublishedProjects
projects={[
{
title: "<img src=x onerror=alert(1)>",
description: "<script>alert(1)</script>",
stack: ["<b>Go</b>"],
repositoryVerified: false,
},
]}
/>,
);
expect(html).not.toContain("<img");
expect(html).not.toContain("<script");
expect(html).not.toContain("<b>");
expect(html).toContain("&lt;img");
});
});
@@ -0,0 +1,60 @@
import { Tag } from "../tag/tag";
import styles from "./published-projects.module.css";
/** One project exactly as an organization reads it: text and a verification flag, never an address. */
export type PublishedProject = {
title: string;
description: string | null;
stack: readonly string[];
/** True when the server found the linked repository public; it does not prove authorship. */
repositoryVerified: boolean;
};
type PublishedProjectsProps = {
projects: readonly PublishedProject[];
};
/**
* Projects a candidate published on the anonymous card. Titles, descriptions,
* and tags are free text of the candidate, so they are rendered as text only.
* The badge states what the check proved: a public repository exists.
*/
export function PublishedProjects({ projects }: PublishedProjectsProps) {
const anyVerified = projects.some((project) => project.repositoryVerified);
return (
<div className={styles.root}>
<ul className={styles.list}>
{projects.map((project, index) => (
<li key={`${index}:${project.title}`} className={styles.project}>
<div className={styles.header}>
<strong className={styles.title}>{project.title}</strong>
{project.repositoryVerified ? (
<Tag tone="success" dot>
Подтвержден публичным репозиторием
</Tag>
) : null}
</div>
{project.description ? (
<p className={styles.description}>{project.description}</p>
) : null}
{project.stack.length > 0 ? (
<ul className={styles.chips} aria-label="Технологии проекта">
{project.stack.map((tag) => (
<li key={tag}>
<Tag tone="stack">{tag}</Tag>
</li>
))}
</ul>
) : null}
</li>
))}
</ul>
{anyVerified ? (
<p className={styles.note}>
Отметка значит только, что публичный репозиторий проекта существует. Авторство она не
доказывает, а адрес репозитория компаниям не показывается.
</p>
) : null}
</div>
);
}
@@ -80,6 +80,11 @@ const codeMessages: Partial<Record<ApiErrorCode, ErrorMessage>> = {
title: "Запрос не прошел проверку",
description: "Проверьте введенные данные и повторите попытку.",
},
service_unavailable: {
title: "Сервис пока не готов",
description:
"Он загружается или временно перегружен. Ничего не потеряно: повторите попытку через минуту.",
},
not_implemented: {
title: "Функция еще не реализована",
description: "Этот раздел появится в одной из следующих версий.",
@@ -113,6 +113,21 @@ describe("describeError", () => {
});
});
it("names the service_unavailable code as a service that is not ready yet", () => {
const error = new ApiRequestError({
status: 503,
code: "service_unavailable",
title: "Service unavailable",
});
const html = renderToStaticMarkup(<ErrorState error={error} onRetry={() => undefined} />);
expect(describeError(error)).toMatchObject({
title: "Сервис пока не готов",
technical: { code: "service_unavailable", status: 503 },
});
expect(text(html)).toContain("Повторить");
});
it("treats a CSRF rejection as an error, not as missing access", () => {
const error = new ApiRequestError({ status: 403, code: "csrf_check_failed", title: "csrf" });
const html = renderToStaticMarkup(<ErrorState error={error} onRetry={() => undefined} />);
@@ -172,6 +172,47 @@ describe("match list", () => {
expect(html).toMatch(/>Заявлено: [^<]+</);
});
describe("matches by meaning", () => {
// The shared helper strips the markers that server rendering puts between text nodes.
const text = (html: string) => html.replaceAll("<!-- -->", "");
it("prints each requirement, the matched card item, and the similarity band", () => {
const html = text(render(matchModelFixture()));
expect(html).toContain("Совпадения по смыслу");
expect(html).toContain("Разработать сервис сверки платежей");
expect(html).toContain("Платежный шлюз");
expect(html).toContain("Высокое сходство");
expect(html).toContain("Среднее сходство");
expect(html).toContain(">Проект<");
expect(html).toContain(">Стек<");
expect(html).toContain(">Роль<");
expect(html).toContain("Обязательный навык");
expect(html).toContain("Желательный навык");
});
it("marks a verified project with the public repository badge, and no other row", () => {
const html = text(render(matchModelFixture()));
expect(html.match(/Публичный репозиторий/g)).toHaveLength(1);
});
it("shows no repository address, owner, or link in the evidence", () => {
const html = text(render(matchModelFixture()));
expect(html).not.toContain("github");
expect(html).not.toMatch(/href="https?:/);
});
it("keeps the unavailable wording where ML was down and shows nothing for a plain empty list", () => {
const html = text(render(matchModelFixture()));
expect(html).toContain("Совпадения по смыслу: смысловой анализ недоступен.");
// Only the near entry carries rows and only the first one the unavailable text.
expect(html.match(/Совпадения по смыслу<\/h6>/g)).toHaveLength(2);
});
});
it("marks the technologies that the search asked for, in words as well as a dot", () => {
const plain = render(matchModelFixture());
// A need result does not echo its filters, so the request's own are used.