From 3b917befa9e953cede2be9e12a2788fc950c1e3f Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 11:36:50 +0300 Subject: [PATCH] feat(frontend): add need entity form model over the transport DTOs --- frontend/README.en.md | 14 +- frontend/README.md | 14 +- frontend/src/entities/need/index.ts | 53 ++ frontend/src/entities/need/model/edit.ts | 238 ++++++++ .../src/entities/need/model/from-transport.ts | 126 +++++ .../src/entities/need/model/need-form.test.ts | 530 ++++++++++++++++++ .../src/entities/need/model/to-transport.ts | 259 +++++++++ frontend/src/entities/need/model/types.ts | 117 ++++ frontend/src/entities/need/model/validate.ts | 63 +++ 9 files changed, 1412 insertions(+), 2 deletions(-) create mode 100644 frontend/src/entities/need/index.ts create mode 100644 frontend/src/entities/need/model/edit.ts create mode 100644 frontend/src/entities/need/model/from-transport.ts create mode 100644 frontend/src/entities/need/model/need-form.test.ts create mode 100644 frontend/src/entities/need/model/to-transport.ts create mode 100644 frontend/src/entities/need/model/types.ts create mode 100644 frontend/src/entities/need/model/validate.ts diff --git a/frontend/README.en.md b/frontend/README.en.md index bb1ee33..9761893 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -7,7 +7,7 @@ A React and TypeScript SPA built with Vite and organized using FSD. The interfac - `src/app/` starts the application: the route tree (`router/`), the query client (`providers/`), global styles, and the route error page. - `src/pages/` holds pages: `welcome` (start page), `placeholder` (screen placeholders and the screen map), `status` (technical status), `not-found`. - `src/widgets/` holds shells: `public-shell`, `candidate-shell`, `employer-shell`, plus the technical `system-status` widget. -- `src/features/` and `src/entities/` are still empty. +- `src/entities/` holds entities: `need` (the form model of an employer need, see [Need entity](#need-entity)); `src/features/` is still empty. - `src/shared/ui/` holds design tokens, fonts, logos, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks. - `codegen/orval.config.ts` configures generation from the shared OpenAPI contract; `codegen/mock-patterns.ts` is the step after Orval that fixes MSW mocks of strings with a `pattern` (see [API client generation](#api-client-generation)). - `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture. @@ -35,6 +35,18 @@ Generated Orval hooks call the shared same-origin `apiRequest` client, so the `Q - `staleTime` of 30 s; window focus does not refetch, and screens that need fresh data opt in per query; - mutations do not retry until the API supports `Idempotency-Key`. +## Need entity + +`entities/need` converts the generated DTOs of the need contract (`Need`, `NeedCreate`, `NeedUpdate`) to a form model and back. It is pure functions without React and without its own store; server data stays in the TanStack Query cache. The need UI is not implemented yet. + +- `fromTransport` builds a draft from a `Need`. Each requirement field is an explicit state: `unknown` without a value, `extracted` as a stored suggestion with its provenance and quote, and `confirmed` as a confirmed value. An unknown field never becomes an empty string, an empty list, or a default value; a skill outside the taxonomy keeps `taxonomy_code: null`. Data that breaks the rule "value and source are null exactly when unknown" is rejected with `NeedTransportError`. +- `toUpdateBody(need, draft)` sends only the fields whose request value changed, plus the `expected_version` of the read version. An untouched suggestion is not sent; when its field or list is sent for another reason, it goes with status `extracted`. A cleared field is sent as null, an emptied list as `[]`, and an untouched list is absent. +- `toCreateBody(draft)` always sends the title and leaves out unknown fields and empty lists, so the server extracts them from `source_text`. +- The edit functions (`confirmField`, `setFieldValue`, `clearField`, `confirmSkill`, `moveSkill`, and others) keep the invariants: only an untouched suggestion has status `extracted`, an edited value becomes `confirmed`, and moving a skill between lists does not confirm it. +- `validateNeedCreate` and `validateNeedUpdate` check the body with the generated Zod schemas and tie the problems to form fields. The server checks cross-field rules (the salary width, a repeated skill), and `needFormFieldOf` maps its pointer to a form field. + +The tests take their fixtures from the named contract examples in `api/core/openapi.bundle.yml` and check every body with the generated `NeedCreate` and `NeedUpdate` schemas. + ## API client generation `make -C frontend generate` runs Orval with `codegen/orval.config.ts` and then `codegen/mock-patterns.ts`. For a string with a `pattern`, Orval 8.40 writes `faker.helpers.fromRegExp(pattern)` into the MSW mock: faker prints the `^` and `$` anchors and `(?:...)` groups as plain text, and Orval ignores `minLength` and `maxLength` when a `pattern` is present. The second step replaces such calls with `fakeFromPattern(pattern, {minLength, maxLength})` from `src/shared/api/mock-pattern.ts`. It takes the length bounds from the OpenAPI contract by the name of the property that holds the call and by the pattern. The step fails when a call has an unexpected form, when the contract has no such property with that pattern, or when the matching schemas disagree on the length bounds. It leaves its own output unchanged, so generation is reproducible and `make check-generated` stays stable. Enums in the mocks are written as literals (`enumGenerationType: "union"`): `Object.values` of a `zod.enum` returns Zod internals, not the values. diff --git a/frontend/README.md b/frontend/README.md index aa79ff3..db80af2 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -7,7 +7,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS - `src/app/` - запуск приложения: дерево маршрутов (`router/`), клиент запросов (`providers/`), глобальные стили и страница ошибки маршрута. - `src/pages/` - страницы: `welcome` (стартовая), `placeholder` (заготовки экранов и карта экранов), `status` (технический статус), `not-found`. - `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, а также технический виджет `system-status`. -- `src/features/` и `src/entities/` пока пусты. +- `src/entities/` - сущности: `need` (модель формы потребности работодателя, см. [сущность потребности](#сущность-потребности)); `src/features/` пока пуст. - `src/shared/ui/` - токены дизайна, шрифты, логотипы и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками. - `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта; `codegen/mock-patterns.ts` - шаг после Orval, который исправляет MSW-моки строк с `pattern` (см. [генерацию API-клиента](#генерация-api-клиента)). - `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2. @@ -35,6 +35,18 @@ SPA на React и TypeScript со сборкой Vite и структурой FS - `staleTime` 30 с; фокус окна не перезапрашивает данные, экраны со свежими данными включают это для своего запроса; - мутации не повторяются, пока API не поддерживает `Idempotency-Key`. +## Сущность потребности + +`entities/need` переводит сгенерированные DTO контракта потребности (`Need`, `NeedCreate`, `NeedUpdate`) в модель формы и обратно; это чистые функции без React и без своего хранилища, серверные данные остаются в кеше TanStack Query. UI потребностей еще не реализован. + +- `fromTransport` строит черновик из `Need`. Каждое поле требования - явное состояние: `unknown` без значения, `extracted` - сохраненное предложение с происхождением и цитатой, `confirmed` - подтвержденное значение. Неизвестное поле никогда не превращается в пустую строку, пустой список или значение по умолчанию; навык вне таксономии сохраняет `taxonomy_code: null`. Данные, нарушающие правило "value и source равны null ровно при unknown", отклоняются ошибкой `NeedTransportError`. +- `toUpdateBody(need, draft)` отправляет только поля, чье значение в запросе изменилось, и `expected_version` прочитанной версии. Нетронутое предложение не отправляется; если его поле или список отправляются по другой причине, оно уходит со статусом `extracted`. Очищенное поле уходит как null, опустошенный список - как `[]`, нетронутый список отсутствует. +- `toCreateBody(draft)` всегда отправляет название, а неизвестные поля и пустые списки опускает, чтобы сервер извлек их из `source_text`. +- Функции правки (`confirmField`, `setFieldValue`, `clearField`, `confirmSkill`, `moveSkill` и другие) сохраняют инварианты: только нетронутое предложение имеет статус `extracted`, измененное значение становится `confirmed`, перенос навыка между списками его не подтверждает. +- `validateNeedCreate` и `validateNeedUpdate` проверяют тело сгенерированными схемами Zod и связывают ошибки с полями формы; межполевые правила (ширина вилки, повтор навыка) проверяет сервер, а `needFormFieldOf` переводит его pointer в поле формы. + +Тесты берут фикстуры из именованных примеров контракта в `api/core/openapi.bundle.yml` и проверяют каждое тело сгенерированными схемами `NeedCreate` и `NeedUpdate`. + ## Генерация API-клиента `make -C frontend generate` запускает Orval с `codegen/orval.config.ts`, а затем `codegen/mock-patterns.ts`. Для строки с `pattern` Orval 8.40 пишет в MSW-мок `faker.helpers.fromRegExp(pattern)`: faker выводит якоря `^`, `$` и группы `(?:...)` как обычный текст, а `minLength` и `maxLength` при `pattern` Orval не учитывает. Второй шаг заменяет такие вызовы на `fakeFromPattern(pattern, {minLength, maxLength})` из `src/shared/api/mock-pattern.ts`. Границы длины он берет из OpenAPI-контракта по имени свойства, которое содержит вызов, и шаблону. Шаг завершается ошибкой, если вызов имеет неожиданный вид, в контракте нет такого свойства с этим шаблоном или схемы с ними расходятся в границах длины. На своем результате шаг ничего не меняет, поэтому генерация воспроизводима и `make check-generated` стабилен. Перечисления в моках записаны литералами (`enumGenerationType: "union"`): `Object.values` от `zod.enum` возвращает внутренние поля Zod, а не значения. diff --git a/frontend/src/entities/need/index.ts b/frontend/src/entities/need/index.ts new file mode 100644 index 0000000..143936c --- /dev/null +++ b/frontend/src/entities/need/index.ts @@ -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"; diff --git a/frontend/src/entities/need/model/edit.ts b/frontend/src/entities/need/model/edit.ts new file mode 100644 index 0000000..fafda7a --- /dev/null +++ b/frontend/src/entities/need/model/edit.ts @@ -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( + values: NeedFormValues, + field: K, +): NeedFieldState { + // 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; +} + +function withScalar( + values: NeedFormValues, + field: K, + state: NeedFieldState, +): 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( + 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( + 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(items: readonly T[], index: number, item: T): readonly T[] { + return items.map((current, position) => (position === index ? item : current)); +} + +function removeAt(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) }; +} diff --git a/frontend/src/entities/need/model/from-transport.ts b/frontend/src/entities/need/model/from-transport.ts new file mode 100644 index 0000000..6346df4 --- /dev/null +++ b/frontend/src/entities/need/model/from-transport.ts @@ -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 { + 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( + name: string, + field: TransportField, + map: (value: T) => U, +): NeedFieldState { + 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(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), + }; +} diff --git a/frontend/src/entities/need/model/need-form.test.ts b/frontend/src/entities/need/model/need-form.test.ts new file mode 100644 index 0000000..b3cf107 --- /dev/null +++ b/frontend/src/entities/need/model/need-form.test.ts @@ -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; + +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(state: NeedFieldState) { + 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[1]>(); + expectTypeOf(toUpdateBody).returns.toEqualTypeOf[2]>(); + expectTypeOf(fromTransport).parameter(0).toEqualTypeOf(); + // A draft cannot be sent as a request body by mistake. + expectTypeOf().not.toExtend(); + expectTypeOf().not.toExtend(); + // An unknown field has no value to collapse into an empty string or list. + expectTypeOf, { status: "unknown" }>>().toEqualTypeOf<{ + readonly status: "unknown"; + }>(); + // A suggestion always carries the stored data it came from. + expectTypeOf< + Extract["stored"] + >().toEqualTypeOf(); + expectTypeOf["stored"]>().not.toBeNullable(); +}); diff --git a/frontend/src/entities/need/model/to-transport.ts b/frontend/src/entities/need/model/to-transport.ts new file mode 100644 index 0000000..5fae0f7 --- /dev/null +++ b/frontend/src/entities/need/model/to-transport.ts @@ -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]-?: Exclude; +}; + +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( + state: NeedFieldState, + 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( + 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( + target: Partial, + 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 { + const body: Partial = {}; + 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(); + const tasks = new Set(); + 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) }; +} diff --git a/frontend/src/entities/need/model/types.ts b/frontend/src/entities/need/model/types.ts new file mode 100644 index 0000000..ee7c840 --- /dev/null +++ b/frontend/src/entities/need/model/types.ts @@ -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 = + | { 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; + readonly grade: NeedFieldState; + readonly requiredSkills: readonly NeedSkillItem[]; + readonly desiredSkills: readonly NeedSkillItem[]; + readonly tasks: readonly NeedTaskItem[]; + readonly domain: NeedFieldState; + readonly workFormats: NeedFieldState; + readonly location: NeedFieldState; + readonly salary: NeedFieldState; +} + +export type NeedFormField = keyof NeedFormValues; diff --git a/frontend/src/entities/need/model/validate.ts b/frontend/src/entities/need/model/validate.ts new file mode 100644 index 0000000..8ad56c7 --- /dev/null +++ b/frontend/src/entities/need/model/validate.ts @@ -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 = + | { readonly success: true; readonly body: Body } + | { readonly success: false; readonly body: Body; readonly issues: readonly NeedFormIssue[] }; + +const fieldOfRequestKey = new Map( + 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(schema: ZodType, body: Body): NeedBodyValidation { + 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 { + 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 { + return validate(NeedUpdate, toUpdateBody(original, values)); +}