feat(frontend): add need entity form model over the transport DTOs

This commit is contained in:
shira committed 2026-10-06 11:36:50 +03:00
1 parent cb2b990cd9
commit 3b917befa9
9 files changed
+1412 -2

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
// Public API of the need entity. The slice maps the generated transport DTOs
// of the need contract to a form draft and back; it holds no server state.
// Read a need with the generated query hooks, build a draft with
// fromTransport, edit it with the helpers below, and send toCreateBody or
// toUpdateBody with the generated mutations. After a successful update the
// returned Need is the new baseline of the draft.
export {
addSkill,
addTask,
clearField,
confirmField,
confirmSkill,
confirmTask,
editTask,
emptyNeedForm,
hasSkill,
moveSkill,
removeSkill,
removeTask,
renameSkill,
resetField,
setFieldValue,
} from "./model/edit";
export { fromTransport, NeedTransportError } from "./model/from-transport";
export {
changedNeedFields,
isNeedFormDirty,
NeedFormStateError,
toCreateBody,
toUpdateBody,
} from "./model/to-transport";
export type {
NeedFieldState,
NeedFormField,
NeedFormValues,
NeedProvenance,
NeedSalaryValue,
NeedScalarField,
NeedScalarValues,
NeedSkillItem,
NeedSkillList,
NeedStoredSkill,
NeedStoredTask,
NeedTaskItem,
} from "./model/types";
export {
needFormFieldOf,
validateNeedCreate,
validateNeedUpdate,
type NeedBodyValidation,
type NeedFormIssue,
} from "./model/validate";
+238
View File
@@ -0,0 +1,238 @@
import type {
NeedFieldState,
NeedFormField,
NeedFormValues,
NeedScalarField,
NeedScalarValues,
NeedSkillItem,
NeedSkillList,
NeedTaskItem,
} from "./types";
// Pure edit operations of a need draft. Each returns a new draft and keeps
// the invariants that the request mappers rely on: only an untouched stored
// suggestion is `extracted`, an edited value is `confirmed`, and an unknown
// field never gets a placeholder value.
/** Draft of a new need: an empty title, no text, and every requirement unknown. */
export function emptyNeedForm(): NeedFormValues {
return {
title: "",
vacancyId: null,
sourceText: null,
specialization: { status: "unknown" },
grade: { status: "unknown" },
requiredSkills: [],
desiredSkills: [],
tasks: [],
domain: { status: "unknown" },
workFormats: { status: "unknown" },
location: { status: "unknown" },
salary: { status: "unknown" },
};
}
function scalarState<K extends NeedScalarField>(
values: NeedFormValues,
field: K,
): NeedFieldState<NeedScalarValues[K]> {
// NeedFormValues declares each scalar field as NeedFieldState of the
// matching NeedScalarValues entry; TypeScript cannot relate the two
// indexed types for a generic key.
return values[field] as NeedFieldState<NeedScalarValues[K]>;
}
function withScalar<K extends NeedScalarField>(
values: NeedFormValues,
field: K,
state: NeedFieldState<NeedScalarValues[K]>,
): NeedFormValues {
return { ...values, [field]: state };
}
// Canonical comparison keys of scalar values: text is compared without
// surrounding whitespace and work formats as a set, as the server does.
const valueKeys: { readonly [K in NeedScalarField]: (value: NeedScalarValues[K]) => string } = {
specialization: (value) => value,
grade: (value) => value,
domain: (value) => value.trim(),
location: (value) => value.trim(),
workFormats: (value) => [...value].sort().join(","),
salary: (value) => [value.from, value.to, value.currency, value.period, value.taxBasis].join(":"),
};
function sameValue<K extends NeedScalarField>(
field: K,
left: NeedScalarValues[K],
right: NeedScalarValues[K],
): boolean {
const key = valueKeys[field];
return key(left) === key(right);
}
/** Confirms a suggestion with its stored value; the server keeps its provenance. */
export function confirmField(values: NeedFormValues, field: NeedScalarField): NeedFormValues {
const state = scalarState(values, field);
if (state.status !== "extracted") {
return values;
}
return withScalar(values, field, { ...state, status: "confirmed" });
}
/**
* Sets a value that the member entered. The field becomes confirmed. When
* the value equals the current one, the field keeps its provenance, the same
* way the server keeps the origin of a confirmed suggestion; otherwise it is
* a new manual value without provenance until the server saves it.
*/
export function setFieldValue<K extends NeedScalarField>(
values: NeedFormValues,
field: K,
value: NeedScalarValues[K],
): NeedFormValues {
const state = scalarState(values, field);
const keepsSource = state.status !== "unknown" && sameValue(field, state.value, value);
return withScalar(values, field, {
status: "confirmed",
value,
source: keepsSource ? state.source : null,
});
}
/** Removes the value: the field becomes unknown and an update sends null. */
export function clearField(values: NeedFormValues, field: NeedScalarField): NeedFormValues {
return withScalar(values, field, { status: "unknown" });
}
/** Restores one field to its state in `baseline`, usually fromTransport of the read need. */
export function resetField(
values: NeedFormValues,
baseline: NeedFormValues,
field: NeedFormField,
): NeedFormValues {
return { ...values, [field]: baseline[field] };
}
function replaceAt<T>(items: readonly T[], index: number, item: T): readonly T[] {
return items.map((current, position) => (position === index ? item : current));
}
function removeAt<T>(items: readonly T[], index: number): readonly T[] {
return items.filter((_item, position) => position !== index);
}
/** True when either skill list has the name; the server compares names without regard to case. */
export function hasSkill(values: NeedFormValues, name: string): boolean {
const key = name.trim().toLowerCase();
return [...values.requiredSkills, ...values.desiredSkills].some(
(skill) => skill.name.trim().toLowerCase() === key,
);
}
/** Confirms one suggested skill and keeps its stored taxonomy code and provenance. */
export function confirmSkill(
values: NeedFormValues,
list: NeedSkillList,
index: number,
): NeedFormValues {
const item = values[list][index];
if (item === undefined || item.status !== "extracted") {
return values;
}
return { ...values, [list]: replaceAt(values[list], index, { ...item, status: "confirmed" }) };
}
/**
* Adds a confirmed manual skill to the end of a list. A name already present
* in either list leaves the draft unchanged, because the server rejects a
* repeated skill; check hasSkill to tell the member.
*/
export function addSkill(
values: NeedFormValues,
list: NeedSkillList,
name: string,
): NeedFormValues {
if (hasSkill(values, name)) {
return values;
}
const item: NeedSkillItem = { status: "confirmed", name, stored: null };
return { ...values, [list]: [...values[list], item] };
}
/**
* Renames a skill. A different name is a new manual skill, so it is
* confirmed and loses the stored taxonomy code and provenance; the same name
* leaves the skill unchanged.
*/
export function renameSkill(
values: NeedFormValues,
list: NeedSkillList,
index: number,
name: string,
): NeedFormValues {
const item = values[list][index];
if (item === undefined || item.name === name) {
return values;
}
const renamed: NeedSkillItem = { status: "confirmed", name, stored: null };
return { ...values, [list]: replaceAt(values[list], index, renamed) };
}
export function removeSkill(
values: NeedFormValues,
list: NeedSkillList,
index: number,
): NeedFormValues {
return { ...values, [list]: removeAt(values[list], index) };
}
/**
* Moves a skill to the end of the other list. The skill keeps its status:
* moving a suggestion between required and desired skills does not confirm
* it.
*/
export function moveSkill(
values: NeedFormValues,
from: NeedSkillList,
index: number,
): NeedFormValues {
const item = values[from][index];
if (item === undefined) {
return values;
}
const to: NeedSkillList = from === "requiredSkills" ? "desiredSkills" : "requiredSkills";
return {
...values,
[from]: removeAt(values[from], index),
[to]: [...values[to], item],
};
}
/** Confirms one suggested task and keeps its provenance. */
export function confirmTask(values: NeedFormValues, index: number): NeedFormValues {
const item = values.tasks[index];
if (item === undefined || item.status !== "extracted") {
return values;
}
return { ...values, tasks: replaceAt(values.tasks, index, { ...item, status: "confirmed" }) };
}
/** Adds a confirmed manual task to the end of the list. */
export function addTask(values: NeedFormValues, text: string): NeedFormValues {
const item: NeedTaskItem = { status: "confirmed", text, stored: null };
return { ...values, tasks: [...values.tasks, item] };
}
/** Edits a task text; a different text is a new confirmed manual task. */
export function editTask(values: NeedFormValues, index: number, text: string): NeedFormValues {
const item = values.tasks[index];
if (item === undefined || item.text === text) {
return values;
}
const edited: NeedTaskItem = { status: "confirmed", text, stored: null };
return { ...values, tasks: replaceAt(values.tasks, index, edited) };
}
export function removeTask(values: NeedFormValues, index: number): NeedFormValues {
return { ...values, tasks: removeAt(values.tasks, index) };
}
@@ -0,0 +1,126 @@
import type {
Need,
NeedSkill,
NeedTask,
NeedValueSource,
NeedValueStatus,
SalaryRange,
} from "../../../shared/api/schemas";
import type {
NeedFieldState,
NeedFormValues,
NeedProvenance,
NeedSalaryValue,
NeedSkillItem,
NeedTaskItem,
} from "./types";
/**
* Thrown when a Need breaks a contract rule that its Zod schema cannot
* express: `value` and `source` are null exactly when `status` is `unknown`.
* The mapper refuses such data instead of inventing a value or dropping one.
*/
export class NeedTransportError extends Error {
readonly field: string;
constructor(field: string, detail: string) {
super(`Need field ${field} breaks the contract: ${detail}`);
this.name = "NeedTransportError";
this.field = field;
}
}
interface TransportField<T> {
readonly status: NeedValueStatus;
readonly value: T | null;
readonly source: NeedValueSource | null;
}
function provenanceFromTransport(source: NeedValueSource): NeedProvenance {
return {
origin: source.origin,
quote: source.quote,
extractedInVersion: source.extracted_in_version,
extractionVersion: source.extraction_version,
};
}
function fieldFromTransport<T, U>(
name: string,
field: TransportField<T>,
map: (value: T) => U,
): NeedFieldState<U> {
if (field.status === "unknown") {
if (field.value !== null || field.source !== null) {
throw new NeedTransportError(name, "an unknown field has a value or a source");
}
return { status: "unknown" };
}
if (field.value === null || field.source === null) {
throw new NeedTransportError(name, `a ${field.status} field has no value or no source`);
}
return {
status: field.status,
value: map(field.value),
source: provenanceFromTransport(field.source),
};
}
function salaryFromTransport(range: SalaryRange): NeedSalaryValue {
return {
from: range.salary_from,
to: range.salary_to,
currency: range.currency,
period: range.period,
taxBasis: range.tax_basis,
};
}
function skillFromTransport(skill: NeedSkill): NeedSkillItem {
return {
status: skill.status,
name: skill.name,
stored: {
taxonomyCode: skill.taxonomy_code,
source: provenanceFromTransport(skill.source),
},
};
}
function taskFromTransport(task: NeedTask): NeedTaskItem {
return {
status: task.status,
text: task.text,
stored: { source: provenanceFromTransport(task.source) },
};
}
function identity<T>(value: T): T {
return value;
}
/**
* Builds the form draft of a need read from the server. Every field keeps its
* status, value, and provenance: an unknown field stays unknown, a
* suggestion stays a suggestion with its quote, and a skill outside the
* taxonomy keeps its null taxonomy code.
*/
export function fromTransport(need: Need): NeedFormValues {
const requirements = need.requirements;
return {
title: need.title,
vacancyId: need.vacancy_id,
sourceText: need.source_text,
specialization: fieldFromTransport("specialization", requirements.specialization, identity),
grade: fieldFromTransport("grade", requirements.grade, identity),
requiredSkills: requirements.required_skills.map(skillFromTransport),
desiredSkills: requirements.desired_skills.map(skillFromTransport),
tasks: requirements.tasks.map(taskFromTransport),
domain: fieldFromTransport("domain", requirements.domain, identity),
workFormats: fieldFromTransport("work_formats", requirements.work_formats, (formats) => [
...formats,
]),
location: fieldFromTransport("location", requirements.location, identity),
salary: fieldFromTransport("salary", requirements.salary, salaryFromTransport),
};
}
@@ -0,0 +1,530 @@
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { describe, expect, expectTypeOf, it } from "vitest";
import { parse as parseYaml } from "yaml";
import {
createOrganizationNeed,
updateOrganizationNeed,
} from "../../../shared/api/endpoints/need/need";
import {
CreateOrganizationNeedBody,
Need,
NeedCreate,
NeedUpdate,
UpdateOrganizationNeedBody,
} from "../../../shared/api/schemas";
import {
addSkill,
addTask,
clearField,
confirmField,
confirmSkill,
emptyNeedForm,
hasSkill,
moveSkill,
removeSkill,
removeTask,
renameSkill,
resetField,
setFieldValue,
} from "./edit";
import { fromTransport, NeedTransportError } from "./from-transport";
import {
changedNeedFields,
isNeedFormDirty,
NeedFormStateError,
toCreateBody,
toUpdateBody,
} from "./to-transport";
import type {
NeedFieldState,
NeedFormValues,
NeedSkillItem,
NeedStoredSkill,
NeedTaskItem,
} from "./types";
import { needFormFieldOf, validateNeedCreate, validateNeedUpdate } from "./validate";
// The fixtures are the named examples of the need contract (TASK-177), read
// from the same bundled OpenAPI document that Orval generates the client
// from, so the tests follow the contract instead of a hand-made copy.
type ExampleMap = Record<string, { value?: unknown } | undefined>;
const bundlePath = fileURLToPath(
new URL("../../../../../api/core/openapi.bundle.yml", import.meta.url),
);
const examples = (
parseYaml(readFileSync(bundlePath, "utf8")) as { components: { examples: ExampleMap } }
).components.examples;
function example(name: string): unknown {
const value = examples[name]?.value;
if (value === undefined) {
throw new Error(`The need contract has no example ${name}.`);
}
return value;
}
const extractedNeed: Need = Need.parse(example("NeedExtractedWithUnknownSkill"));
const confirmedNeed: Need = Need.parse(example("NeedConfirmedAfterUpdate"));
const manualNeed: Need = Need.parse(example("NeedManualWithoutVacancy"));
const confirmSuggestions = NeedUpdate.parse(example("NeedUpdateConfirmSuggestions"));
const createManual = NeedCreate.parse(example("NeedCreateManual"));
const createFromText = NeedCreate.parse(example("NeedCreateFromText"));
const temporalQuote = "Обязательно: Go, PostgreSQL и Temporal";
function expectValidUpdate(body: NeedUpdate): NeedUpdate {
expect(NeedUpdate.safeParse(body).error?.issues).toBeUndefined();
expect(UpdateOrganizationNeedBody.safeParse(body).success).toBe(true);
return body;
}
function expectValidCreate(body: NeedCreate): NeedCreate {
expect(NeedCreate.safeParse(body).error?.issues).toBeUndefined();
expect(CreateOrganizationNeedBody.safeParse(body).success).toBe(true);
return body;
}
function skillIndex(
values: NeedFormValues,
list: "requiredSkills" | "desiredSkills",
name: string,
) {
const index = values[list].findIndex((skill) => skill.name === name);
expect(index).toBeGreaterThanOrEqual(0);
return index;
}
function confirmRequiredSkill(values: NeedFormValues, name: string): NeedFormValues {
return confirmSkill(values, "requiredSkills", skillIndex(values, "requiredSkills", name));
}
function statusOf<T>(state: NeedFieldState<T>) {
return state.status === "unknown"
? { status: state.status }
: { status: state.status, value: state.value };
}
// Status and value of every requirement, without provenance, to compare a
// draft with the need the server returns for it.
function decisionsOf(values: NeedFormValues) {
return {
specialization: statusOf(values.specialization),
grade: statusOf(values.grade),
requiredSkills: values.requiredSkills.map(({ name, status }) => ({ name, status })),
desiredSkills: values.desiredSkills.map(({ name, status }) => ({ name, status })),
tasks: values.tasks.map(({ text, status }) => ({ text, status })),
domain: statusOf(values.domain),
workFormats: statusOf(values.workFormats),
location: statusOf(values.location),
salary: statusOf(values.salary),
};
}
describe("fromTransport", () => {
const form = fromTransport(extractedNeed);
it("keeps unknown fields unknown instead of empty or default values", () => {
for (const field of [form.grade, form.location, form.salary]) {
expect(field).toEqual({ status: "unknown" });
expect(field).not.toHaveProperty("value");
}
expect(form.vacancyId).toBeNull();
});
it("keeps a suggestion with its origin, quote, and versions", () => {
expect(form.specialization).toEqual({
status: "extracted",
value: "backend",
source: {
origin: "extracted_from_text",
quote: "Ищем бэкенд-разработчика",
extractedInVersion: 1,
extractionVersion: "need-rules.2026-10.1",
},
});
expect(form.workFormats).toMatchObject({ status: "extracted", value: ["remote"] });
expect(form.sourceText).toBe(extractedNeed.source_text);
});
it("keeps a skill outside the taxonomy as an unconfirmed suggestion with its quote", () => {
const temporal = form.requiredSkills.find((skill) => skill.name === "Temporal");
expect(temporal).toEqual({
status: "extracted",
name: "Temporal",
stored: {
taxonomyCode: null,
source: {
origin: "extracted_from_text",
quote: temporalQuote,
extractedInVersion: 1,
extractionVersion: "need-rules.2026-10.1",
},
},
});
expect(form.desiredSkills).toEqual([
expect.objectContaining({ name: "Kafka", status: "extracted" }),
]);
});
it("keeps the provenance of confirmed suggestions and of manual values", () => {
const confirmed = fromTransport(confirmedNeed);
expect(confirmed.requiredSkills.find((skill) => skill.name === "Temporal")).toEqual({
status: "confirmed",
name: "Temporal",
stored: expect.objectContaining({
taxonomyCode: null,
source: expect.objectContaining({ origin: "extracted_from_text", quote: temporalQuote }),
}),
});
expect(confirmed.grade).toEqual({
status: "confirmed",
value: "middle",
source: {
origin: "manual",
quote: null,
extractedInVersion: null,
extractionVersion: null,
},
});
});
it.each([
["an unknown field with a value", { status: "unknown", value: "middle", source: null }],
["a suggestion without a source", { status: "extracted", value: "middle", source: null }],
["a confirmed field without a value", { status: "confirmed", value: null, source: null }],
] as const)("refuses %s instead of guessing", (_case, grade) => {
const broken = { ...extractedNeed, requirements: { ...extractedNeed.requirements, grade } };
expect(() => fromTransport(broken)).toThrow(NeedTransportError);
});
});
describe("toUpdateBody", () => {
it.each([
["NeedExtractedWithUnknownSkill", extractedNeed],
["NeedConfirmedAfterUpdate", confirmedNeed],
["NeedManualWithoutVacancy", manualNeed],
])("sends only the expected version for an untouched %s", (_name, need) => {
const form = fromTransport(need);
expect(expectValidUpdate(toUpdateBody(need, form))).toEqual({
expected_version: need.version,
});
expect(isNeedFormDirty(need, form)).toBe(false);
});
it("reproduces the contract confirmation without confirming the untouched suggestions", () => {
let form = fromTransport(extractedNeed);
form = confirmField(form, "specialization");
form = setFieldValue(form, "grade", "middle");
for (const name of ["Go", "PostgreSQL", "Temporal"]) {
form = confirmRequiredSkill(form, name);
}
form = confirmField(form, "workFormats");
form = setFieldValue(form, "salary", {
from: 250000,
to: 320000,
currency: "RUB",
period: "month",
taxBasis: "gross",
});
const body = expectValidUpdate(toUpdateBody(extractedNeed, form));
// The contract example also sends Kafka and the domain back with status
// extracted; leaving untouched suggestions out is the equivalent the
// contract allows, so neither can be confirmed by accident.
const { desired_skills: keptKafka, domain: keptDomain, ...touched } = confirmSuggestions;
expect(keptKafka).toEqual([{ name: "Kafka", status: "extracted" }]);
expect(keptDomain).toEqual({ value: "платежи", status: "extracted" });
expect(body).toEqual(touched);
expect(changedNeedFields(extractedNeed, form)).toEqual([
"specialization",
"grade",
"requiredSkills",
"workFormats",
"salary",
]);
// The draft predicts the version the server returns for this body.
expect(decisionsOf(form)).toEqual(decisionsOf(fromTransport(confirmedNeed)));
});
it("never writes an unconfirmed skill into required skills as confirmed", () => {
const form = confirmRequiredSkill(fromTransport(extractedNeed), "Go");
const body = expectValidUpdate(toUpdateBody(extractedNeed, form));
expect(body.required_skills).toEqual([
{ name: "Go", status: "confirmed" },
{ name: "PostgreSQL", status: "extracted" },
{ name: "Temporal", status: "extracted" },
]);
expect(body).not.toHaveProperty("desired_skills");
expect(body).not.toHaveProperty("grade");
expect(body).not.toHaveProperty("location");
expect(body).not.toHaveProperty("salary");
expect(body).not.toHaveProperty("domain");
expect(body).not.toHaveProperty("tasks");
});
it("keeps a moved suggestion unconfirmed in the required list", () => {
const original = fromTransport(extractedNeed);
const form = moveSkill(
original,
"desiredSkills",
skillIndex(original, "desiredSkills", "Kafka"),
);
const body = expectValidUpdate(toUpdateBody(extractedNeed, form));
expect(body.required_skills).toContainEqual({ name: "Kafka", status: "extracted" });
expect(body.required_skills?.filter((skill) => skill.status === "confirmed")).toEqual([]);
expect(body.desired_skills).toEqual([]);
});
it("keeps the other suggestions of a list open when a manual skill is added", () => {
const form = addSkill(fromTransport(extractedNeed), "desiredSkills", "Docker");
expect(expectValidUpdate(toUpdateBody(extractedNeed, form))).toEqual({
expected_version: 1,
desired_skills: [
{ name: "Kafka", status: "extracted" },
{ name: "Docker", status: "confirmed" },
],
});
});
it("sends a list without the removed item and leaves untouched lists out", () => {
const original = fromTransport(extractedNeed);
const form = removeSkill(
original,
"requiredSkills",
skillIndex(original, "requiredSkills", "Temporal"),
);
expect(expectValidUpdate(toUpdateBody(extractedNeed, form))).toEqual({
expected_version: 1,
required_skills: [
{ name: "Go", status: "extracted" },
{ name: "PostgreSQL", status: "extracted" },
],
});
});
it("sends an emptied list as an empty list and a cleared field as null", () => {
let form = removeTask(fromTransport(extractedNeed), 0);
form = clearField(form, "domain");
expect(expectValidUpdate(toUpdateBody(extractedNeed, form))).toEqual({
expected_version: 1,
tasks: [],
domain: null,
});
});
it("leaves a field out once the member resets it", () => {
const original = fromTransport(extractedNeed);
const form = resetField(confirmField(original, "domain"), original, "domain");
expect(toUpdateBody(extractedNeed, form)).toEqual({ expected_version: 1 });
});
it("confirms a suggestion and keeps its provenance when the member types the same value", () => {
const form = setFieldValue(fromTransport(extractedNeed), "domain", "платежи");
expect(form.domain).toMatchObject({
status: "confirmed",
source: { origin: "extracted_from_text", quote: "в команду платежей" },
});
expect(expectValidUpdate(toUpdateBody(extractedNeed, form)).domain).toEqual({
value: "платежи",
status: "confirmed",
});
});
it("turns an edited suggestion into a confirmed manual value", () => {
const original = fromTransport(extractedNeed);
const form = renameSkill(
original,
"requiredSkills",
skillIndex(original, "requiredSkills", "Temporal"),
"Temporal.io",
);
expect(form.requiredSkills[2]).toEqual({
status: "confirmed",
name: "Temporal.io",
stored: null,
});
expect(expectValidUpdate(toUpdateBody(extractedNeed, form)).required_skills).toEqual([
{ name: "Go", status: "extracted" },
{ name: "PostgreSQL", status: "extracted" },
{ name: "Temporal.io", status: "confirmed" },
]);
});
it("does not treat surrounding spaces or a reordering of work formats as a change", () => {
const need: Need = {
...manualNeed,
requirements: {
...manualNeed.requirements,
work_formats: { ...manualNeed.requirements.work_formats, value: ["office", "hybrid"] },
},
};
let form = setFieldValue(fromTransport(need), "location", " Москва ");
form = setFieldValue(form, "workFormats", ["hybrid", "office"]);
expect(form.workFormats).toMatchObject({ source: { origin: "manual" } });
expect(toUpdateBody(need, form)).toEqual({ expected_version: 1 });
});
it("refuses a suggestion whose value no longer matches the stored one", () => {
const form = fromTransport(extractedNeed);
const domain = form.domain;
if (domain.status !== "extracted") {
throw new Error("The fixture domain must be a suggestion.");
}
const tampered: NeedFormValues = { ...form, domain: { ...domain, value: "логистика" } };
expect(() => toUpdateBody(extractedNeed, tampered)).toThrow(NeedFormStateError);
});
it("refuses an extracted skill that is not a stored suggestion", () => {
const form = fromTransport(extractedNeed);
const temporal = form.requiredSkills[2];
if (temporal?.status !== "extracted") {
throw new Error("The fixture Temporal skill must be a suggestion.");
}
const invented: NeedSkillItem = { ...temporal, name: "Cadence" };
const tampered: NeedFormValues = {
...form,
requiredSkills: [...form.requiredSkills, invented],
};
expect(() => toUpdateBody(extractedNeed, tampered)).toThrow(NeedFormStateError);
});
});
describe("toCreateBody", () => {
function manualDraft(): NeedFormValues {
let form: NeedFormValues = { ...emptyNeedForm(), title: createManual.title };
form = setFieldValue(form, "specialization", "backend");
form = setFieldValue(form, "grade", "junior");
form = addSkill(form, "requiredSkills", "Go");
form = addSkill(form, "requiredSkills", "PostgreSQL");
form = addSkill(form, "desiredSkills", "Docker");
form = addTask(form, "Поддерживать и развивать сервис уведомлений");
form = setFieldValue(form, "workFormats", ["hybrid"]);
form = setFieldValue(form, "location", "Москва");
return setFieldValue(form, "salary", {
from: 120000,
to: 160000,
currency: "RUB",
period: "month",
taxBasis: "net",
});
}
it("builds the contract manual example and leaves the unknown domain out", () => {
const body = expectValidCreate(toCreateBody(manualDraft()));
expect(body).toEqual(createManual);
expect(body).not.toHaveProperty("domain");
expect(body).not.toHaveProperty("vacancy_id");
});
it("round-trips the created need back to the same create body", () => {
const form = fromTransport(manualNeed);
expect(decisionsOf(form)).toEqual(decisionsOf(manualDraft()));
expect(expectValidCreate(toCreateBody(form))).toEqual(createManual);
});
it("sends only the title and the text so the server extracts the rest", () => {
const form: NeedFormValues = {
...emptyNeedForm(),
title: ` ${createFromText.title} `,
sourceText: createFromText.source_text ?? null,
};
expect(expectValidCreate(toCreateBody(form))).toEqual(createFromText);
});
it("refuses to create a need from stored suggestions", () => {
expect(() => toCreateBody(fromTransport(extractedNeed))).toThrow(NeedFormStateError);
});
it("does not add a skill that either list already has", () => {
const form = addSkill(emptyNeedForm(), "requiredSkills", "Go");
expect(hasSkill(form, " go ")).toBe(true);
expect(addSkill(form, "desiredSkills", "GO")).toBe(form);
});
});
describe("validation", () => {
it("reports generated schema problems on the form field", () => {
const result = validateNeedCreate(addSkill(emptyNeedForm(), "requiredSkills", "Go\nRust"));
expect(result.success).toBe(false);
if (!result.success) {
expect(new Set(result.issues.map((issue) => issue.field))).toEqual(
new Set(["title", "requiredSkills"]),
);
expect(result.issues).toContainEqual(
expect.objectContaining({ path: ["required_skills", 0, "name"] }),
);
}
});
it("accepts an update body that the generated schema accepts", () => {
const form = confirmRequiredSkill(fromTransport(extractedNeed), "Temporal");
const result = validateNeedUpdate(extractedNeed, form);
expect(result).toEqual({
success: true,
body: {
expected_version: 1,
required_skills: [
{ name: "Go", status: "extracted" },
{ name: "PostgreSQL", status: "extracted" },
{ name: "Temporal", status: "confirmed" },
],
},
});
});
it.each([
["/required_skills/2/status", "requiredSkills"],
["/salary/value/salary_to", "salary"],
["/work_formats/value", "workFormats"],
["/vacancy_id", "vacancyId"],
["/expected_version", null],
["", null],
] as const)("maps the problem pointer %s to a form field", (pointer, field) => {
expect(needFormFieldOf(pointer)).toBe(field);
});
});
it("keeps the form model apart from the transport DTOs", () => {
expectTypeOf(toCreateBody).returns.toEqualTypeOf<Parameters<typeof createOrganizationNeed>[1]>();
expectTypeOf(toUpdateBody).returns.toEqualTypeOf<Parameters<typeof updateOrganizationNeed>[2]>();
expectTypeOf(fromTransport).parameter(0).toEqualTypeOf<Need>();
// A draft cannot be sent as a request body by mistake.
expectTypeOf<NeedFormValues>().not.toExtend<NeedCreate>();
expectTypeOf<NeedFormValues>().not.toExtend<NeedUpdate>();
// An unknown field has no value to collapse into an empty string or list.
expectTypeOf<Extract<NeedFieldState<string>, { status: "unknown" }>>().toEqualTypeOf<{
readonly status: "unknown";
}>();
// A suggestion always carries the stored data it came from.
expectTypeOf<
Extract<NeedSkillItem, { status: "extracted" }>["stored"]
>().toEqualTypeOf<NeedStoredSkill>();
expectTypeOf<Extract<NeedTaskItem, { status: "extracted" }>["stored"]>().not.toBeNullable();
});
@@ -0,0 +1,259 @@
import {
WorkFormat,
type Need,
type NeedCreate,
type NeedItemStatus,
type NeedUpdate,
type SalaryRange,
} from "../../../shared/api/schemas";
import { emptyNeedForm } from "./edit";
import { fromTransport } from "./from-transport";
import type {
NeedFieldState,
NeedFormField,
NeedFormValues,
NeedSalaryValue,
NeedScalarField,
NeedSkillItem,
NeedTaskItem,
} from "./types";
/**
* Thrown when a draft holds a state that no request may send, such as a
* suggestion whose value no longer equals the stored one. The edit helpers
* of this slice never produce such a state; the error reports a programming
* mistake instead of letting the server answer 400 or, worse, letting the
* client confirm a value nobody confirmed.
*/
export class NeedFormStateError extends Error {
readonly field: NeedFormField;
constructor(field: NeedFormField, detail: string) {
super(`Need form field ${field} cannot be sent: ${detail}`);
this.name = "NeedFormStateError";
this.field = field;
}
}
/** Every request field of a need with the value the draft would send. */
type NeedRequestProjection = {
[K in Exclude<keyof NeedUpdate, "expected_version">]-?: Exclude<NeedUpdate[K], undefined>;
};
type NeedRequestKey = keyof NeedRequestProjection;
/** Request field name of each form field, in the order of the contract. */
export const needRequestKeyOfField = {
title: "title",
vacancyId: "vacancy_id",
sourceText: "source_text",
specialization: "specialization",
grade: "grade",
requiredSkills: "required_skills",
desiredSkills: "desired_skills",
tasks: "tasks",
domain: "domain",
workFormats: "work_formats",
location: "location",
salary: "salary",
} as const satisfies { readonly [F in NeedFormField]: NeedRequestKey };
const formFields = Object.keys(needRequestKeyOfField) as readonly NeedFormField[];
// Request formats are compared as a set, so the draft sends them in the
// order of the contract enum and a reordering is not a change.
const workFormatOrder: readonly string[] = WorkFormat.options;
function normalizeLine(text: string): string {
return text.trim();
}
function normalizeSourceText(text: string | null): string | null {
return text === null || text.trim() === "" ? null : text;
}
function decision<T, U>(
state: NeedFieldState<T>,
map: (value: T) => U,
): { value: U; status: NeedItemStatus } | null {
return state.status === "unknown" ? null : { value: map(state.value), status: state.status };
}
function salaryToTransport(salary: NeedSalaryValue): SalaryRange {
return {
salary_from: salary.from,
salary_to: salary.to,
currency: salary.currency,
period: salary.period,
tax_basis: salary.taxBasis,
};
}
function skillsToTransport(items: readonly NeedSkillItem[]) {
return items.map((item) => ({ name: normalizeLine(item.name), status: item.status }));
}
function tasksToTransport(items: readonly NeedTaskItem[]) {
return items.map((item) => ({ text: normalizeLine(item.text), status: item.status }));
}
function project(values: NeedFormValues): NeedRequestProjection {
return {
title: normalizeLine(values.title),
vacancy_id: values.vacancyId,
source_text: normalizeSourceText(values.sourceText),
specialization: decision(values.specialization, (value) => value),
grade: decision(values.grade, (value) => value),
required_skills: skillsToTransport(values.requiredSkills),
desired_skills: skillsToTransport(values.desiredSkills),
tasks: tasksToTransport(values.tasks),
domain: decision(values.domain, normalizeLine),
work_formats: decision(values.workFormats, (formats) =>
[...formats].sort((a, b) => workFormatOrder.indexOf(a) - workFormatOrder.indexOf(b)),
),
location: decision(values.location, normalizeLine),
salary: decision(values.salary, salaryToTransport),
};
}
function sameProjection<K extends NeedRequestKey>(
key: K,
left: NeedRequestProjection,
right: NeedRequestProjection,
): boolean {
// Projections hold only JSON data built in a fixed key order.
return JSON.stringify(left[key]) === JSON.stringify(right[key]);
}
function copyField<K extends NeedRequestKey>(
target: Partial<NeedRequestProjection>,
source: NeedRequestProjection,
key: K,
): void {
target[key] = source[key];
}
function changedFormFields(
baseline: NeedRequestProjection,
current: NeedRequestProjection,
): NeedFormField[] {
return formFields.filter(
(field) => !sameProjection(needRequestKeyOfField[field], baseline, current),
);
}
function pick(
projection: NeedRequestProjection,
fields: readonly NeedFormField[],
): Partial<NeedRequestProjection> {
const body: Partial<NeedRequestProjection> = {};
for (const field of fields) {
copyField(body, projection, needRequestKeyOfField[field]);
}
return body;
}
const scalarFields = [
"specialization",
"grade",
"domain",
"workFormats",
"location",
"salary",
] as const satisfies readonly NeedScalarField[];
function storedSuggestions(baseline: NeedFormValues | null) {
const skills = new Set<string>();
const tasks = new Set<string>();
if (baseline !== null) {
// A skill name refers to a stored skill of either list without regard
// to letter case; a task text must match exactly.
for (const skill of [...baseline.requiredSkills, ...baseline.desiredSkills]) {
if (skill.status === "extracted") {
skills.add(skill.name.toLowerCase());
}
}
for (const task of baseline.tasks) {
if (task.status === "extracted") {
tasks.add(task.text);
}
}
}
return { skills, tasks };
}
// A request may send `extracted` only to keep a stored suggestion open with
// exactly its stored value. Every changed field is checked against the
// baseline; a create has no baseline, so it may not send `extracted` at all.
function assertSendable(
values: NeedFormValues,
baseline: NeedFormValues | null,
fields: readonly NeedFormField[],
): void {
const suggestions = storedSuggestions(baseline);
for (const field of scalarFields) {
if (fields.includes(field) && values[field].status === "extracted") {
throw new NeedFormStateError(field, "a changed value is still marked extracted");
}
}
for (const list of ["requiredSkills", "desiredSkills"] as const) {
if (!fields.includes(list)) {
continue;
}
for (const item of values[list]) {
if (item.status === "extracted" && !suggestions.skills.has(item.name.toLowerCase())) {
throw new NeedFormStateError(list, `skill ${item.name} is not a stored suggestion`);
}
}
}
if (fields.includes("tasks")) {
for (const item of values.tasks) {
if (item.status === "extracted" && !suggestions.tasks.has(item.text)) {
throw new NeedFormStateError("tasks", "a task is not a stored suggestion");
}
}
}
}
/**
* Builds the NeedCreate body of a new draft. Only the title is always sent.
* An unknown field and an empty list are left out, so the server extracts
* them from `source_text` when a text is given and leaves them unknown or
* empty otherwise. A new need has no stored suggestion, so every sent
* decision is `confirmed`.
*/
export function toCreateBody(values: NeedFormValues): NeedCreate {
const current = project(values);
const fields = changedFormFields(project(emptyNeedForm()), current).filter(
(field) => field !== "title",
);
assertSendable(values, null, fields);
return { ...pick(current, fields), title: current.title };
}
/** Form fields whose request value differs from the need the draft started from. */
export function changedNeedFields(original: Need, values: NeedFormValues): NeedFormField[] {
return changedFormFields(project(fromTransport(original)), project(values));
}
/** True when saving the draft would change the need. */
export function isNeedFormDirty(original: Need, values: NeedFormValues): boolean {
return changedNeedFields(original, values).length > 0;
}
/**
* Builds the NeedUpdate body of a draft over the need version it was read
* from. Only fields whose request value changed are sent; an absent field
* stays unchanged on the server. An untouched suggestion is therefore never
* sent, and when its list or field is sent for another reason it keeps the
* status `extracted`, so the client confirms nothing by accident. A field
* cleared to unknown is sent as null, and a list emptied by the member is
* sent as an empty list. `expected_version` is the version of `original`.
*/
export function toUpdateBody(original: Need, values: NeedFormValues): NeedUpdate {
const baseline = fromTransport(original);
const current = project(values);
const fields = changedFormFields(project(baseline), current);
assertSendable(values, baseline, fields);
return { expected_version: original.version, ...pick(current, fields) };
}
+117
View File
@@ -0,0 +1,117 @@
import type {
CurrencyCode,
GradeCode,
NeedValueOrigin,
SalaryPeriod,
SalaryTaxBasis,
SpecializationCode,
WorkFormat,
} from "../../../shared/api/schemas";
// The form model of an employer need. It is a client view of the generated
// transport DTOs (Need, NeedCreate, NeedUpdate) and never travels over the
// wire itself: the mappers in this slice convert it in both directions.
// Server data stays in the TanStack Query cache; this model only describes a
// draft that a form edits.
/** Provenance of a stored value as the server reported it. Read-only. */
export interface NeedProvenance {
readonly origin: NeedValueOrigin;
/** Excerpt of the need text, or null when the server tied no excerpt. */
readonly quote: string | null;
/** Need version whose text the quote belongs to; null for a manual value. */
readonly extractedInVersion: number | null;
/** Extractor version; null for a manual value. */
readonly extractionVersion: string | null;
}
/**
* State of one requirement field. Each state is explicit: an unknown field
* has no value at all, so it is never represented by an empty string, an
* empty list, or a default such as a grade or a work format.
*
* - unknown: the field has no value.
* - extracted: a stored suggestion that nobody confirmed. It always carries
* its provenance and exactly the stored value; editing the value turns the
* field into a confirmed one.
* - confirmed: a value that a member entered or confirmed. `source` is null
* only for a value entered in this draft that the server has not saved
* yet, so it has no provenance yet.
*/
export type NeedFieldState<T> =
| { readonly status: "unknown" }
| { readonly status: "extracted"; readonly value: T; readonly source: NeedProvenance }
| { readonly status: "confirmed"; readonly value: T; readonly source: NeedProvenance | null };
/** Salary range of the form, the client view of SalaryRange. */
export interface NeedSalaryValue {
readonly from: number;
readonly to: number;
readonly currency: CurrencyCode;
readonly period: SalaryPeriod;
readonly taxBasis: SalaryTaxBasis;
}
/** Server data of a stored skill. */
export interface NeedStoredSkill {
/** Taxonomy code, or null when the platform taxonomy does not know the skill. */
readonly taxonomyCode: string | null;
readonly source: NeedProvenance;
}
/**
* One skill of a list. `stored` is null only for a skill added or renamed in
* this draft; such a skill is always confirmed, because a request may send
* `extracted` only for a stored suggestion.
*/
export type NeedSkillItem =
| { readonly status: "extracted"; readonly name: string; readonly stored: NeedStoredSkill }
| {
readonly status: "confirmed";
readonly name: string;
readonly stored: NeedStoredSkill | null;
};
/** Server data of a stored task. */
export interface NeedStoredTask {
readonly source: NeedProvenance;
}
/** One task of the list; `stored` follows the rule of NeedSkillItem. */
export type NeedTaskItem =
| { readonly status: "extracted"; readonly text: string; readonly stored: NeedStoredTask }
| { readonly status: "confirmed"; readonly text: string; readonly stored: NeedStoredTask | null };
/** Value types of the single-value requirement fields. */
export interface NeedScalarValues {
readonly specialization: SpecializationCode;
readonly grade: GradeCode;
readonly domain: string;
readonly workFormats: readonly WorkFormat[];
readonly location: string;
readonly salary: NeedSalaryValue;
}
export type NeedScalarField = keyof NeedScalarValues;
export type NeedSkillList = "requiredSkills" | "desiredSkills";
/** Draft of a need that a form edits. */
export interface NeedFormValues {
readonly title: string;
/** Linked vacancy, or null for a need without a vacancy. */
readonly vacancyId: string | null;
/** Need text, or null when the need has none. */
readonly sourceText: string | null;
readonly specialization: NeedFieldState<SpecializationCode>;
readonly grade: NeedFieldState<GradeCode>;
readonly requiredSkills: readonly NeedSkillItem[];
readonly desiredSkills: readonly NeedSkillItem[];
readonly tasks: readonly NeedTaskItem[];
readonly domain: NeedFieldState<string>;
readonly workFormats: NeedFieldState<readonly WorkFormat[]>;
readonly location: NeedFieldState<string>;
readonly salary: NeedFieldState<NeedSalaryValue>;
}
export type NeedFormField = keyof NeedFormValues;
@@ -0,0 +1,63 @@
import type { ZodType } from "zod";
import { NeedCreate, NeedUpdate, type Need } from "../../../shared/api/schemas";
import { needRequestKeyOfField, toCreateBody, toUpdateBody } from "./to-transport";
import type { NeedFormField, NeedFormValues } from "./types";
// Validation reuses the generated Zod request schemas, so the form checks
// exactly the per-field limits of the contract. Cross-field rules, such as
// the salary width or a skill repeated across lists, stay with the server,
// which answers 400 with a JSON pointer that needFormFieldOf maps back.
/** One validation problem of a request body, tied to the form field when it has one. */
export interface NeedFormIssue {
/** Form field, or null for a problem of the whole body. */
readonly field: NeedFormField | null;
/** Path inside the request body, for example ["required_skills", 2, "name"]. */
readonly path: readonly PropertyKey[];
readonly message: string;
}
export type NeedBodyValidation<Body> =
| { readonly success: true; readonly body: Body }
| { readonly success: false; readonly body: Body; readonly issues: readonly NeedFormIssue[] };
const fieldOfRequestKey = new Map<PropertyKey, NeedFormField>(
Object.entries(needRequestKeyOfField).map(([field, key]) => [key, field as NeedFormField]),
);
/**
* Maps a request location to its form field: a Zod issue path such as
* ["salary", "value", "salary_to"] or a problem pointer such as
* "/required_skills/2/status". Returns null for the whole body and for
* `expected_version`.
*/
export function needFormFieldOf(location: string | readonly PropertyKey[]): NeedFormField | null {
const head = typeof location === "string" ? location.split("/")[1] : location[0];
return head === undefined ? null : (fieldOfRequestKey.get(head) ?? null);
}
function validate<Body>(schema: ZodType, body: Body): NeedBodyValidation<Body> {
const result = schema.safeParse(body);
if (result.success) {
return { success: true, body };
}
const issues = result.error.issues.map((issue) => ({
field: needFormFieldOf(issue.path),
path: issue.path,
message: issue.message,
}));
return { success: false, body, issues };
}
/** Builds the NeedCreate body of a draft and checks it with the generated schema. */
export function validateNeedCreate(values: NeedFormValues): NeedBodyValidation<NeedCreate> {
return validate(NeedCreate, toCreateBody(values));
}
/** Builds the NeedUpdate body of a draft and checks it with the generated schema. */
export function validateNeedUpdate(
original: Need,
values: NeedFormValues,
): NeedBodyValidation<NeedUpdate> {
return validate(NeedUpdate, toUpdateBody(original, values));
}