feat: add candidate profile, questionnaire and company forms
This commit is contained in:
1 parent
3a61a8e8bb
commit
f81cd0ae09
68 files changed
+9517
-54
No files matched your search
@@ -0,0 +1,28 @@
|
||||
export {
|
||||
addExperience,
|
||||
addRole,
|
||||
addSoftSkill,
|
||||
addStack,
|
||||
buildCandidateProfileUpdate,
|
||||
mapProfileServerErrors,
|
||||
moveExperience,
|
||||
profilePointerField,
|
||||
removeExperience,
|
||||
removeItem,
|
||||
reviewExperienceOverlaps,
|
||||
setParallelAcknowledgement,
|
||||
toCandidateProfileDraft,
|
||||
updateExperienceDraft,
|
||||
updateFieldDraft,
|
||||
updateRoleDraft,
|
||||
updateSalaryDraft,
|
||||
updateSoftSkillDraft,
|
||||
updateStackDraft,
|
||||
type CandidateProfileDraft,
|
||||
type ExperienceDraft,
|
||||
type FieldDraft,
|
||||
type ProfileFormIssue,
|
||||
type RoleDraft,
|
||||
type SoftSkillDraft,
|
||||
type StackDraft,
|
||||
} from "./model/profile-form";
|
||||
@@ -0,0 +1,234 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CandidateProfile } from "../../../shared/api/schemas";
|
||||
import {
|
||||
addExperience,
|
||||
buildCandidateProfileUpdate,
|
||||
mapProfileServerErrors,
|
||||
moveExperience,
|
||||
reviewExperienceOverlaps,
|
||||
setParallelAcknowledgement,
|
||||
toCandidateProfileDraft,
|
||||
updateExperienceDraft,
|
||||
updateFieldDraft,
|
||||
} from "./profile-form";
|
||||
|
||||
const unknownClaim = { status: "unknown", value: null, source: null } as const;
|
||||
|
||||
function blankProfile(): CandidateProfile {
|
||||
return {
|
||||
version: 0,
|
||||
full_name: unknownClaim,
|
||||
contacts: { email: unknownClaim, phone: unknownClaim, telegram: unknownClaim },
|
||||
stack: [],
|
||||
roles: [],
|
||||
experience: [],
|
||||
experience_overlaps: [],
|
||||
soft_skills: [],
|
||||
terms: {
|
||||
location: unknownClaim,
|
||||
relocation: unknownClaim,
|
||||
salary_minimum: unknownClaim,
|
||||
},
|
||||
confirmed_categories: [],
|
||||
updated_at: null,
|
||||
};
|
||||
}
|
||||
|
||||
const suggestion = {
|
||||
origin: "extracted_from_resume",
|
||||
trust_level: 0,
|
||||
quote: "Работал с Go и PostgreSQL",
|
||||
extraction_version: "resume-rules.2026-10.1",
|
||||
confirmed_at: null,
|
||||
} as const;
|
||||
|
||||
describe("candidate profile draft mapping", () => {
|
||||
it("sends an empty first profile as unknown values at version zero", () => {
|
||||
const draft = toCandidateProfileDraft(blankProfile());
|
||||
const result = buildCandidateProfileUpdate(draft, new Date("2026-06-15T00:00:00Z"));
|
||||
|
||||
expect(result.issues).toEqual([]);
|
||||
expect(result.data).toMatchObject({
|
||||
expected_version: 0,
|
||||
full_name: null,
|
||||
contacts: { email: null, phone: null, telegram: null },
|
||||
stack: [],
|
||||
roles: [],
|
||||
experience: [],
|
||||
confirmed_parallel_periods: [],
|
||||
soft_skills: [],
|
||||
terms: { location: null, relocation: null, salary_minimum: null },
|
||||
});
|
||||
expect(result.data).not.toHaveProperty("confirmed_categories");
|
||||
});
|
||||
|
||||
it("preserves untouched suggestions and confirms a changed suggestion", () => {
|
||||
const profile: CandidateProfile = {
|
||||
...blankProfile(),
|
||||
version: 4,
|
||||
full_name: { status: "extracted", value: "Анна Соколова", source: suggestion },
|
||||
contacts: {
|
||||
email: unknownClaim,
|
||||
phone: { status: "extracted", value: "+79000000000", source: suggestion },
|
||||
telegram: unknownClaim,
|
||||
},
|
||||
stack: [{ tag: "Go", status: "extracted", source: suggestion }],
|
||||
experience: [
|
||||
{
|
||||
employer_name: "ООО Пример",
|
||||
specialization: "backend",
|
||||
started_on: "2022-01",
|
||||
ended_on: null,
|
||||
summary: "Разработка сервисов",
|
||||
status: "extracted",
|
||||
source: suggestion,
|
||||
},
|
||||
],
|
||||
soft_skills: [{ skill: "Наставничество", status: "extracted", source: suggestion }],
|
||||
terms: {
|
||||
location: { status: "extracted", value: "Казань", source: suggestion },
|
||||
relocation: unknownClaim,
|
||||
salary_minimum: unknownClaim,
|
||||
},
|
||||
};
|
||||
let draft = toCandidateProfileDraft(profile);
|
||||
const stackId = draft.stack[0]?.id;
|
||||
if (!stackId) throw new Error("Expected a stack suggestion in the fixture.");
|
||||
|
||||
let result = buildCandidateProfileUpdate(draft, new Date("2026-06-15T00:00:00Z"));
|
||||
expect(result.data?.full_name).toEqual({ value: "Анна Соколова", status: "extracted" });
|
||||
expect(result.data?.contacts.phone).toEqual({ value: "+79000000000", status: "extracted" });
|
||||
expect(result.data?.stack).toEqual([{ tag: "Go", status: "extracted" }]);
|
||||
expect(result.data?.experience[0]?.status).toBe("extracted");
|
||||
expect(result.data?.soft_skills).toEqual([{ skill: "Наставничество", status: "extracted" }]);
|
||||
expect(result.data?.terms.location).toEqual({ value: "Казань", status: "extracted" });
|
||||
|
||||
draft = {
|
||||
...draft,
|
||||
stack: draft.stack.map((item) =>
|
||||
item.id === stackId ? { ...item, tag: "Go и PostgreSQL", status: "confirmed" } : item,
|
||||
),
|
||||
};
|
||||
result = buildCandidateProfileUpdate(draft, new Date("2026-06-15T00:00:00Z"));
|
||||
expect(result.data?.stack).toEqual([{ tag: "Go и PostgreSQL", status: "confirmed" }]);
|
||||
|
||||
const nameDraft = toCandidateProfileDraft(profile).fullName;
|
||||
expect(updateFieldDraft(nameDraft, "Новое имя").status).toBe("confirmed");
|
||||
expect(updateFieldDraft(nameDraft, "Анна Соколова").status).toBe("extracted");
|
||||
});
|
||||
|
||||
it("requires an explicit range-bound acknowledgement and clears it after date edits or reorder", () => {
|
||||
let draft = toCandidateProfileDraft(blankProfile());
|
||||
draft = addExperience(draft, "first");
|
||||
draft = updateExperienceDraft(draft, "first", {
|
||||
employer_name: "Первая компания",
|
||||
specialization: "backend",
|
||||
started_on: "2023-01",
|
||||
ended_on: "2024-12",
|
||||
});
|
||||
draft = addExperience(draft, "second");
|
||||
draft = updateExperienceDraft(draft, "second", {
|
||||
employer_name: "Вторая компания",
|
||||
specialization: "frontend",
|
||||
started_on: "2024-01",
|
||||
ended_on: "2025-01",
|
||||
});
|
||||
|
||||
const overlap = reviewExperienceOverlaps(draft, new Date("2026-06-15T00:00:00Z"))[0];
|
||||
expect(overlap).toMatchObject({
|
||||
key: "0:1",
|
||||
requiresAcknowledgement: true,
|
||||
acknowledged: false,
|
||||
});
|
||||
expect(buildCandidateProfileUpdate(draft, new Date("2026-06-15T00:00:00Z")).data).toBeNull();
|
||||
|
||||
draft = setParallelAcknowledgement(draft, "0:1", true);
|
||||
const acknowledged = buildCandidateProfileUpdate(draft, new Date("2026-06-15T00:00:00Z"));
|
||||
expect(acknowledged.data?.confirmed_parallel_periods).toEqual([
|
||||
{
|
||||
first_index: 0,
|
||||
second_index: 1,
|
||||
first_period: { started_on: "2023-01", ended_on: "2024-12" },
|
||||
second_period: { started_on: "2024-01", ended_on: "2025-01" },
|
||||
},
|
||||
]);
|
||||
|
||||
const changed = updateExperienceDraft(draft, "second", { started_on: "2024-02" });
|
||||
expect(changed.parallelAcknowledgements).toEqual({});
|
||||
expect(
|
||||
reviewExperienceOverlaps(changed, new Date("2026-06-15T00:00:00Z"))[0]?.acknowledged,
|
||||
).toBe(false);
|
||||
|
||||
const reordered = moveExperience(draft, 1, -1);
|
||||
expect(reordered.parallelAcknowledgements).toEqual({});
|
||||
expect(
|
||||
reviewExperienceOverlaps(reordered, new Date("2026-06-15T00:00:00Z"))[0]
|
||||
?.requiresAcknowledgement,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("carries a confirmed overlap only for the original indices and exact date ranges", () => {
|
||||
const profile: CandidateProfile = {
|
||||
...blankProfile(),
|
||||
version: 2,
|
||||
experience: [
|
||||
{
|
||||
employer_name: null,
|
||||
specialization: "backend",
|
||||
started_on: "2023-01",
|
||||
ended_on: "2024-12",
|
||||
summary: null,
|
||||
status: "confirmed",
|
||||
source: {
|
||||
...suggestion,
|
||||
origin: "manual",
|
||||
quote: null,
|
||||
extraction_version: null,
|
||||
confirmed_at: "2026-01-01T00:00:00Z",
|
||||
},
|
||||
},
|
||||
{
|
||||
employer_name: null,
|
||||
specialization: "frontend",
|
||||
started_on: "2024-01",
|
||||
ended_on: "2025-01",
|
||||
summary: null,
|
||||
status: "confirmed",
|
||||
source: {
|
||||
...suggestion,
|
||||
origin: "manual",
|
||||
quote: null,
|
||||
extraction_version: null,
|
||||
confirmed_at: "2026-01-01T00:00:00Z",
|
||||
},
|
||||
},
|
||||
],
|
||||
experience_overlaps: [{ first_index: 0, second_index: 1, status: "confirmed" }],
|
||||
};
|
||||
const draft = toCandidateProfileDraft(profile);
|
||||
expect(
|
||||
reviewExperienceOverlaps(draft, new Date("2026-06-15T00:00:00Z"))[0]?.requiresAcknowledgement,
|
||||
).toBe(false);
|
||||
const changed = updateExperienceDraft(draft, "experience-0", { started_on: "2023-02" });
|
||||
expect(
|
||||
reviewExperienceOverlaps(changed, new Date("2026-06-15T00:00:00Z"))[0]
|
||||
?.requiresAcknowledgement,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("maps server validation pointers to the corresponding form fields", () => {
|
||||
expect(
|
||||
mapProfileServerErrors([
|
||||
{ pointer: "/contacts/phone/value" },
|
||||
{ pointer: "/experience/2/ended_on" },
|
||||
{ pointer: "/terms/salary_minimum/value/amount" },
|
||||
{ pointer: "/confirmed_parallel_periods/0/first_period/started_on" },
|
||||
]),
|
||||
).toEqual([
|
||||
{ field: "contacts.phone", message: "Проверьте значение и формат этого поля." },
|
||||
{ field: "experience.2.ended_on", message: "Проверьте значение и формат этого поля." },
|
||||
{ field: "terms.salaryMinimum.amount", message: "Проверьте значение и формат этого поля." },
|
||||
{ field: "experience.overlaps", message: "Проверьте значение и формат этого поля." },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,713 @@
|
||||
import {
|
||||
CandidateProfileUpdate as CandidateProfileUpdateSchema,
|
||||
type CandidateProfile,
|
||||
type CandidateProfileUpdate,
|
||||
} from "../../../shared/api/schemas";
|
||||
|
||||
type ClaimStatus = CandidateProfile["full_name"]["status"];
|
||||
type DecisionStatus = Exclude<ClaimStatus, "unknown">;
|
||||
type ClaimSource = NonNullable<CandidateProfile["full_name"]["source"]>;
|
||||
|
||||
export type FieldDraft<Value> = {
|
||||
value: Value;
|
||||
status: ClaimStatus;
|
||||
originalStatus: ClaimStatus;
|
||||
originalValue: Value | null;
|
||||
source: ClaimSource | null;
|
||||
};
|
||||
|
||||
type ItemMetadata<Value> = {
|
||||
id: string;
|
||||
originalIndex: number | null;
|
||||
status: DecisionStatus;
|
||||
originalStatus: DecisionStatus | null;
|
||||
originalValue: Value | null;
|
||||
source: ClaimSource | null;
|
||||
};
|
||||
|
||||
type StackValue = Pick<CandidateProfile["stack"][number], "tag">;
|
||||
type RoleValue = Omit<
|
||||
Pick<CandidateProfile["roles"][number], "specialization" | "self_assessed_grade">,
|
||||
"specialization"
|
||||
> & { specialization: CandidateProfile["roles"][number]["specialization"] | "" };
|
||||
type ExperienceValue = Omit<
|
||||
Pick<
|
||||
CandidateProfile["experience"][number],
|
||||
"employer_name" | "specialization" | "started_on" | "ended_on" | "summary"
|
||||
>,
|
||||
"specialization"
|
||||
> & { specialization: CandidateProfile["experience"][number]["specialization"] | "" };
|
||||
type SoftSkillValue = Pick<CandidateProfile["soft_skills"][number], "skill">;
|
||||
type SalaryValue = CandidateProfile["terms"]["salary_minimum"]["value"];
|
||||
|
||||
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 SalaryDraft = {
|
||||
amount: string;
|
||||
tax_basis: "net" | "gross" | "";
|
||||
status: ClaimStatus;
|
||||
originalStatus: ClaimStatus;
|
||||
originalValue: SalaryValue;
|
||||
source: ClaimSource | null;
|
||||
};
|
||||
|
||||
export type CandidateProfileDraft = {
|
||||
expectedVersion: number;
|
||||
fullName: FieldDraft<string>;
|
||||
contacts: {
|
||||
email: FieldDraft<string>;
|
||||
phone: FieldDraft<string>;
|
||||
telegram: FieldDraft<string>;
|
||||
};
|
||||
stack: StackDraft[];
|
||||
roles: RoleDraft[];
|
||||
experience: ExperienceDraft[];
|
||||
softSkills: SoftSkillDraft[];
|
||||
terms: {
|
||||
location: FieldDraft<string>;
|
||||
relocation: FieldDraft<boolean | null>;
|
||||
salaryMinimum: SalaryDraft;
|
||||
};
|
||||
confirmedCategories: CandidateProfile["confirmed_categories"];
|
||||
originalOverlaps: CandidateProfile["experience_overlaps"];
|
||||
parallelAcknowledgements: Record<string, boolean>;
|
||||
};
|
||||
|
||||
export type ExperienceOverlapReview = {
|
||||
key: string;
|
||||
firstIndex: number;
|
||||
secondIndex: number;
|
||||
firstPeriod: { started_on: string; ended_on: string | null };
|
||||
secondPeriod: { started_on: string; ended_on: string | null };
|
||||
requiresAcknowledgement: boolean;
|
||||
acknowledged: boolean;
|
||||
};
|
||||
|
||||
export type ProfileFormIssue = { field: string; message: string };
|
||||
|
||||
function textFieldDraft(claim: {
|
||||
status: ClaimStatus;
|
||||
value: string | null;
|
||||
source: ClaimSource | null;
|
||||
}): FieldDraft<string> {
|
||||
return {
|
||||
value: claim.value ?? "",
|
||||
status: claim.status,
|
||||
originalStatus: claim.status,
|
||||
originalValue: claim.value,
|
||||
source: claim.source,
|
||||
};
|
||||
}
|
||||
|
||||
function valueFieldDraft<Value>(claim: {
|
||||
status: ClaimStatus;
|
||||
value: Value | null;
|
||||
source: ClaimSource | null;
|
||||
}): FieldDraft<Value | null> {
|
||||
return {
|
||||
value: claim.value,
|
||||
status: claim.status,
|
||||
originalStatus: claim.status,
|
||||
originalValue: claim.value,
|
||||
source: claim.source,
|
||||
};
|
||||
}
|
||||
|
||||
function itemDraft<Value, Item extends { status: DecisionStatus; source: ClaimSource }>(
|
||||
id: string,
|
||||
index: number,
|
||||
item: Item,
|
||||
value: Value,
|
||||
): Value & ItemMetadata<Value> {
|
||||
return {
|
||||
...value,
|
||||
id,
|
||||
originalIndex: index,
|
||||
status: item.status,
|
||||
originalStatus: item.status,
|
||||
originalValue: value,
|
||||
source: item.source,
|
||||
};
|
||||
}
|
||||
|
||||
export function toCandidateProfileDraft(profile: CandidateProfile): CandidateProfileDraft {
|
||||
const salaryValue = profile.terms.salary_minimum.value;
|
||||
return {
|
||||
expectedVersion: profile.version,
|
||||
fullName: textFieldDraft(profile.full_name),
|
||||
contacts: {
|
||||
email: textFieldDraft(profile.contacts.email),
|
||||
phone: textFieldDraft(profile.contacts.phone),
|
||||
telegram: textFieldDraft(profile.contacts.telegram),
|
||||
},
|
||||
stack: profile.stack.map((item, index) =>
|
||||
itemDraft(`stack-${index}`, index, item, { tag: item.tag }),
|
||||
),
|
||||
roles: profile.roles.map((item, index) =>
|
||||
itemDraft(`role-${index}`, index, item, {
|
||||
specialization: item.specialization,
|
||||
self_assessed_grade: item.self_assessed_grade,
|
||||
}),
|
||||
),
|
||||
experience: profile.experience.map((item, index) =>
|
||||
itemDraft(`experience-${index}`, index, item, {
|
||||
employer_name: item.employer_name,
|
||||
specialization: item.specialization,
|
||||
started_on: item.started_on,
|
||||
ended_on: item.ended_on,
|
||||
summary: item.summary,
|
||||
}),
|
||||
),
|
||||
softSkills: profile.soft_skills.map((item, index) =>
|
||||
itemDraft(`soft-skill-${index}`, index, item, { skill: item.skill }),
|
||||
),
|
||||
terms: {
|
||||
location: textFieldDraft(profile.terms.location),
|
||||
relocation: valueFieldDraft(profile.terms.relocation),
|
||||
salaryMinimum: {
|
||||
amount: salaryValue ? String(salaryValue.amount) : "",
|
||||
tax_basis: salaryValue?.tax_basis ?? "",
|
||||
status: profile.terms.salary_minimum.status,
|
||||
originalStatus: profile.terms.salary_minimum.status,
|
||||
originalValue: salaryValue,
|
||||
source: profile.terms.salary_minimum.source,
|
||||
},
|
||||
},
|
||||
confirmedCategories: profile.confirmed_categories,
|
||||
originalOverlaps: profile.experience_overlaps,
|
||||
parallelAcknowledgements: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function updateFieldDraft<Value>(draft: FieldDraft<Value>, value: Value): FieldDraft<Value> {
|
||||
const keepSuggestion =
|
||||
draft.originalStatus === "extracted" && sameValue(value, draft.originalValue);
|
||||
const remainsUnknown = draft.originalStatus === "unknown" && isEmptyValue(value);
|
||||
return {
|
||||
...draft,
|
||||
value,
|
||||
status: keepSuggestion ? "extracted" : remainsUnknown ? "unknown" : "confirmed",
|
||||
};
|
||||
}
|
||||
|
||||
export function updateStackDraft(
|
||||
draft: CandidateProfileDraft,
|
||||
id: string,
|
||||
patch: Partial<StackValue>,
|
||||
): CandidateProfileDraft {
|
||||
return updateItem(draft, "stack", id, patch);
|
||||
}
|
||||
|
||||
export function updateRoleDraft(
|
||||
draft: CandidateProfileDraft,
|
||||
id: string,
|
||||
patch: Partial<RoleValue>,
|
||||
): CandidateProfileDraft {
|
||||
return updateItem(draft, "roles", id, patch);
|
||||
}
|
||||
|
||||
export function updateExperienceDraft(
|
||||
draft: CandidateProfileDraft,
|
||||
id: string,
|
||||
patch: Partial<ExperienceValue>,
|
||||
): CandidateProfileDraft {
|
||||
const dateChanged = "started_on" in patch || "ended_on" in patch;
|
||||
const updated = updateItem(draft, "experience", id, patch);
|
||||
return dateChanged ? { ...updated, parallelAcknowledgements: {} } : updated;
|
||||
}
|
||||
|
||||
export function updateSalaryDraft(
|
||||
draft: CandidateProfileDraft,
|
||||
patch: Partial<Pick<SalaryDraft, "amount" | "tax_basis">>,
|
||||
): CandidateProfileDraft {
|
||||
const next = { ...draft.terms.salaryMinimum, ...patch };
|
||||
const sameOriginal = Boolean(
|
||||
next.amount.trim() !== "" &&
|
||||
next.tax_basis !== "" &&
|
||||
next.originalValue &&
|
||||
Number(next.amount) === next.originalValue.amount &&
|
||||
next.tax_basis === next.originalValue.tax_basis,
|
||||
);
|
||||
const isEmpty = next.amount.trim() === "";
|
||||
return {
|
||||
...draft,
|
||||
terms: {
|
||||
...draft.terms,
|
||||
salaryMinimum: {
|
||||
...next,
|
||||
status:
|
||||
next.originalStatus === "extracted" && sameOriginal
|
||||
? "extracted"
|
||||
: next.originalStatus === "unknown" && isEmpty
|
||||
? "unknown"
|
||||
: "confirmed",
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function updateSoftSkillDraft(
|
||||
draft: CandidateProfileDraft,
|
||||
id: string,
|
||||
patch: Partial<SoftSkillValue>,
|
||||
): CandidateProfileDraft {
|
||||
return updateItem(draft, "softSkills", id, patch);
|
||||
}
|
||||
|
||||
function updateItem<
|
||||
Key extends "stack" | "roles" | "experience" | "softSkills",
|
||||
Item extends CandidateProfileDraft[Key][number],
|
||||
Patch extends Partial<Omit<Item, keyof ItemMetadata<unknown>>>,
|
||||
>(draft: CandidateProfileDraft, key: Key, id: string, patch: Patch): CandidateProfileDraft {
|
||||
const items = draft[key] as Item[];
|
||||
const updatedItems = items.map((item) => {
|
||||
if (item.id !== id) return item;
|
||||
const next = { ...item, ...patch };
|
||||
const unchangedSuggestion =
|
||||
item.originalStatus === "extracted" &&
|
||||
item.originalValue !== null &&
|
||||
sameValue(itemValue(next), item.originalValue);
|
||||
return {
|
||||
...next,
|
||||
status: unchangedSuggestion ? "extracted" : "confirmed",
|
||||
} as Item;
|
||||
});
|
||||
return { ...draft, [key]: updatedItems } as CandidateProfileDraft;
|
||||
}
|
||||
|
||||
function itemValue(item: object): object {
|
||||
const value: Record<string, unknown> = {};
|
||||
for (const [key, itemValue] of Object.entries(item)) {
|
||||
if (
|
||||
key !== "id" &&
|
||||
key !== "originalIndex" &&
|
||||
key !== "status" &&
|
||||
key !== "originalStatus" &&
|
||||
key !== "originalValue" &&
|
||||
key !== "source"
|
||||
) {
|
||||
value[key] = itemValue;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function sameValue(left: unknown, right: unknown): boolean {
|
||||
return JSON.stringify(left) === JSON.stringify(right);
|
||||
}
|
||||
|
||||
function isEmptyValue(value: unknown): boolean {
|
||||
return value === "" || value === null;
|
||||
}
|
||||
|
||||
function monthNumber(value: string): number | null {
|
||||
if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(value)) return null;
|
||||
const year = Number(value.slice(0, 4));
|
||||
const month = Number(value.slice(5, 7));
|
||||
return year * 12 + month - 1;
|
||||
}
|
||||
|
||||
function rangesOverlap(
|
||||
first: ExperienceDraft,
|
||||
second: ExperienceDraft,
|
||||
currentMonth: number,
|
||||
): boolean {
|
||||
const firstStart = monthNumber(first.started_on);
|
||||
const secondStart = monthNumber(second.started_on);
|
||||
const firstEnd = first.ended_on === null ? currentMonth : monthNumber(first.ended_on);
|
||||
const secondEnd = second.ended_on === null ? currentMonth : monthNumber(second.ended_on);
|
||||
if (firstStart === null || secondStart === null || firstEnd === null || secondEnd === null) {
|
||||
return false;
|
||||
}
|
||||
if (firstStart > firstEnd || secondStart > secondEnd) return false;
|
||||
return firstStart <= secondEnd && secondStart <= firstEnd;
|
||||
}
|
||||
|
||||
function samePeriod(current: ExperienceDraft, original: ExperienceValue | null): boolean {
|
||||
return Boolean(
|
||||
original &&
|
||||
current.started_on === original.started_on &&
|
||||
current.ended_on === original.ended_on,
|
||||
);
|
||||
}
|
||||
|
||||
export function reviewExperienceOverlaps(
|
||||
draft: CandidateProfileDraft,
|
||||
now = new Date(),
|
||||
): ExperienceOverlapReview[] {
|
||||
const currentMonth = now.getUTCFullYear() * 12 + now.getUTCMonth();
|
||||
const overlaps: ExperienceOverlapReview[] = [];
|
||||
for (let firstIndex = 0; firstIndex < draft.experience.length; firstIndex += 1) {
|
||||
const first = draft.experience[firstIndex];
|
||||
if (!first) continue;
|
||||
for (
|
||||
let secondIndex = firstIndex + 1;
|
||||
secondIndex < draft.experience.length;
|
||||
secondIndex += 1
|
||||
) {
|
||||
const second = draft.experience[secondIndex];
|
||||
if (!second || !rangesOverlap(first, second, currentMonth)) continue;
|
||||
const key = `${firstIndex}:${secondIndex}`;
|
||||
const prior = draft.originalOverlaps.find(
|
||||
(overlap) => overlap.first_index === firstIndex && overlap.second_index === secondIndex,
|
||||
);
|
||||
const unchangedConfirmed = Boolean(
|
||||
prior?.status === "confirmed" &&
|
||||
first.originalIndex === firstIndex &&
|
||||
second.originalIndex === secondIndex &&
|
||||
samePeriod(first, first.originalValue) &&
|
||||
samePeriod(second, second.originalValue),
|
||||
);
|
||||
overlaps.push({
|
||||
key,
|
||||
firstIndex,
|
||||
secondIndex,
|
||||
firstPeriod: { started_on: first.started_on, ended_on: first.ended_on },
|
||||
secondPeriod: { started_on: second.started_on, ended_on: second.ended_on },
|
||||
requiresAcknowledgement: !unchangedConfirmed,
|
||||
acknowledged: draft.parallelAcknowledgements[key] === true,
|
||||
});
|
||||
}
|
||||
}
|
||||
return overlaps;
|
||||
}
|
||||
|
||||
export function setParallelAcknowledgement(
|
||||
draft: CandidateProfileDraft,
|
||||
key: string,
|
||||
acknowledged: boolean,
|
||||
): CandidateProfileDraft {
|
||||
return {
|
||||
...draft,
|
||||
parallelAcknowledgements: { ...draft.parallelAcknowledgements, [key]: acknowledged },
|
||||
};
|
||||
}
|
||||
|
||||
export function addExperience(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
|
||||
return {
|
||||
...draft,
|
||||
experience: [
|
||||
...draft.experience,
|
||||
{
|
||||
id,
|
||||
originalIndex: null,
|
||||
employer_name: null,
|
||||
specialization: "",
|
||||
started_on: "",
|
||||
ended_on: null,
|
||||
summary: null,
|
||||
status: "confirmed",
|
||||
originalStatus: null,
|
||||
originalValue: null,
|
||||
source: null,
|
||||
},
|
||||
],
|
||||
parallelAcknowledgements: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function removeExperience(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
|
||||
return {
|
||||
...draft,
|
||||
experience: draft.experience.filter((item) => item.id !== id),
|
||||
parallelAcknowledgements: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function moveExperience(
|
||||
draft: CandidateProfileDraft,
|
||||
index: number,
|
||||
direction: -1 | 1,
|
||||
): CandidateProfileDraft {
|
||||
const targetIndex = index + direction;
|
||||
if (targetIndex < 0 || targetIndex >= draft.experience.length) return draft;
|
||||
const experience = [...draft.experience];
|
||||
[experience[index], experience[targetIndex]] = [experience[targetIndex]!, experience[index]!];
|
||||
return { ...draft, experience, parallelAcknowledgements: {} };
|
||||
}
|
||||
|
||||
export function addStack(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
|
||||
return {
|
||||
...draft,
|
||||
stack: [
|
||||
...draft.stack,
|
||||
{
|
||||
id,
|
||||
originalIndex: null,
|
||||
tag: "",
|
||||
status: "confirmed",
|
||||
originalStatus: null,
|
||||
originalValue: null,
|
||||
source: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export function addRole(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
|
||||
return {
|
||||
...draft,
|
||||
roles: [
|
||||
...draft.roles,
|
||||
{
|
||||
id,
|
||||
originalIndex: null,
|
||||
specialization: "",
|
||||
self_assessed_grade: null,
|
||||
status: "confirmed",
|
||||
originalStatus: null,
|
||||
originalValue: null,
|
||||
source: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export function addSoftSkill(draft: CandidateProfileDraft, id: string): CandidateProfileDraft {
|
||||
return {
|
||||
...draft,
|
||||
softSkills: [
|
||||
...draft.softSkills,
|
||||
{
|
||||
id,
|
||||
originalIndex: null,
|
||||
skill: "",
|
||||
status: "confirmed",
|
||||
originalStatus: null,
|
||||
originalValue: null,
|
||||
source: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export function removeItem<Key extends "stack" | "roles" | "softSkills">(
|
||||
draft: CandidateProfileDraft,
|
||||
key: Key,
|
||||
id: string,
|
||||
): CandidateProfileDraft {
|
||||
return { ...draft, [key]: draft[key].filter((item) => item.id !== id) } as CandidateProfileDraft;
|
||||
}
|
||||
|
||||
function fieldDecision<Value>(
|
||||
draft: FieldDraft<Value>,
|
||||
value = draft.value,
|
||||
): { value: Exclude<Value, null | "">; status: DecisionStatus } | null {
|
||||
if (isEmptyValue(value)) return null;
|
||||
const extracted = draft.status === "extracted" && sameValue(value, draft.originalValue);
|
||||
return {
|
||||
value: value as Exclude<Value, null | "">,
|
||||
status: extracted ? "extracted" : "confirmed",
|
||||
};
|
||||
}
|
||||
|
||||
function itemDecision<Value>(
|
||||
item: Value & ItemMetadata<Value>,
|
||||
): Value & { status: DecisionStatus } {
|
||||
const extracted =
|
||||
item.status === "extracted" &&
|
||||
item.originalValue !== null &&
|
||||
sameValue(itemValue(item), item.originalValue);
|
||||
return { ...itemValue(item), status: extracted ? "extracted" : "confirmed" } as Value & {
|
||||
status: DecisionStatus;
|
||||
};
|
||||
}
|
||||
|
||||
function escapePointerSegment(value: string | number): string {
|
||||
return String(value).replaceAll("~", "~0").replaceAll("/", "~1");
|
||||
}
|
||||
|
||||
function fieldForPointer(pointer: string): string {
|
||||
const parts = pointer
|
||||
.split("/")
|
||||
.slice(1)
|
||||
.map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
||||
const [root, index, property, detail] = parts;
|
||||
if (root === "full_name") return "fullName";
|
||||
if (root === "contacts" && index) return `contacts.${index}`;
|
||||
if (root === "stack" && index !== undefined) return `stack.${index}.${property ?? "tag"}`;
|
||||
if (root === "roles" && index !== undefined)
|
||||
return `roles.${index}.${property ?? "specialization"}`;
|
||||
if (root === "experience" && index !== undefined)
|
||||
return `experience.${index}.${property ?? "started_on"}`;
|
||||
if (root === "soft_skills" && index !== undefined) return `softSkills.${index}.skill`;
|
||||
if (root === "terms" && index) {
|
||||
if (index === "salary_minimum") {
|
||||
return property === "value"
|
||||
? `terms.salaryMinimum.${detail ?? "amount"}`
|
||||
: "terms.salaryMinimum";
|
||||
}
|
||||
return `terms.${index}`;
|
||||
}
|
||||
if (root === "confirmed_parallel_periods") return "experience.overlaps";
|
||||
if (root === "expected_version" || !root) return "form";
|
||||
return "form";
|
||||
}
|
||||
|
||||
function zodPointer(path: readonly PropertyKey[]): string {
|
||||
return `/${path.map((part) => escapePointerSegment(String(part))).join("/")}`;
|
||||
}
|
||||
|
||||
function monthIsFuture(value: string, now: Date): boolean {
|
||||
const month = monthNumber(value);
|
||||
if (month === null) return false;
|
||||
const current = now.getUTCFullYear() * 12 + now.getUTCMonth();
|
||||
return month > current;
|
||||
}
|
||||
|
||||
function customValidationIssues(draft: CandidateProfileDraft, now: Date): ProfileFormIssue[] {
|
||||
const issues: ProfileFormIssue[] = [];
|
||||
const duplicates = <Value>(
|
||||
items: Value[],
|
||||
valueOf: (value: Value) => string,
|
||||
fieldOfIndex: (index: number) => string,
|
||||
) => {
|
||||
const seen = new Set<string>();
|
||||
items.forEach((item, index) => {
|
||||
const value = valueOf(item).trim().toLocaleLowerCase("ru");
|
||||
if (!value) return;
|
||||
if (seen.has(value)) {
|
||||
issues.push({ field: fieldOfIndex(index), message: "Повторяющееся значение." });
|
||||
}
|
||||
seen.add(value);
|
||||
});
|
||||
};
|
||||
duplicates(
|
||||
draft.stack,
|
||||
(item) => item.tag,
|
||||
(index) => `stack.${index}.tag`,
|
||||
);
|
||||
duplicates(
|
||||
draft.roles,
|
||||
(item) => item.specialization,
|
||||
(index) => `roles.${index}.specialization`,
|
||||
);
|
||||
duplicates(
|
||||
draft.softSkills,
|
||||
(item) => item.skill,
|
||||
(index) => `softSkills.${index}.skill`,
|
||||
);
|
||||
draft.experience.forEach((item, index) => {
|
||||
const start = monthNumber(item.started_on);
|
||||
const end = item.ended_on === null ? null : monthNumber(item.ended_on);
|
||||
if (start !== null && monthIsFuture(item.started_on, now)) {
|
||||
issues.push({
|
||||
field: `experience.${index}.started_on`,
|
||||
message: "Месяц не может быть в будущем.",
|
||||
});
|
||||
}
|
||||
if (item.ended_on !== null && end !== null && monthIsFuture(item.ended_on, now)) {
|
||||
issues.push({
|
||||
field: `experience.${index}.ended_on`,
|
||||
message: "Месяц не может быть в будущем.",
|
||||
});
|
||||
}
|
||||
if (start !== null && end !== null && end < start) {
|
||||
issues.push({
|
||||
field: `experience.${index}.ended_on`,
|
||||
message: "Месяц окончания должен быть не раньше начала.",
|
||||
});
|
||||
}
|
||||
});
|
||||
if (draft.terms.salaryMinimum.amount.trim() && !draft.terms.salaryMinimum.tax_basis) {
|
||||
issues.push({
|
||||
field: "terms.salaryMinimum.tax_basis",
|
||||
message: "Выберите, указана сумма до или после налога.",
|
||||
});
|
||||
}
|
||||
for (const overlap of reviewExperienceOverlaps(draft, now)) {
|
||||
if (overlap.requiresAcknowledgement && !overlap.acknowledged) {
|
||||
issues.push({
|
||||
field: "experience.overlaps",
|
||||
message: `Подтвердите отдельно, что периоды ${overlap.firstIndex + 1} и ${overlap.secondIndex + 1} действительно шли параллельно.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
|
||||
export function profilePointerField(pointer: string): string {
|
||||
return fieldForPointer(pointer);
|
||||
}
|
||||
|
||||
export function buildCandidateProfileUpdate(
|
||||
draft: CandidateProfileDraft,
|
||||
now = new Date(),
|
||||
): { data: CandidateProfileUpdate | null; issues: ProfileFormIssue[] } {
|
||||
const salaryAmount = draft.terms.salaryMinimum.amount.trim();
|
||||
const salaryValue: SalaryValue =
|
||||
salaryAmount && draft.terms.salaryMinimum.tax_basis
|
||||
? {
|
||||
amount: Number(salaryAmount),
|
||||
currency: "RUB",
|
||||
period: "month",
|
||||
tax_basis: draft.terms.salaryMinimum.tax_basis,
|
||||
}
|
||||
: null;
|
||||
const data: unknown = {
|
||||
expected_version: draft.expectedVersion,
|
||||
full_name: fieldDecision(draft.fullName, draft.fullName.value.trim()),
|
||||
contacts: {
|
||||
email: fieldDecision(draft.contacts.email, draft.contacts.email.value.trim()),
|
||||
phone: fieldDecision(draft.contacts.phone, draft.contacts.phone.value.trim()),
|
||||
telegram: fieldDecision(draft.contacts.telegram, draft.contacts.telegram.value.trim()),
|
||||
},
|
||||
stack: draft.stack.filter((item) => item.tag.trim()).map(itemDecision),
|
||||
roles: draft.roles.map(itemDecision),
|
||||
experience: draft.experience.map((item) =>
|
||||
itemDecision({
|
||||
...item,
|
||||
employer_name: item.employer_name?.trim() || null,
|
||||
summary: item.summary?.trim() || null,
|
||||
}),
|
||||
),
|
||||
confirmed_parallel_periods: reviewExperienceOverlaps(draft, now)
|
||||
.filter((overlap) => overlap.requiresAcknowledgement && overlap.acknowledged)
|
||||
.map((overlap) => ({
|
||||
first_index: overlap.firstIndex,
|
||||
second_index: overlap.secondIndex,
|
||||
first_period: overlap.firstPeriod,
|
||||
second_period: overlap.secondPeriod,
|
||||
})),
|
||||
soft_skills: draft.softSkills.filter((item) => item.skill.trim()).map(itemDecision),
|
||||
terms: {
|
||||
location: fieldDecision(draft.terms.location, draft.terms.location.value.trim()),
|
||||
relocation: fieldDecision(draft.terms.relocation),
|
||||
salary_minimum: salaryValue
|
||||
? {
|
||||
value: salaryValue,
|
||||
status:
|
||||
draft.terms.salaryMinimum.status === "extracted" &&
|
||||
sameValue(salaryValue, draft.terms.salaryMinimum.originalValue)
|
||||
? "extracted"
|
||||
: "confirmed",
|
||||
}
|
||||
: null,
|
||||
},
|
||||
};
|
||||
|
||||
const issues = customValidationIssues(draft, now);
|
||||
const parsed = CandidateProfileUpdateSchema.safeParse(data);
|
||||
if (!parsed.success) {
|
||||
issues.push(
|
||||
...parsed.error.issues.map((issue) => ({
|
||||
field: fieldForPointer(zodPointer(issue.path)),
|
||||
message: "Проверьте значение и формат этого поля.",
|
||||
})),
|
||||
);
|
||||
}
|
||||
return {
|
||||
data: issues.length === 0 && parsed.success ? (parsed.data as CandidateProfileUpdate) : null,
|
||||
issues,
|
||||
};
|
||||
}
|
||||
|
||||
export function mapProfileServerErrors(errors: readonly { pointer: string }[]): ProfileFormIssue[] {
|
||||
return errors.map((error) => ({
|
||||
field: fieldForPointer(error.pointer),
|
||||
message: "Проверьте значение и формат этого поля.",
|
||||
}));
|
||||
}
|
||||
Reference in new issue
Block a user