Files
lincodex/frontend/src/shared/api/profile-contract.test.ts
T

413 lines
14 KiB
TypeScript

import { readFileSync, readdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, expectTypeOf, it } from "vitest";
import { saveMyProfile } from "./endpoints/candidate/candidate";
import {
CandidateProfile,
CandidateProfileUpdate,
ProfileClaimSource,
ProfileConfirmedCategory,
ProfileRoleItem,
ProfileRoleItemInput,
SaveMyProfileBody,
} from "./schemas";
// These tests pin the generated candidate profile contract that
// the profile form consumes. They fail when regeneration drops a limit, lets a
// request carry a confirmed grade, a category, or provenance, loses the trust
// level of a claim, or mixes the private profile with organization DTOs.
const manual = (confirmedAt = "2026-10-05T09:30:00Z") => ({
origin: "manual",
trust_level: 0,
quote: null,
extraction_version: null,
confirmed_at: confirmedAt,
});
const suggestion = {
origin: "extracted_from_resume",
trust_level: 0,
quote: "Tel.: +7 900 000-00-00",
extraction_version: "resume-rules.2026-10.1",
confirmed_at: null,
};
// without returns a copy of an object that lacks one key.
function without<T extends object>(value: T, key: string): Record<string, unknown> {
return Object.fromEntries(Object.entries(value).filter(([name]) => name !== key));
}
const unknownClaim = { status: "unknown", value: null, source: null } as const;
const validUpdate = {
expected_version: 0,
full_name: { value: "Anna Sokolova", status: "confirmed" },
contacts: {
email: { value: "anna.sokolova@example.com", status: "confirmed" },
phone: { value: "+79000000000", status: "extracted" },
telegram: null,
},
stack: [
{ tag: "PostgreSQL", status: "confirmed" },
{ tag: "Kafka", status: "extracted" },
],
roles: [{ specialization: "backend", self_assessed_grade: "middle", status: "confirmed" }],
experience: [
{
employer_name: "Example Payments",
specialization: "backend",
started_on: "2022-03",
ended_on: null,
summary: "Moved the payout service to an event model.",
status: "confirmed",
},
],
confirmed_parallel_periods: [],
soft_skills: [{ skill: "Mentoring", status: "confirmed" }],
terms: {
location: { value: "Kazan", status: "confirmed" },
relocation: { value: false, status: "confirmed" },
salary_minimum: {
value: { amount: 180000, currency: "RUB", period: "month", tax_basis: "net" },
status: "confirmed",
},
},
};
const emptyUpdate = {
expected_version: 3,
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 },
};
const profile = {
version: 3,
full_name: { status: "confirmed", value: "Anna Sokolova", source: manual() },
contacts: {
email: unknownClaim,
phone: { status: "extracted", value: "+79000000000", source: suggestion },
telegram: unknownClaim,
},
stack: [{ tag: "PostgreSQL", status: "confirmed", source: manual() }],
roles: [
{
specialization: "backend",
self_assessed_grade: "middle",
status: "confirmed",
source: manual(),
},
],
experience: [],
experience_overlaps: [],
soft_skills: [],
terms: { location: unknownClaim, relocation: unknownClaim, salary_minimum: unknownClaim },
confirmed_categories: [
{
specialization: "backend",
grade: "junior",
confirmed_at: "2026-10-04T18:10:00Z",
attempt_id: "0192b3c4-d5e6-7f80-9a1b-2c3d4e5f6a7b",
},
],
updated_at: "2026-10-05T09:30:00Z",
};
const bodySchemas = [
["CandidateProfileUpdate", CandidateProfileUpdate],
["SaveMyProfileBody", SaveMyProfileBody],
] as const;
describe.each(bodySchemas)("generated %s", (_name, schema) => {
it("accepts a manual profile with a kept suggestion", () => {
const parsed = schema.parse(validUpdate);
expect(parsed.contacts.phone?.status).toBe("extracted");
expect(parsed.roles[0]?.self_assessed_grade).toBe("middle");
});
it("accepts a profile with nothing set, so no file or FSP link is required", () => {
expect(schema.parse(emptyUpdate)).toEqual(emptyUpdate);
});
it("requires the version that the client read", () => {
const withoutVersion = without(validUpdate, "expected_version");
const result = schema.safeParse(withoutVersion);
expect(result.success).toBe(false);
expect(result.error?.issues).toEqual([expect.objectContaining({ path: ["expected_version"] })]);
});
it.each([
[
"a phone outside E.164",
{ contacts: { ...validUpdate.contacts, phone: { value: "8 900 000", status: "confirmed" } } },
["contacts", "phone", "value"],
],
[
"a Telegram name without @",
{ contacts: { ...validUpdate.contacts, telegram: { value: "anna", status: "confirmed" } } },
["contacts", "telegram", "value"],
],
[
"an email that is not an address",
{ contacts: { ...validUpdate.contacts, email: { value: "anna", status: "confirmed" } } },
["contacts", "email", "value"],
],
[
"a decision outside confirmed and extracted",
{ stack: [{ tag: "Go", status: "unknown" }] },
["stack", 0, "status"],
],
[
"a name with surrounding whitespace",
{ full_name: { value: " Anna", status: "confirmed" } },
["full_name", "value"],
],
[
"a grade outside the scale",
{ roles: [{ specialization: "backend", self_assessed_grade: "lead", status: "confirmed" }] },
["roles", 0, "self_assessed_grade"],
],
[
"a language used as a specialization",
{ roles: [{ specialization: "go", self_assessed_grade: null, status: "confirmed" }] },
["roles", 0, "specialization"],
],
[
"a month outside YYYY-MM",
{ experience: [{ ...validUpdate.experience[0], started_on: "2022-3" }] },
["experience", 0, "started_on"],
],
[
"a salary that is not a multiple of 1000",
{
terms: {
...validUpdate.terms,
salary_minimum: {
value: { amount: 180500, currency: "RUB", period: "month", tax_basis: "net" },
status: "confirmed",
},
},
},
["terms", "salary_minimum", "value", "amount"],
],
[
"a salary in another currency",
{
terms: {
...validUpdate.terms,
salary_minimum: {
value: { amount: 180000, currency: "USD", period: "month", tax_basis: "net" },
status: "confirmed",
},
},
},
["terms", "salary_minimum"],
],
])("rejects %s", (_label, change, path) => {
const result = schema.safeParse({ ...validUpdate, ...change });
expect(result.success).toBe(false);
expect(result.error?.issues).toContainEqual(expect.objectContaining({ path }));
});
it("rejects more items than a list allows instead of truncating it", () => {
const stack = Array.from({ length: 31 }, (_, index) => ({
tag: `Tag ${index}`,
status: "confirmed",
}));
const roles = Array.from({ length: 10 }, () => ({
specialization: "qa",
self_assessed_grade: null,
status: "confirmed",
}));
const tooManyTags = schema.safeParse({ ...validUpdate, stack });
const tooManyRoles = schema.safeParse({ ...validUpdate, roles });
expect(tooManyTags.error?.issues).toEqual([
expect.objectContaining({ code: "too_big", path: ["stack"] }),
]);
expect(tooManyRoles.error?.issues).toEqual([
expect.objectContaining({ code: "too_big", path: ["roles"] }),
]);
});
it("never carries a confirmed grade, a category, or provenance in the parsed body", () => {
const parsed = schema.parse({
...validUpdate,
confirmed_categories: [{ specialization: "backend", grade: "senior" }],
full_name: {
value: "Anna Sokolova",
status: "confirmed",
source: suggestion,
trust_level: 5,
},
roles: [
{
specialization: "backend",
self_assessed_grade: "senior",
status: "confirmed",
confirmed_grade: "senior",
category: "backend",
},
],
});
// Generated Zod strips unknown keys; the server rejects them with 400.
expect(parsed).not.toHaveProperty("confirmed_categories");
expect(parsed.full_name).not.toHaveProperty("source");
expect(parsed.full_name).not.toHaveProperty("trust_level");
expect(parsed.roles[0]).not.toHaveProperty("confirmed_grade");
expect(parsed.roles[0]).not.toHaveProperty("category");
});
});
describe("generated CandidateProfile", () => {
it("separates the self-assessed grade of a role from the confirmed category", () => {
const parsed = CandidateProfile.parse(profile);
expect(parsed.roles[0]?.self_assessed_grade).toBe("middle");
expect(parsed.confirmed_categories).toEqual([
expect.objectContaining({ specialization: "backend", grade: "junior" }),
]);
expect(parsed.roles[0]).not.toHaveProperty("confirmed_grade");
});
it("gives every claim a source with trust level 0", () => {
expect(ProfileClaimSource.safeParse(suggestion).success).toBe(true);
expect(ProfileClaimSource.safeParse(manual()).success).toBe(true);
expect(ProfileClaimSource.safeParse({ ...suggestion, trust_level: 1 }).success).toBe(false);
expect(ProfileClaimSource.safeParse({ ...manual(), origin: "verified" }).success).toBe(false);
const withoutSource = without(profile.stack[0] ?? {}, "source");
expect(CandidateProfile.safeParse({ ...profile, stack: [withoutSource] }).success).toBe(false);
});
it("keeps an unconfirmed suggestion apart from a confirmed value", () => {
const parsed = CandidateProfile.parse(profile);
expect(parsed.contacts.phone.status).toBe("extracted");
expect(parsed.contacts.phone.source?.confirmed_at).toBeNull();
expect(parsed.contacts.phone.source?.trust_level).toBe(0);
expect(parsed.full_name.source?.confirmed_at).toBe("2026-10-05T09:30:00Z");
});
it("represents a profile that was never saved as version 0 with unknown fields", () => {
const parsed = CandidateProfile.parse({
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,
});
expect(parsed.version).toBe(0);
expect(parsed.confirmed_categories).toEqual([]);
});
it("requires a confirmed category to name its assessment", () => {
const withoutAttempt = without(profile.confirmed_categories[0] ?? {}, "attempt_id");
expect(ProfileConfirmedCategory.safeParse(profile.confirmed_categories[0]).success).toBe(true);
expect(ProfileConfirmedCategory.safeParse(withoutAttempt).success).toBe(false);
});
});
it("exposes the profile DTOs without a confirmed grade or a category in requests", () => {
type UpdateRole = CandidateProfileUpdate["roles"][number];
expectTypeOf<CandidateProfileUpdate>().not.toHaveProperty("confirmed_categories");
expectTypeOf<CandidateProfileUpdate>().not.toHaveProperty("version");
expectTypeOf<CandidateProfileUpdate>().toHaveProperty("confirmed_parallel_periods");
expectTypeOf<UpdateRole>().not.toHaveProperty("confirmed_grade");
expectTypeOf<UpdateRole>().not.toHaveProperty("category");
expectTypeOf<UpdateRole>().not.toHaveProperty("source");
expectTypeOf<ProfileRoleItemInput>().not.toHaveProperty("trust_level");
expectTypeOf<ProfileRoleItem>().not.toHaveProperty("confirmed_grade");
expectTypeOf<ProfileRoleItem>().not.toHaveProperty("category");
expectTypeOf<CandidateProfile>().toHaveProperty("confirmed_categories");
expectTypeOf<CandidateProfile>().toHaveProperty("experience_overlaps");
expectTypeOf(saveMyProfile).parameter(0).toEqualTypeOf<CandidateProfileUpdate>();
});
// The private profile holds personal data that no organization may read. The
// generated Zod files inline every referenced schema, so a profile schema that
// an organization-visible schema referred to would leave its field names in
// that generated file. The check reads the generated files: the organization,
// invitation, and need schemas and endpoints carry no profile-only field, and
// the profile schemas carry no organization-only field.
describe("private profile schemas", () => {
const apiDirectory = resolve(dirname(fileURLToPath(import.meta.url)));
const sourcesIn = (directory: string) =>
readdirSync(join(apiDirectory, directory), { recursive: true, encoding: "utf8" })
.filter((name) => name.endsWith(".ts"))
.map((name) => ({
name: join(directory, name),
source: readFileSync(join(apiDirectory, directory, name), "utf8"),
}));
const organizationSide = ["organization", "invitation", "need"].flatMap((tag) => [
...sourcesIn(join("schemas", tag)),
...sourcesIn(join("endpoints", tag)),
]);
const profileSide = sourcesIn(join("schemas", "candidate")).filter((file) =>
/(^|\/)(profile|candidateProfile|saveMyProfile)[^/]*\.zod\.ts$/.test(file.name),
);
// Generated object keys that only the private profile has. They are matched
// as quoted keys, because endpoint comments quote contract prose.
const profileOnly = [
'"confirmed_categories":',
'"salary_minimum":',
'"soft_skills":',
'"relocation":',
];
// Generated object keys that only organization-visible DTOs have.
const organizationOnly = [
'"verification_level":',
'"candidate_card":',
'"representatives":',
'"membership":',
];
it("finds the generated files of both sides", () => {
expect(profileSide.length).toBeGreaterThan(20);
expect(organizationSide.length).toBeGreaterThan(20);
});
it("is not reachable from an organization, invitation, or need schema or endpoint", () => {
const leaks = organizationSide.flatMap((file) =>
profileOnly
.filter((marker) => file.source.includes(marker))
.map((marker) => `${file.name}: ${marker}`),
);
expect(leaks).toEqual([]);
});
it("refers to nothing of an organization, an invitation, or a need", () => {
const leaks = profileSide.flatMap((file) =>
organizationOnly
.filter((marker) => file.source.includes(marker))
.map((marker) => `${file.name}: ${marker}`),
);
expect(leaks).toEqual([]);
});
});