feat(invitations): add the invitation compose screen with a candidate-side preview

This commit is contained in:
shira committed 2026-10-09 17:14:58 +03:00
1 parent 1a067221f7
commit cb08f212cc
35 files changed
+4170 -67

No files matched your search

@@ -0,0 +1,17 @@
// Public API of the send-invitation feature: the draft of the terms, its
// client validation, the idempotent create-update-send command, and the form
// that runs it. The page supplies the preview and reacts to the result.
export {
emptyInvitationDraft,
invitationDraftFromNeed,
invitationDraftFromTerms,
toInvitationTerms,
type InvitationDraft,
} from "./model/draft";
export { initialSendProgress, type SendProgress } from "./model/send-command";
export {
InvitationForm,
type InvitationFormProps,
type InvitationPreviewSnapshot,
} from "./ui/invitation-form";
@@ -0,0 +1,29 @@
import { emptyInvitationDraft, type InvitationDraft } from "./draft";
/** A draft that passes validation: [100000; 140000] net and a mixed package. */
export function completeDraft(overrides: Partial<InvitationDraft> = {}): InvitationDraft {
const base = emptyInvitationDraft("backend");
return {
...base,
roleTitle: "Middle Go-разработчик в команду платежей",
grade: "middle",
offerType: "full_time",
tasks: "Развивать сервис выплат\n \nПеревести отчеты на события",
team: "Пять бэкенд-разработчиков и QA-инженер.",
techStack: "Go, PostgreSQL,\nKafka",
workFormats: ["remote", "hybrid"],
location: "Москва",
channel: "video_call",
channelDetails: "Созвон с тимлидом в течение трех рабочих дней",
salaryFrom: "100000",
salaryTo: "140000",
taxBasis: "net",
packageItems: {
bonus: { status: "provided", description: "Квартальная премия до 20%" },
equipment: { status: "provided", description: "Ноутбук и монитор" },
training: { status: "not_provided", description: "" },
health_insurance: { status: "not_provided", description: "" },
},
...overrides,
};
}
@@ -0,0 +1,221 @@
import type {
GradeCode,
InvitationCommunicationChannel,
InvitationOfferType,
InvitationResponsePeriod,
InvitationTerms,
Need,
SalaryTaxBasis,
SpecializationCode,
WorkFormat,
} from "../../../shared/api/schemas";
import {
defaultResponsePeriod,
packageItemKeys,
type InvitationPackageKey,
} from "../../../entities/invitation";
import { fromTransport } from "../../../entities/need";
// The form draft of an invitation. It keeps what the employer typed as
// strings, so a half-filled field is never coerced into a default value;
// toInvitationTerms turns a validated draft into the transport terms.
export type PackageChoice = "" | "provided" | "not_provided";
export interface PackageItemDraft {
readonly status: PackageChoice;
readonly description: string;
}
export interface InvitationDraft {
readonly roleTitle: string;
readonly specialization: SpecializationCode | "";
readonly grade: GradeCode | "";
readonly offerType: InvitationOfferType | "";
/** One task per line. */
readonly tasks: string;
readonly team: string;
/** Technologies separated by commas or line breaks. */
readonly techStack: string;
readonly workFormats: readonly WorkFormat[];
readonly location: string;
readonly channel: InvitationCommunicationChannel | "";
readonly channelDetails: string;
readonly salaryFrom: string;
readonly salaryTo: string;
readonly taxBasis: SalaryTaxBasis | "";
readonly packageItems: Readonly<Record<InvitationPackageKey, PackageItemDraft>>;
readonly responsePeriodDays: InvitationResponsePeriod;
}
const emptyPackageItem: PackageItemDraft = { status: "", description: "" };
/** A blank draft; no package condition is preselected, because each is an explicit choice. */
export function emptyInvitationDraft(
specialization: SpecializationCode | "" = "",
): InvitationDraft {
return {
roleTitle: "",
specialization,
grade: "",
offerType: "",
tasks: "",
team: "",
techStack: "",
workFormats: [],
location: "",
channel: "",
channelDetails: "",
salaryFrom: "",
salaryTo: "",
taxBasis: "",
packageItems: Object.fromEntries(
packageItemKeys.map((key) => [key, emptyPackageItem]),
) as Record<InvitationPackageKey, PackageItemDraft>,
responsePeriodDays: defaultResponsePeriod,
};
}
/**
* Prefills a draft from the confirmed requirements of a need. Values that
* nobody confirmed stay empty, and the specialization of the search entry
* wins over the need, because the invitation is for that entry.
*/
export function invitationDraftFromNeed(
need: Need,
specialization: SpecializationCode | "",
): InvitationDraft {
const values = fromTransport(need);
const draft = emptyInvitationDraft(specialization);
const confirmed = <T>(state: { status: string; value?: T }): T | undefined =>
state.status === "confirmed" ? state.value : undefined;
const salary = confirmed(values.salary);
const workFormats = confirmed(values.workFormats);
const needSpecialization = confirmed(values.specialization);
return {
...draft,
roleTitle: need.title,
specialization: specialization || needSpecialization || "",
grade: confirmed(values.grade) ?? "",
tasks: values.tasks
.filter((task) => task.status === "confirmed")
.map((task) => task.text)
.join("\n"),
techStack: values.requiredSkills
.filter((skill) => skill.status === "confirmed")
.map((skill) => skill.name)
.join(", "),
workFormats: workFormats ? [...workFormats] : [],
location: confirmed(values.location) ?? "",
salaryFrom: salary ? String(salary.from) : "",
salaryTo: salary ? String(salary.to) : "",
taxBasis: salary?.taxBasis ?? "",
};
}
/** Restores the draft of stored terms, for example when a saved draft is reopened. */
export function invitationDraftFromTerms(
terms: InvitationTerms,
responsePeriodDays: InvitationResponsePeriod,
): InvitationDraft {
return {
roleTitle: terms.role_title,
specialization: terms.specialization,
grade: terms.grade,
offerType: terms.offer_type,
tasks: terms.tasks.join("\n"),
team: terms.team,
techStack: terms.tech_stack.join(", "),
workFormats: [...terms.work_formats],
location: terms.location ?? "",
channel: terms.communication_method.channel,
channelDetails: terms.communication_method.details ?? "",
salaryFrom: String(terms.salary.salary_from),
salaryTo: String(terms.salary.salary_to),
taxBasis: terms.salary.tax_basis,
packageItems: Object.fromEntries(
packageItemKeys.map((key) => {
const item = terms.package[key];
return [
key,
item.status === "provided"
? { status: "provided", description: item.description }
: { status: "not_provided", description: "" },
];
}),
) as Record<InvitationPackageKey, PackageItemDraft>,
responsePeriodDays,
};
}
/** Splits the task text into trimmed, non-empty lines. */
export function taskLines(value: string): string[] {
return value
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
}
/** Splits the technology text at commas and line breaks. */
export function techStackItems(value: string): string[] {
return value
.split(/[,\n]/)
.map((item) => item.trim())
.filter(Boolean);
}
function optionalLine(value: string): string | null {
const trimmed = value.trim();
return trimmed === "" ? null : trimmed;
}
/**
* Builds the transport terms of a draft. Call it only for a draft without
* validation issues: it assumes every required choice is made.
*/
export function toInvitationTerms(draft: InvitationDraft): InvitationTerms {
if (
!draft.specialization ||
!draft.grade ||
!draft.offerType ||
!draft.channel ||
!draft.taxBasis
) {
throw new Error("The invitation draft has an unanswered required choice.");
}
return {
role_title: draft.roleTitle.trim(),
specialization: draft.specialization,
grade: draft.grade,
offer_type: draft.offerType,
tasks: taskLines(draft.tasks),
team: draft.team.trim(),
tech_stack: techStackItems(draft.techStack),
work_formats: [...draft.workFormats],
// A remote-only role may still name a place; the server requires one
// only for the office and hybrid formats.
location: optionalLine(draft.location),
communication_method: {
channel: draft.channel,
details: optionalLine(draft.channelDetails),
},
salary: {
salary_from: Number(draft.salaryFrom),
salary_to: Number(draft.salaryTo),
currency: "RUB",
period: "month",
tax_basis: draft.taxBasis,
},
package: Object.fromEntries(
packageItemKeys.map((key) => {
const item = draft.packageItems[key];
return [
key,
item.status === "provided"
? { status: "provided", description: item.description.trim() }
: { status: "not_provided" },
];
}),
) as InvitationTerms["package"],
};
}
@@ -0,0 +1,121 @@
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
import { formatRetryAfter } from "../../../entities/match";
import { issuesOfProblem, type InvitationIssue } from "./validate";
import type { SendStage } from "./send-command";
/**
* What the form shows after a failed attempt.
*
* - fields: the server rejected values; the issues are bound to fields.
* - retry: the outcome is unknown or temporary; the next click repeats the
* same command with the same Idempotency-Key.
* - blocked: the server refused the command for a reason the form cannot fix.
* - access: the session, the membership, or the role no longer allows it.
* - csrf: the CSRF token is stale; the session must be read again.
*/
export type SendFailure =
| {
readonly kind: "fields";
readonly issues: readonly InvitationIssue[];
readonly message: string;
}
| { readonly kind: "retry"; readonly message: string }
| { readonly kind: "blocked"; readonly message: string }
| { readonly kind: "access"; readonly message: string }
| { readonly kind: "csrf"; readonly message: string };
const sameKeyHint =
"Нажмите «Отправить приглашение» еще раз: повтор использует тот же ключ и не создаст второе приглашение.";
function isAmbiguous(error: ApiRequestError): boolean {
return error.status === 0 || error.status >= 500 || error.code === invalidResponseCode;
}
/** Describes a failed send command without any value the employer did not type. */
export function describeSendFailure(stage: SendStage, error: unknown): SendFailure {
if (!(error instanceof ApiRequestError)) {
return { kind: "retry", message: `Не удалось завершить отправку. ${sameKeyHint}` };
}
if (isAmbiguous(error)) {
return {
kind: "retry",
message: `Сервер не подтвердил результат. ${sameKeyHint}`,
};
}
if (error.status === 403 && error.code === "csrf_check_failed") {
return {
kind: "csrf",
message: "Проверка входа устарела. Мы обновили ее; отправьте приглашение еще раз.",
};
}
if (error.status === 401 || error.status === 403 || error.status === 404) {
return {
kind: "access",
message:
error.status === 401
? "Сессия завершилась. Войдите снова; заполненные условия останутся на странице до перезагрузки."
: "Нет доступа к приглашениям этой компании. Приглашать кандидатов может только владелец.",
};
}
if (error.status === 400) {
if (error.fieldErrors.some((field) => field.pointer === "/candidate_handle")) {
return {
kind: "blocked",
message:
"Кандидат больше недоступен компании. Вернитесь к поиску и выберите кандидата заново.",
};
}
if (error.fieldErrors.some((field) => field.pointer.startsWith("/need"))) {
return {
kind: "blocked",
message:
"Потребность не найдена или ее версия устарела. Откройте приглашение из поиска заново.",
};
}
const issues = issuesOfProblem(error.fieldErrors);
return {
kind: "fields",
issues,
message:
issues.length > 0
? "Сервер не принял условия. Исправьте отмеченные поля."
: "Сервер не принял запрос. Проверьте условия и повторите.",
};
}
if (error.status === 409 && error.code === "idempotency_in_progress") {
return {
kind: "retry",
message: `Предыдущая попытка еще обрабатывается. Подождите несколько секунд. ${sameKeyHint}`,
};
}
if (error.status === 409) {
return {
kind: "blocked",
message:
stage === "send"
? "Сейчас этому кандидату нельзя отправить приглашение: профиль стал недоступен компании или действует ограничение. Приглашение не отправлено."
: "Черновик уже нельзя изменить. Обновите страницу, чтобы увидеть его состояние.",
};
}
if (error.status === 412) {
return {
kind: "retry",
message:
"Черновик изменился в другом окне. Мы загрузили его текущую версию; ваши условия применятся при следующей отправке.",
};
}
if (error.status === 429) {
const wait = formatRetryAfter(error.retryAfterSeconds);
return {
kind: "retry",
message:
stage === "send"
? `Исчерпан лимит приглашений компании на неделю. ${wait ? `Повторить можно ${wait}.` : "Повторите позже."}`
: `Слишком много изменений зарплатных вилок. ${wait ? `Повторить можно ${wait}.` : "Повторите позже."}`,
};
}
return {
kind: "blocked",
message: "Сервер отклонил запрос. Обновите страницу и проверьте состояние приглашения.",
};
}
@@ -0,0 +1,360 @@
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import type {
InvitationTerms,
OrganizationInvitation,
OrganizationInvitationCreate,
OrganizationInvitationUpdate,
} from "../../../shared/api/schemas";
import { toInvitationTerms } from "./draft";
import { completeDraft } from "./draft.fixtures";
import { describeSendFailure } from "./failure";
import {
initialSendProgress,
runSendCommand,
type SendOutcome,
type SendRequest,
} from "./send-command";
const organizationId = "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01";
const invitationId = "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f";
const candidateHandle = `cv1_${"A".repeat(43)}`;
const base = `http://localhost/api/v1/organizations/${organizationId}/invitations`;
const deadline = "2026-10-16T10:00:00Z";
const server = setupServer();
beforeAll(() => server.listen());
afterEach(() => {
vi.unstubAllGlobals();
server.resetHandlers();
});
afterAll(() => server.close());
function stubRelativeFetch(): void {
const realFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
realFetch(new URL(input, "http://localhost"), init),
);
}
function invitation(
terms: InvitationTerms,
overrides: Partial<OrganizationInvitation> = {},
): OrganizationInvitation {
return {
id: invitationId,
organization_id: organizationId,
candidate_handle: candidateHandle,
need: null,
state: "draft",
expiry_reason: null,
version: 1,
terms_version: 1,
terms,
response_period_days: 7,
response_deadline_at: null,
salary_raise_used: false,
salary_fit: "not_available",
contact_access: { status: "not_granted", fields: [] },
created_at: "2026-10-09T10:00:00Z",
updated_at: "2026-10-09T10:00:00Z",
delivered_at: null,
viewed_at: null,
responded_at: null,
...overrides,
};
}
type Recorded = {
method: string;
path: string;
key: string | null;
csrf: string | null;
body: unknown;
};
/**
* A small fake of the invitation endpoints with the replay rules of the
* contract: a known key replays the stored answer, and `lose` drops the
* response of the next matching request after the server applied it.
*/
function fakeBackend(options: { lose?: "create" | "send"; sendStatus?: number } = {}) {
const requests: Recorded[] = [];
let stored: OrganizationInvitation | null = null;
let deliveries = 0;
let lose = options.lose;
const createReplies = new Map<string, OrganizationInvitation>();
const sendReplies = new Map<string, OrganizationInvitation>();
async function record(request: Request): Promise<Recorded> {
const entry: Recorded = {
method: request.method,
path: new URL(request.url).pathname,
key: request.headers.get("Idempotency-Key"),
csrf: request.headers.get("X-CSRF-Token"),
body: request.method === "GET" ? null : await request.json(),
};
requests.push(entry);
return entry;
}
server.use(
http.post(base, async ({ request }) => {
const entry = await record(request);
const key = entry.key ?? "";
let reply = createReplies.get(key);
if (!reply) {
const body = entry.body as OrganizationInvitationCreate;
reply = invitation(body.terms, { response_period_days: body.response_period_days ?? 7 });
stored = reply;
createReplies.set(key, reply);
}
if (lose === "create") {
lose = undefined;
return HttpResponse.error();
}
return HttpResponse.json(reply, { status: 201 });
}),
http.patch(`${base}/${invitationId}`, async ({ request }) => {
const entry = await record(request);
const body = entry.body as OrganizationInvitationUpdate;
if (!stored || body.expected_version !== stored.version) {
return HttpResponse.json(
{ type: "about:blank", title: "Version conflict", status: 412, code: "version_conflict" },
{ status: 412, headers: { "Content-Type": "application/problem+json" } },
);
}
stored = invitation(body.terms ?? stored.terms, {
version: stored.version + 1,
terms_version: stored.terms_version + 1,
});
return HttpResponse.json(stored);
}),
http.get(`${base}/${invitationId}`, async ({ request }) => {
await record(request);
return HttpResponse.json(stored);
}),
http.post(`${base}/${invitationId}/send`, async ({ request }) => {
const entry = await record(request);
if (options.sendStatus) {
return HttpResponse.json(
{
type: "about:blank",
title: "Rejected",
status: options.sendStatus,
code: "version_conflict",
},
{ status: options.sendStatus, headers: { "Content-Type": "application/problem+json" } },
);
}
const key = entry.key ?? "";
let reply = sendReplies.get(key);
if (!reply && stored) {
deliveries += 1;
stored = {
...stored,
state: "delivered",
version: stored.version + 1,
delivered_at: "2026-10-09T10:00:00Z",
response_deadline_at: deadline,
};
reply = stored;
sendReplies.set(key, reply);
}
if (lose === "send") {
lose = undefined;
return HttpResponse.error();
}
return HttpResponse.json(reply);
}),
);
return { requests, deliveries: () => deliveries };
}
const terms = toInvitationTerms(completeDraft());
function request(overrides: Partial<SendRequest> = {}): SendRequest {
return {
organizationId,
candidateHandle,
need: null,
terms,
responsePeriodDays: 7,
csrfToken: "csrf-token",
...overrides,
};
}
function keys(): () => string {
let next = 0;
return () => `key-${++next}`;
}
describe("send invitation command", () => {
it("creates the draft and sends it with separate keys and the CSRF token", async () => {
stubRelativeFetch();
const backend = fakeBackend();
const onDraft = vi.fn();
const outcome = await runSendCommand(request(), initialSendProgress, {
newKey: keys(),
onDraft,
});
expect(outcome.kind).toBe("sent");
if (outcome.kind !== "sent") return;
expect(outcome.invitation.state).toBe("delivered");
expect(outcome.invitation.response_deadline_at).toBe(deadline);
expect(outcome.progress).toMatchObject({ createKey: null, sendKey: null });
expect(onDraft).toHaveBeenCalledOnce();
expect(backend.requests.map((item) => [item.method, item.key, item.csrf])).toEqual([
["POST", "key-1", "csrf-token"],
["POST", "key-2", "csrf-token"],
]);
expect(backend.requests[0]?.body).toEqual({
candidate_handle: candidateHandle,
need: null,
response_period_days: 7,
terms,
});
expect(backend.requests[1]?.body).toEqual({ expected_version: 1 });
});
it("repeats a send whose response was lost with the same key and delivers once", async () => {
stubRelativeFetch();
const backend = fakeBackend({ lose: "send" });
const newKey = keys();
const first = await runSendCommand(request(), initialSendProgress, { newKey });
expect(first).toMatchObject({ kind: "failed", stage: "send" });
if (first.kind !== "failed") return;
expect(describeSendFailure(first.stage, first.error).kind).toBe("retry");
const second = await runSendCommand(request(), first.progress, { newKey });
expect(second.kind).toBe("sent");
const sends = backend.requests.filter((item) => item.path.endsWith("/send"));
expect(sends.map((item) => item.key)).toEqual(["key-2", "key-2"]);
expect(backend.requests.filter((item) => item.path.endsWith("/invitations"))).toHaveLength(1);
expect(backend.deliveries()).toBe(1);
});
it("repeats a create whose response was lost with the same key", async () => {
stubRelativeFetch();
const backend = fakeBackend({ lose: "create" });
const newKey = keys();
const first = await runSendCommand(request(), initialSendProgress, { newKey });
expect(first).toMatchObject({ kind: "failed", stage: "create" });
const second = await runSendCommand(
request(),
(first as Extract<SendOutcome, { kind: "failed" }>).progress,
{ newKey },
);
expect(second.kind).toBe("sent");
const creates = backend.requests.filter((item) => item.path.endsWith("/invitations"));
expect(creates.map((item) => item.key)).toEqual(["key-1", "key-1"]);
});
it("binds server field errors of a rejected draft to the form and sends nothing", async () => {
stubRelativeFetch();
const sent: string[] = [];
server.use(
http.post(base, () =>
HttpResponse.json(
{
type: "about:blank",
title: "Validation failed",
status: 400,
code: "validation_failed",
errors: [
{
in: "body",
pointer: "/terms/communication_method",
code: "required",
message: "x",
},
{ in: "body", pointer: "/terms/salary/salary_to", code: "invalid", message: "x" },
],
},
{ status: 400, headers: { "Content-Type": "application/problem+json" } },
),
),
http.post(`${base}/${invitationId}/send`, () => {
sent.push("send");
return HttpResponse.json({}, { status: 500 });
}),
);
const outcome = await runSendCommand(request(), initialSendProgress, { newKey: keys() });
expect(outcome).toMatchObject({ kind: "failed", stage: "create" });
if (outcome.kind !== "failed") return;
const failure = describeSendFailure(outcome.stage, outcome.error);
expect(failure.kind).toBe("fields");
expect(failure.kind === "fields" ? failure.issues.map((issue) => issue.field) : []).toEqual([
"channel",
"salaryTo",
]);
expect(outcome.progress.draft).toBeNull();
expect(sent).toEqual([]);
});
it("updates a saved draft whose terms changed before sending it under a new key", async () => {
stubRelativeFetch();
const recorded: { method: string; body: unknown }[] = [];
const newKey = keys();
// A draft that was saved but not sent, for example reopened from the address.
const saved = invitation(terms);
const changed = { ...terms, role_title: "Senior Go-разработчик" };
server.use(
http.patch(`${base}/${invitationId}`, async ({ request: patch }) => {
const body = (await patch.json()) as OrganizationInvitationUpdate;
recorded.push({ method: "PATCH", body });
return HttpResponse.json(invitation(changed, { version: 2, terms_version: 2 }));
}),
http.post(`${base}/${invitationId}/send`, async ({ request: send }) => {
recorded.push({
method: `POST ${send.headers.get("Idempotency-Key")}`,
body: await send.json(),
});
return HttpResponse.json(
invitation(changed, {
state: "delivered",
version: 3,
terms_version: 2,
delivered_at: "2026-10-09T10:00:00Z",
response_deadline_at: deadline,
}),
);
}),
);
const outcome = await runSendCommand(
request({ terms: changed }),
{ ...initialSendProgress, draft: saved },
{ newKey },
);
expect(outcome.kind).toBe("sent");
expect(recorded.map((item) => [item.method, item.body])).toEqual([
["PATCH", { expected_version: 1, need: null, response_period_days: 7, terms: changed }],
["POST key-1", { expected_version: 2 }],
]);
});
it("reloads the draft after a version conflict and keeps the form's terms for the retry", async () => {
stubRelativeFetch();
const backend = fakeBackend({ sendStatus: 412 });
const outcome = await runSendCommand(request(), initialSendProgress, { newKey: keys() });
expect(outcome).toMatchObject({ kind: "failed", stage: "send" });
if (outcome.kind !== "failed") return;
expect(backend.requests.map((item) => item.method)).toEqual(["POST", "POST", "GET"]);
expect(outcome.progress.draft?.id).toBe(invitationId);
expect(describeSendFailure("send", outcome.error).message).toContain("другом окне");
});
});
@@ -0,0 +1,201 @@
import { ApiRequestError } from "../../../shared/api";
import type {
InvitationNeedReference,
InvitationResponsePeriod,
InvitationTerms,
OrganizationInvitation,
OrganizationInvitationCreate,
} from "../../../shared/api/schemas";
import {
createInvitationDraft,
readOrganizationInvitation,
sendInvitationDraft,
updateInvitationDraft,
} from "../../../entities/invitation";
// Sending an invitation is three contract operations: create the draft
// (Idempotency-Key), bring its terms up to date when the form changed after
// the draft was created (expected_version), and send it (Idempotency-Key).
// The progress object is the client side of that command: it remembers the
// draft and the key of each keyed step, so a repeated click, a retry after a
// lost response, or a retry after a server error replays the same key and
// never creates a second draft or a second delivery. A key is bound to what
// it protects (the create body, or the draft id and version) and changes only
// when that changes, which is when the server would answer 422 for the old key.
/** An Idempotency-Key and the request it was issued for. */
export interface KeyBinding {
readonly fingerprint: string;
readonly key: string;
}
export interface SendProgress {
readonly createKey: KeyBinding | null;
/** The draft as the server last returned it, or null before it exists. */
readonly draft: OrganizationInvitation | null;
readonly sendKey: KeyBinding | null;
}
export const initialSendProgress: SendProgress = { createKey: null, draft: null, sendKey: null };
export interface SendRequest {
readonly organizationId: string;
readonly candidateHandle: string;
readonly need: InvitationNeedReference | null;
readonly terms: InvitationTerms;
readonly responsePeriodDays: InvitationResponsePeriod;
readonly csrfToken: string;
}
export type SendStage = "create" | "update" | "send";
export type SendOutcome =
| {
readonly kind: "sent";
/** The invitation after the send; its state is no longer `draft`. */
readonly invitation: OrganizationInvitation;
readonly progress: SendProgress;
}
| {
readonly kind: "failed";
readonly stage: SendStage;
readonly error: unknown;
readonly progress: SendProgress;
};
export interface SendDependencies {
readonly newKey: () => string;
/** Called once the draft exists on the server, before it is sent. */
readonly onDraft?: ((draft: OrganizationInvitation) => void) | undefined;
}
export function newIdempotencyKey(): string {
if (typeof crypto === "undefined" || typeof crypto.randomUUID !== "function") {
throw new Error("Secure random key generation is unavailable.");
}
return crypto.randomUUID();
}
/** JSON with object keys in a fixed order, so equal values give equal text. */
export function stableJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
if (value !== null && typeof value === "object") {
const entries = Object.entries(value as Record<string, unknown>)
.filter(([, item]) => item !== undefined)
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`).join(",")}}`;
}
return JSON.stringify(value);
}
function bind(previous: KeyBinding | null, fingerprint: string, newKey: () => string): KeyBinding {
return previous?.fingerprint === fingerprint ? previous : { fingerprint, key: newKey() };
}
function draftMatches(draft: OrganizationInvitation, request: SendRequest): boolean {
return (
stableJson(draft.terms) === stableJson(request.terms) &&
draft.response_period_days === request.responsePeriodDays &&
stableJson(draft.need) === stableJson(request.need)
);
}
function versionConflict(error: unknown): boolean {
return error instanceof ApiRequestError && error.status === 412;
}
/** Reads the current draft after a version conflict; keeps the old one when the read fails. */
async function reloadDraft(
request: SendRequest,
progress: SendProgress,
draft: OrganizationInvitation,
): Promise<SendProgress> {
try {
const latest = await readOrganizationInvitation(request.organizationId, draft.id);
return { ...progress, draft: latest };
} catch {
return progress;
}
}
/**
* Runs the send command from the given progress. It never throws for a
* request failure: the outcome carries the stage, the error, and the progress
* to pass to the next attempt.
*/
export async function runSendCommand(
request: SendRequest,
initial: SendProgress,
dependencies: SendDependencies,
): Promise<SendOutcome> {
let progress = initial;
if (progress.draft === null) {
const body: OrganizationInvitationCreate = {
candidate_handle: request.candidateHandle,
need: request.need,
response_period_days: request.responsePeriodDays,
terms: request.terms,
};
const createKey = bind(progress.createKey, stableJson(body), dependencies.newKey);
progress = { ...progress, createKey };
try {
const draft = await createInvitationDraft({
organizationId: request.organizationId,
csrfToken: request.csrfToken,
body,
idempotencyKey: createKey.key,
});
progress = { ...progress, draft };
dependencies.onDraft?.(draft);
} catch (error: unknown) {
return { kind: "failed", stage: "create", error, progress };
}
}
let draft = progress.draft;
if (draft === null) throw new Error("The draft must exist after its creation.");
if (draft.state !== "draft") return { kind: "sent", invitation: draft, progress };
if (!draftMatches(draft, request)) {
try {
draft = await updateInvitationDraft({
organizationId: request.organizationId,
csrfToken: request.csrfToken,
invitationId: draft.id,
body: {
expected_version: draft.version,
need: request.need,
response_period_days: request.responsePeriodDays,
terms: request.terms,
},
});
progress = { ...progress, draft };
} catch (error: unknown) {
if (versionConflict(error)) progress = await reloadDraft(request, progress, draft);
return { kind: "failed", stage: "update", error, progress };
}
if (draft.state !== "draft") return { kind: "sent", invitation: draft, progress };
}
const sendKey = bind(progress.sendKey, `${draft.id}:${draft.version}`, dependencies.newKey);
progress = { ...progress, sendKey };
try {
const sent = await sendInvitationDraft({
organizationId: request.organizationId,
csrfToken: request.csrfToken,
invitationId: draft.id,
expectedVersion: draft.version,
idempotencyKey: sendKey.key,
});
// The command is complete: the next command starts with fresh keys.
return {
kind: "sent",
invitation: sent,
progress: { createKey: null, draft: sent, sendKey: null },
};
} catch (error: unknown) {
if (versionConflict(error)) progress = await reloadDraft(request, progress, draft);
return { kind: "failed", stage: "send", error, progress };
}
}
@@ -0,0 +1,132 @@
import { describe, expect, it } from "vitest";
import { InvitationTerms as InvitationTermsSchema } from "../../../shared/api/schemas";
import {
emptyInvitationDraft,
invitationDraftFromTerms,
toInvitationTerms,
type InvitationDraft,
} from "./draft";
import { completeDraft } from "./draft.fixtures";
import { fieldOfPointer, issuesOfProblem, validateInvitationDraft } from "./validate";
const fieldsOf = (draft: InvitationDraft) => validateInvitationDraft(draft).map((i) => i.field);
describe("invitation draft validation", () => {
it("accepts a complete draft and builds terms the contract accepts", () => {
const draft = completeDraft();
expect(validateInvitationDraft(draft)).toEqual([]);
const terms = toInvitationTerms(draft);
expect(InvitationTermsSchema.safeParse(terms).success).toBe(true);
expect(terms.tasks).toEqual(["Развивать сервис выплат", "Перевести отчеты на события"]);
expect(terms.tech_stack).toEqual(["Go", "PostgreSQL", "Kafka"]);
expect(terms.salary).toEqual({
salary_from: 100000,
salary_to: 140000,
currency: "RUB",
period: "month",
tax_basis: "net",
});
expect(terms.package.training).toEqual({ status: "not_provided" });
expect(terms.communication_method).toEqual({
channel: "video_call",
details: "Созвон с тимлидом в течение трех рабочих дней",
});
});
it("blocks a blank draft on every required term in the order of the form", () => {
expect(fieldsOf(emptyInvitationDraft())).toEqual([
"roleTitle",
"specialization",
"grade",
"offerType",
"tasks",
"team",
"techStack",
"workFormats",
"channel",
"salaryFrom",
"salaryTo",
"taxBasis",
"package.bonus",
"package.equipment",
"package.training",
"package.health_insurance",
]);
});
it.each([
[{ salaryTo: "" }, ["salaryTo"]],
[{ salaryFrom: "" }, ["salaryFrom"]],
[{ taxBasis: "" as const }, ["taxBasis"]],
[{ salaryFrom: "100500" }, ["salaryTo"]],
[{ salaryFrom: "140000", salaryTo: "100000" }, ["salaryTo"]],
[{ salaryTo: "105000" }, ["salaryTo"]],
[{ salaryFrom: "79000", salaryTo: "121000" }, ["salaryTo"]],
])("does not allow sending an incomplete or invalid salary range %j", (overrides, fields) => {
expect(fieldsOf(completeDraft(overrides))).toEqual(fields);
});
it("requires the communication method, a place for office formats, and each package choice", () => {
expect(fieldsOf(completeDraft({ channel: "" }))).toEqual(["channel"]);
expect(fieldsOf(completeDraft({ location: "" }))).toEqual(["location"]);
expect(fieldsOf(completeDraft({ location: "", workFormats: ["remote"] }))).toEqual([]);
const draft = completeDraft();
expect(
fieldsOf({
...draft,
packageItems: {
...draft.packageItems,
training: { status: "", description: "" },
bonus: { status: "provided", description: " " },
},
}),
).toEqual(["package.bonus", "package.training"]);
});
it("finds a technology repeated in another letter case", () => {
const issues = validateInvitationDraft(completeDraft({ techStack: "Go, PostgreSQL, GO" }));
expect(issues).toEqual([{ field: "techStack", message: "Технология «GO» указана дважды." }]);
});
it("restores the same terms from a stored invitation", () => {
const terms = toInvitationTerms(completeDraft());
expect(toInvitationTerms(invitationDraftFromTerms(terms, 14))).toEqual(terms);
expect(invitationDraftFromTerms(terms, 14).responsePeriodDays).toBe(14);
});
});
describe("server field errors", () => {
it.each([
["/terms/salary/salary_to", "salaryTo"],
["/terms/salary/tax_basis", "taxBasis"],
["/terms/communication_method", "channel"],
["/terms/communication_method/channel", "channel"],
["/terms/communication_method/details", "channelDetails"],
["/terms/tech_stack/1", "techStack"],
["/terms/tasks/0", "tasks"],
["/terms/location", "location"],
["/terms/package/training", "package.training"],
["/terms/package/bonus/description", "package.bonus"],
["/response_period_days", "responsePeriodDays"],
["/candidate_handle", null],
["/expected_version", null],
["", null],
])("maps the pointer %s to %s", (pointer, field) => {
expect(fieldOfPointer(pointer)).toBe(field);
});
it("binds each body error to its field once, in the order of the form", () => {
const issues = issuesOfProblem([
{ in: "body", pointer: "/terms/salary/salary_to", code: "invalid", message: "Width." },
{ in: "body", pointer: "/terms/communication_method", code: "required", message: "Missing." },
{ in: "body", pointer: "/terms/package/training", code: "required", message: "Missing." },
{ in: "body", pointer: "/terms/salary/salary_to", code: "invalid", message: "Again." },
{ in: "header", pointer: "/Idempotency-Key", code: "invalid", message: "Key." },
]);
expect(issues.map((issue) => issue.field)).toEqual(["channel", "salaryTo", "package.training"]);
expect(issues[2]?.message).toContain("незаполненным");
expect(JSON.stringify(issues)).not.toMatch(/Width|Missing|Again/);
});
});
@@ -0,0 +1,267 @@
import type { ProblemFieldError } from "../../../shared/api/schemas";
import { OrganizationInvitationCreate } from "../../../shared/api/schemas";
import {
packageItemKeys,
packageItemLabels,
salaryRangeIssue,
type InvitationPackageKey,
} from "../../../entities/invitation";
import { taskLines, techStackItems, toInvitationTerms, type InvitationDraft } from "./draft";
// Client validation mirrors the contract for immediate feedback: the per-field
// limits and the cross-field rules of the terms (salary range, place of work,
// repeated technology). The server stays the source of truth; its RFC 9457
// field errors come back through fieldOfPointer and land on the same fields.
export type InvitationField =
| "roleTitle"
| "specialization"
| "grade"
| "offerType"
| "tasks"
| "team"
| "techStack"
| "workFormats"
| "location"
| "channel"
| "channelDetails"
| "salaryFrom"
| "salaryTo"
| "taxBasis"
| `package.${InvitationPackageKey}`
| "responsePeriodDays";
/** Field order of the form, used to order the issue summary and to pick the first field. */
export const invitationFieldOrder: readonly InvitationField[] = [
"roleTitle",
"specialization",
"grade",
"offerType",
"tasks",
"team",
"techStack",
"workFormats",
"location",
"channel",
"channelDetails",
"salaryFrom",
"salaryTo",
"taxBasis",
...packageItemKeys.map((key) => `package.${key}` as const),
"responsePeriodDays",
];
export interface InvitationIssue {
readonly field: InvitationField;
readonly message: string;
}
const singleLine = /^\S(?:.*\S)?$/;
const salaryIssueMessages = {
bound: "Суммы должны быть целыми, положительными и кратными 1 000 рублей.",
order: "Верхняя граница вилки должна быть больше нижней.",
narrow: "Вилка слишком узкая: ширина должна быть не меньше 10% от середины.",
wide: "Вилка слишком широкая: ширина должна быть не больше 40% от середины.",
} as const;
function lineIssue(value: string, max: number, empty: string, field: InvitationField) {
const trimmed = value.trim();
if (trimmed === "") return { field, message: empty };
if (trimmed.length > max) return { field, message: `Не больше ${max} символов.` };
if (!singleLine.test(trimmed)) return { field, message: "Текст должен быть в одну строку." };
return null;
}
function checkSalary(draft: InvitationDraft): InvitationIssue[] {
const issues: InvitationIssue[] = [];
const from = draft.salaryFrom.trim();
const to = draft.salaryTo.trim();
if (from === "") issues.push({ field: "salaryFrom", message: "Укажите нижнюю границу вилки." });
if (to === "") issues.push({ field: "salaryTo", message: "Укажите верхнюю границу вилки." });
if (!draft.taxBasis) {
issues.push({ field: "taxBasis", message: "Выберите базу суммы: до или после налога." });
}
if (from === "" || to === "") return issues;
const issue = salaryRangeIssue(Number(from), Number(to));
if (issue) issues.push({ field: "salaryTo", message: salaryIssueMessages[issue] });
return issues;
}
function checkTechStack(value: string): InvitationIssue | null {
const items = techStackItems(value);
if (items.length === 0) {
return { field: "techStack", message: "Укажите хотя бы одну технологию." };
}
if (items.length > 30) return { field: "techStack", message: "Не больше 30 технологий." };
if (items.some((item) => item.length > 100)) {
return { field: "techStack", message: "Название технологии не длиннее 100 символов." };
}
const seen = new Set<string>();
for (const item of items) {
const folded = item.toLocaleLowerCase("ru-RU");
if (seen.has(folded)) {
return { field: "techStack", message: `Технология «${item}» указана дважды.` };
}
seen.add(folded);
}
return null;
}
function checkTasks(value: string): InvitationIssue | null {
const lines = taskLines(value);
if (lines.length === 0) return { field: "tasks", message: "Опишите хотя бы одну задачу." };
if (lines.length > 20) return { field: "tasks", message: "Не больше 20 задач." };
if (lines.some((line) => line.length > 300)) {
return { field: "tasks", message: "Каждая задача не длиннее 300 символов." };
}
return null;
}
/** Every issue of a draft in the order of the form; an empty list means it can be sent. */
export function validateInvitationDraft(draft: InvitationDraft): InvitationIssue[] {
const issues: (InvitationIssue | null)[] = [
lineIssue(draft.roleTitle, 200, "Укажите название роли.", "roleTitle"),
draft.specialization ? null : { field: "specialization", message: "Выберите специализацию." },
draft.grade ? null : { field: "grade", message: "Выберите грейд." },
draft.offerType ? null : { field: "offerType", message: "Выберите тип предложения." },
checkTasks(draft.tasks),
draft.team.trim() === ""
? { field: "team", message: "Опишите команду." }
: draft.team.trim().length > 1000
? { field: "team", message: "Не больше 1000 символов." }
: null,
checkTechStack(draft.techStack),
draft.workFormats.length === 0
? { field: "workFormats", message: "Выберите хотя бы один формат работы." }
: null,
];
const officeFormat = draft.workFormats.includes("office") || draft.workFormats.includes("hybrid");
if (draft.location.trim() !== "" || officeFormat) {
issues.push(
lineIssue(draft.location, 100, "Для офиса или гибрида укажите место работы.", "location"),
);
}
issues.push(
draft.channel
? null
: { field: "channel", message: "Выберите способ связи после принятия приглашения." },
);
if (draft.channelDetails.trim() !== "") {
issues.push(lineIssue(draft.channelDetails, 300, "", "channelDetails"));
}
issues.push(...checkSalary(draft));
for (const key of packageItemKeys) {
const item = draft.packageItems[key];
const field = `package.${key}` as const;
if (!item.status) {
issues.push({
field,
message: `${packageItemLabels[key]}: выберите «Предусмотрено» или «Не предусмотрено».`,
});
} else if (item.status === "provided") {
const issue = lineIssue(
item.description,
300,
`${packageItemLabels[key]}: опишите условие.`,
field,
);
issues.push(issue);
}
}
const found = issues.filter((issue): issue is InvitationIssue => issue !== null);
if (found.length > 0) return found;
// Safety net: the generated request schema must accept the built terms.
const parsed = OrganizationInvitationCreate.safeParse({
candidate_handle: `cv1_${"A".repeat(43)}`,
terms: toInvitationTerms(draft),
});
if (parsed.success) return [];
return parsed.error.issues.map((issue) => ({
field: fieldOfPath(issue.path) ?? "roleTitle",
message: "Проверьте это значение.",
}));
}
const termsFields: Readonly<Record<string, InvitationField>> = {
role_title: "roleTitle",
specialization: "specialization",
grade: "grade",
offer_type: "offerType",
tasks: "tasks",
team: "team",
tech_stack: "techStack",
work_formats: "workFormats",
location: "location",
};
function fieldOfTermsPath(path: readonly string[]): InvitationField | null {
const [head, next] = path;
if (head === undefined) return null;
const direct = termsFields[head];
if (direct) return direct;
if (head === "communication_method") {
return next === "details" ? "channelDetails" : "channel";
}
if (head === "salary") {
if (next === "salary_from") return "salaryFrom";
if (next === "tax_basis") return "taxBasis";
return "salaryTo";
}
if (head === "package") {
const key = packageItemKeys.find((item) => item === next);
return key ? `package.${key}` : null;
}
return null;
}
/** Maps a request body path, such as ["terms", "salary", "salary_to"], to its form field. */
export function fieldOfPath(path: readonly PropertyKey[]): InvitationField | null {
const parts = path.map(String);
if (parts[0] === "terms") return fieldOfTermsPath(parts.slice(1));
if (parts[0] === "response_period_days") return "responsePeriodDays";
return null;
}
/** Maps an RFC 6901 pointer of a problem, such as "/terms/tech_stack/1", to its form field. */
export function fieldOfPointer(pointer: string): InvitationField | null {
if (!pointer.startsWith("/")) return null;
const path = pointer
.slice(1)
.split("/")
.map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
return fieldOfPath(path);
}
const serverMessages: Partial<Record<InvitationField, string>> = {
salaryTo:
"Сервер не принял вилку: границы кратны 1 000 рублей, нижняя меньше верхней, ширина от 10% до 40%.",
location: "Сервер требует место работы для офиса или гибрида.",
techStack: "Сервер не принял список технологий: проверьте повторы и длину названий.",
channel: "Сервер не принял способ связи: выберите канал.",
};
/** Field issues of a server problem; pointers outside the terms are left to the caller. */
export function issuesOfProblem(errors: readonly ProblemFieldError[]): InvitationIssue[] {
const issues: InvitationIssue[] = [];
for (const error of errors) {
if (error.in !== "body") continue;
const field = fieldOfPointer(error.pointer);
if (!field || issues.some((issue) => issue.field === field)) continue;
issues.push({
field,
message:
serverMessages[field] ??
(error.code === "required"
? "Сервер считает это поле незаполненным. Заполните его."
: "Сервер не принял это значение. Исправьте его."),
});
}
return issues.sort(
(left, right) =>
invitationFieldOrder.indexOf(left.field) - invitationFieldOrder.indexOf(right.field),
);
}
@@ -0,0 +1,186 @@
.form {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.fields {
display: grid;
gap: var(--space-5);
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.intro,
.hint {
margin: 0;
color: var(--color-text-secondary);
line-height: var(--line-height-body);
}
.issue-summary {
min-width: 0;
padding: var(--space-4);
border: var(--line-strong) solid var(--color-danger);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.issue-summary h2 {
margin: 0;
font-size: var(--font-size-l);
}
.issue-summary ul {
margin: var(--space-3) 0 0;
padding-left: var(--space-5);
}
.group {
display: grid;
gap: var(--space-4);
min-width: 0;
margin: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
}
.group > legend {
max-width: 100%;
padding: 0 var(--space-2);
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
overflow-wrap: anywhere;
}
.row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
gap: var(--space-3);
min-width: 0;
}
.field {
display: grid;
gap: var(--space-2);
align-content: start;
min-width: 0;
}
.field > label {
font-weight: var(--font-weight-bold);
}
.field input,
.field select,
.field textarea {
box-sizing: border-box;
width: 100%;
min-width: 0;
min-height: 2.75rem;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-s);
color: var(--color-text);
background: var(--color-surface);
font: inherit;
}
.field textarea {
resize: vertical;
}
.field :is(input, select, textarea):focus-visible,
.choice input:focus-visible {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
.field [aria-invalid="true"] {
border-color: var(--color-danger);
}
.choices {
display: flex;
flex-wrap: wrap;
gap: var(--space-3) var(--space-5);
align-items: center;
min-width: 0;
margin: 0;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
}
.choices > legend {
padding: 0 var(--space-2);
font-weight: var(--font-weight-bold);
}
.choice {
display: inline-flex;
gap: var(--space-2);
align-items: center;
min-height: 2.75rem;
}
.field-error,
.form-error {
margin: 0;
color: var(--color-danger);
font-weight: var(--font-weight-bold);
line-height: var(--line-height-body);
}
.notice,
.stale {
margin: 0;
padding: var(--space-3);
border-inline-start: var(--line-strong) solid var(--color-accent);
background: var(--color-canvas);
line-height: var(--line-height-body);
}
.preview {
display: grid;
gap: var(--space-4);
min-width: 0;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
align-items: center;
}
.choices > .field,
.choices > .field-error {
flex-basis: 100%;
}
.issue-summary:focus,
.preview:focus,
.notice:focus,
.form-error:focus {
outline: var(--line-strong) solid var(--color-focus-ring);
outline-offset: 2px;
}
@media (width < 42rem) {
.group {
padding: var(--space-3);
}
}
@@ -0,0 +1,711 @@
import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from "react";
import type {
GradeCode,
InvitationCommunicationChannel,
InvitationNeedReference,
InvitationOfferType,
InvitationResponsePeriod,
InvitationTerms,
OrganizationInvitation,
SalaryTaxBasis,
SpecializationCode,
WorkFormat,
} from "../../../shared/api/schemas";
import { Button } from "../../../shared/ui";
import {
communicationChannelCodes,
communicationChannelLabels,
notProvidedLabel,
offerTypeCodes,
offerTypeLabels,
packageItemKeys,
packageItemLabels,
responsePeriodLabel,
responsePeriods,
taxBasisLabels,
type InvitationPackageKey,
} from "../../../entities/invitation";
import {
gradeCodes,
gradeLabels,
specializationCodes,
specializationLabels,
workFormatCodes,
workFormatLabels,
} from "../../../entities/match";
import { toInvitationTerms, type InvitationDraft, type PackageChoice } from "../model/draft";
import { describeSendFailure, type SendFailure } from "../model/failure";
import {
newIdempotencyKey,
runSendCommand,
stableJson,
type SendProgress,
} from "../model/send-command";
import {
invitationFieldOrder,
validateInvitationDraft,
type InvitationField,
type InvitationIssue,
} from "../model/validate";
import styles from "./invitation-form.module.css";
/** Terms of a preview, frozen at the moment the employer asked for it. */
export interface InvitationPreviewSnapshot {
readonly terms: InvitationTerms;
readonly responsePeriodDays: InvitationResponsePeriod;
}
export type InvitationFormProps = {
organizationId: string;
candidateHandle: string;
need: InvitationNeedReference | null;
csrfToken: string;
initialDraft: InvitationDraft;
/** Progress of an earlier attempt, for example a saved draft reopened from the address. */
initialProgress: SendProgress;
/** False once the session that rendered the form is no longer the current one. */
isSessionCurrent: () => boolean;
/** Renders the preview of the given terms; the form never sends anything for it. */
renderPreview: (snapshot: InvitationPreviewSnapshot) => ReactNode;
onDraftSaved: (draft: OrganizationInvitation) => void;
onSent: (invitation: OrganizationInvitation) => void;
onCsrfFailed: () => void;
};
type Notice = { tone: "error" | "info"; text: string };
type FocusTarget = "summary" | "preview" | "notice";
function describedBy(...ids: (string | false | undefined)[]): string | undefined {
const present = ids.filter((id): id is string => typeof id === "string" && id.length > 0);
return present.length > 0 ? present.join(" ") : undefined;
}
function FieldError({ id, message }: { id: string; message: string | undefined }) {
return message ? (
<p className={styles["field-error"]} id={id}>
{message}
</p>
) : null;
}
/**
* The terms of an invitation for one search entry, with a local preview and
* the send command. The form validates like the contract before any request;
* the server answer is still authoritative and its field errors are shown on
* the same fields. A click that repeats an unfinished command reuses its
* Idempotency-Key, and a click while a command runs does nothing.
*/
export function InvitationForm({
organizationId,
candidateHandle,
need,
csrfToken,
initialDraft,
initialProgress,
isSessionCurrent,
renderPreview,
onDraftSaved,
onSent,
onCsrfFailed,
}: InvitationFormProps) {
const prefix = `invitation-${useId().replaceAll(":", "")}`;
const [draft, setDraft] = useState<InvitationDraft>(initialDraft);
const [issues, setIssues] = useState<readonly InvitationIssue[]>([]);
const [summaryVisible, setSummaryVisible] = useState(false);
const [notice, setNotice] = useState<Notice | null>(null);
const [sending, setSending] = useState(false);
const [preview, setPreview] = useState<{
snapshot: InvitationPreviewSnapshot;
source: string;
} | null>(null);
const progress = useRef<SendProgress>(initialProgress);
const inFlight = useRef(false);
const mounted = useRef(false);
const summaryRef = useRef<HTMLDivElement>(null);
const previewRef = useRef<HTMLElement>(null);
const noticeRef = useRef<HTMLParagraphElement>(null);
// A new object per request, so asking for the same target twice moves focus twice.
const [focusRequest, setFocusRequest] = useState<{ target: FocusTarget } | null>(null);
const setFocusTarget = (target: FocusTarget) => setFocusRequest({ target });
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
// Focus moves after the target is rendered: to the issue list, the preview, or the notice.
useEffect(() => {
if (focusRequest?.target === "summary") summaryRef.current?.focus();
if (focusRequest?.target === "preview") previewRef.current?.focus();
if (focusRequest?.target === "notice") noticeRef.current?.focus();
}, [focusRequest]);
const fieldId = (field: InvitationField) => `${prefix}-${field.replace(".", "-")}`;
const errorId = (field: InvitationField) => `${fieldId(field)}-error`;
const issueOf = (field: InvitationField) => issues.find((item) => item.field === field)?.message;
const invalid = (field: InvitationField) => Boolean(issueOf(field));
const previewStale = preview !== null && preview.source !== stableJson(draft);
function change(next: Partial<InvitationDraft>, fields: readonly InvitationField[]): void {
setDraft((current) => ({ ...current, ...next }));
if (fields.length > 0) {
setIssues((current) => current.filter((item) => !fields.includes(item.field)));
}
}
function changePackage(
key: InvitationPackageKey,
next: Partial<InvitationDraft["packageItems"][InvitationPackageKey]>,
) {
change(
{ packageItems: { ...draft.packageItems, [key]: { ...draft.packageItems[key], ...next } } },
[`package.${key}`],
);
}
function toggleFormat(format: WorkFormat, checked: boolean): void {
const formats = checked
? workFormatCodes.filter((code) => code === format || draft.workFormats.includes(code))
: draft.workFormats.filter((code) => code !== format);
change({ workFormats: formats }, ["workFormats", "location"]);
}
function showIssues(found: readonly InvitationIssue[]): void {
const ordered = [...found].sort(
(left, right) =>
invitationFieldOrder.indexOf(left.field) - invitationFieldOrder.indexOf(right.field),
);
setIssues(ordered);
setSummaryVisible(true);
setFocusTarget("summary");
}
function validated(): InvitationPreviewSnapshot | null {
const found = validateInvitationDraft(draft);
if (found.length > 0) {
showIssues(found);
return null;
}
setIssues([]);
setSummaryVisible(false);
return { terms: toInvitationTerms(draft), responsePeriodDays: draft.responsePeriodDays };
}
function showPreview(): void {
if (sending) return;
setNotice(null);
const snapshot = validated();
if (!snapshot) return;
setPreview({ snapshot, source: stableJson(draft) });
setFocusTarget("preview");
}
function applyFailure(failure: SendFailure): void {
if (failure.kind === "fields") {
setNotice({ tone: "error", text: failure.message });
if (failure.issues.length > 0) showIssues(failure.issues);
else setFocusTarget("notice");
return;
}
if (failure.kind === "csrf") onCsrfFailed();
setNotice({ tone: failure.kind === "retry" ? "info" : "error", text: failure.message });
setFocusTarget("notice");
}
async function send(): Promise<void> {
// A click while the command runs neither starts a second request nor
// issues a new key; the running command finishes for both clicks.
if (inFlight.current) return;
setNotice(null);
const snapshot = validated();
if (!snapshot) return;
if (!isSessionCurrent()) {
setNotice({
tone: "error",
text: "Вход изменился. Обновите страницу и проверьте, от чьего имени отправляется приглашение.",
});
setFocusTarget("notice");
return;
}
inFlight.current = true;
setSending(true);
try {
const outcome = await runSendCommand(
{
organizationId,
candidateHandle,
need,
terms: snapshot.terms,
responsePeriodDays: snapshot.responsePeriodDays,
csrfToken,
},
progress.current,
{ newKey: newIdempotencyKey, onDraft: onDraftSaved },
);
progress.current = outcome.progress;
if (!mounted.current) return;
if (outcome.kind === "sent") {
onSent(outcome.invitation);
return;
}
applyFailure(describeSendFailure(outcome.stage, outcome.error));
} finally {
inFlight.current = false;
if (mounted.current) setSending(false);
}
}
function submit(event: FormEvent<HTMLFormElement>): void {
event.preventDefault();
void send();
}
const salaryHintId = `${fieldId("salaryFrom")}-hint`;
const locationHintId = `${fieldId("location")}-hint`;
return (
<form className={styles.form} onSubmit={submit} noValidate aria-describedby={`${prefix}-intro`}>
<p className={styles.intro} id={`${prefix}-intro`}>
Кандидат увидит все условия до решения и до раскрытия контактов. Все поля обязательны, кроме
комментария к способу связи; каждое условие пакета выберите явно.
</p>
{summaryVisible && issues.length > 0 ? (
<div
className={styles["issue-summary"]}
ref={summaryRef}
role="alert"
aria-labelledby={`${prefix}-issues-title`}
tabIndex={-1}
>
<h2 id={`${prefix}-issues-title`}>Проверьте условия приглашения</h2>
<ul>
{issues.map((item) => (
<li key={item.field}>{item.message}</li>
))}
</ul>
</div>
) : null}
<fieldset className={styles.fields} disabled={sending}>
<legend className={styles["visually-hidden"]}>Условия приглашения</legend>
<fieldset className={styles.group}>
<legend>Роль</legend>
<div className={styles.field}>
<label htmlFor={fieldId("roleTitle")}>Название роли</label>
<input
id={fieldId("roleTitle")}
value={draft.roleTitle}
maxLength={200}
aria-invalid={invalid("roleTitle")}
aria-describedby={describedBy(invalid("roleTitle") && errorId("roleTitle"))}
onChange={(event) => change({ roleTitle: event.currentTarget.value }, ["roleTitle"])}
/>
<FieldError id={errorId("roleTitle")} message={issueOf("roleTitle")} />
</div>
<div className={styles.row}>
<div className={styles.field}>
<label htmlFor={fieldId("specialization")}>Специализация</label>
<select
id={fieldId("specialization")}
value={draft.specialization}
aria-invalid={invalid("specialization")}
aria-describedby={describedBy(
invalid("specialization") && errorId("specialization"),
)}
onChange={(event) =>
change({ specialization: event.currentTarget.value as SpecializationCode | "" }, [
"specialization",
])
}
>
<option value="">Не выбрана</option>
{specializationCodes.map((code) => (
<option key={code} value={code}>
{specializationLabels[code]}
</option>
))}
</select>
<FieldError id={errorId("specialization")} message={issueOf("specialization")} />
</div>
<div className={styles.field}>
<label htmlFor={fieldId("grade")}>Грейд</label>
<select
id={fieldId("grade")}
value={draft.grade}
aria-invalid={invalid("grade")}
aria-describedby={describedBy(invalid("grade") && errorId("grade"))}
onChange={(event) =>
change({ grade: event.currentTarget.value as GradeCode | "" }, ["grade"])
}
>
<option value="">Не выбран</option>
{gradeCodes.map((code) => (
<option key={code} value={code}>
{gradeLabels[code]}
</option>
))}
</select>
<FieldError id={errorId("grade")} message={issueOf("grade")} />
</div>
<div className={styles.field}>
<label htmlFor={fieldId("offerType")}>Тип предложения</label>
<select
id={fieldId("offerType")}
value={draft.offerType}
aria-invalid={invalid("offerType")}
aria-describedby={describedBy(invalid("offerType") && errorId("offerType"))}
onChange={(event) =>
change({ offerType: event.currentTarget.value as InvitationOfferType | "" }, [
"offerType",
])
}
>
<option value="">Не выбран</option>
{offerTypeCodes.map((code) => (
<option key={code} value={code}>
{offerTypeLabels[code]}
</option>
))}
</select>
<FieldError id={errorId("offerType")} message={issueOf("offerType")} />
</div>
</div>
</fieldset>
<fieldset className={styles.group}>
<legend>Работа и команда</legend>
<div className={styles.field}>
<label htmlFor={fieldId("tasks")}>Задачи</label>
<p className={styles.hint} id={`${fieldId("tasks")}-hint`}>
По одной задаче в строке, до 20 задач.
</p>
<textarea
id={fieldId("tasks")}
rows={4}
value={draft.tasks}
aria-invalid={invalid("tasks")}
aria-describedby={describedBy(
`${fieldId("tasks")}-hint`,
invalid("tasks") && errorId("tasks"),
)}
onChange={(event) => change({ tasks: event.currentTarget.value }, ["tasks"])}
/>
<FieldError id={errorId("tasks")} message={issueOf("tasks")} />
</div>
<div className={styles.field}>
<label htmlFor={fieldId("team")}>Команда</label>
<p className={styles.hint} id={`${fieldId("team")}-hint`}>
Размер, роли и способ работы. Без персональных данных сотрудников.
</p>
<textarea
id={fieldId("team")}
rows={3}
maxLength={1000}
value={draft.team}
aria-invalid={invalid("team")}
aria-describedby={describedBy(
`${fieldId("team")}-hint`,
invalid("team") && errorId("team"),
)}
onChange={(event) => change({ team: event.currentTarget.value }, ["team"])}
/>
<FieldError id={errorId("team")} message={issueOf("team")} />
</div>
<div className={styles.field}>
<label htmlFor={fieldId("techStack")}>Технологии</label>
<p className={styles.hint} id={`${fieldId("techStack")}-hint`}>
Через запятую, например: Go, PostgreSQL, Kafka. Регистр не различается.
</p>
<input
id={fieldId("techStack")}
value={draft.techStack}
aria-invalid={invalid("techStack")}
aria-describedby={describedBy(
`${fieldId("techStack")}-hint`,
invalid("techStack") && errorId("techStack"),
)}
onChange={(event) => change({ techStack: event.currentTarget.value }, ["techStack"])}
/>
<FieldError id={errorId("techStack")} message={issueOf("techStack")} />
</div>
</fieldset>
<fieldset className={styles.group}>
<legend>Формат и место работы</legend>
<fieldset
className={styles.choices}
aria-describedby={describedBy(invalid("workFormats") && errorId("workFormats"))}
>
<legend>Формат работы</legend>
{workFormatCodes.map((code) => (
<label key={code} className={styles.choice}>
<input
type="checkbox"
checked={draft.workFormats.includes(code)}
aria-invalid={invalid("workFormats")}
onChange={(event) => toggleFormat(code, event.currentTarget.checked)}
/>
{workFormatLabels[code]}
</label>
))}
<FieldError id={errorId("workFormats")} message={issueOf("workFormats")} />
</fieldset>
<div className={styles.field}>
<label htmlFor={fieldId("location")}>Место работы</label>
<p className={styles.hint} id={locationHintId}>
Город или адрес офиса. Обязательно для офиса и гибрида.
</p>
<input
id={fieldId("location")}
value={draft.location}
maxLength={100}
aria-invalid={invalid("location")}
aria-describedby={describedBy(
locationHintId,
invalid("location") && errorId("location"),
)}
onChange={(event) => change({ location: event.currentTarget.value }, ["location"])}
/>
<FieldError id={errorId("location")} message={issueOf("location")} />
</div>
</fieldset>
<fieldset className={styles.group}>
<legend>Способ связи после принятия</legend>
<div className={styles.row}>
<div className={styles.field}>
<label htmlFor={fieldId("channel")}>Канал связи</label>
<select
id={fieldId("channel")}
value={draft.channel}
aria-invalid={invalid("channel")}
aria-describedby={describedBy(invalid("channel") && errorId("channel"))}
onChange={(event) =>
change(
{ channel: event.currentTarget.value as InvitationCommunicationChannel | "" },
["channel"],
)
}
>
<option value="">Не выбран</option>
{communicationChannelCodes.map((code) => (
<option key={code} value={code}>
{communicationChannelLabels[code]}
</option>
))}
</select>
<FieldError id={errorId("channel")} message={issueOf("channel")} />
</div>
<div className={styles.field}>
<label htmlFor={fieldId("channelDetails")}>Комментарий (необязательно)</label>
<input
id={fieldId("channelDetails")}
value={draft.channelDetails}
maxLength={300}
aria-invalid={invalid("channelDetails")}
aria-describedby={describedBy(
invalid("channelDetails") && errorId("channelDetails"),
)}
onChange={(event) =>
change({ channelDetails: event.currentTarget.value }, ["channelDetails"])
}
/>
<FieldError id={errorId("channelDetails")} message={issueOf("channelDetails")} />
</div>
</div>
</fieldset>
<fieldset className={styles.group} aria-describedby={salaryHintId}>
<legend>Зарплатная вилка, рублей в месяц</legend>
<p className={styles.hint} id={salaryHintId}>
Целые рубли с шагом 1 000. Нижняя граница меньше верхней, ширина вилки от 10% до 40% от
середины. База суммы указывается явно.
</p>
<div className={styles.row}>
<div className={styles.field}>
<label htmlFor={fieldId("salaryFrom")}>От, ₽</label>
<input
id={fieldId("salaryFrom")}
type="number"
inputMode="numeric"
min={1000}
step={1000}
value={draft.salaryFrom}
aria-invalid={invalid("salaryFrom")}
aria-describedby={describedBy(invalid("salaryFrom") && errorId("salaryFrom"))}
onChange={(event) =>
change({ salaryFrom: event.currentTarget.value }, ["salaryFrom", "salaryTo"])
}
/>
<FieldError id={errorId("salaryFrom")} message={issueOf("salaryFrom")} />
</div>
<div className={styles.field}>
<label htmlFor={fieldId("salaryTo")}>До, ₽</label>
<input
id={fieldId("salaryTo")}
type="number"
inputMode="numeric"
min={1000}
step={1000}
value={draft.salaryTo}
aria-invalid={invalid("salaryTo")}
aria-describedby={describedBy(invalid("salaryTo") && errorId("salaryTo"))}
onChange={(event) => change({ salaryTo: event.currentTarget.value }, ["salaryTo"])}
/>
<FieldError id={errorId("salaryTo")} message={issueOf("salaryTo")} />
</div>
<div className={styles.field}>
<label htmlFor={fieldId("taxBasis")}>База суммы</label>
<select
id={fieldId("taxBasis")}
value={draft.taxBasis}
aria-invalid={invalid("taxBasis")}
aria-describedby={describedBy(invalid("taxBasis") && errorId("taxBasis"))}
onChange={(event) =>
change({ taxBasis: event.currentTarget.value as SalaryTaxBasis | "" }, [
"taxBasis",
])
}
>
<option value="">Не выбрана</option>
<option value="net">{taxBasisLabels.net}</option>
<option value="gross">{taxBasisLabels.gross}</option>
</select>
<FieldError id={errorId("taxBasis")} message={issueOf("taxBasis")} />
</div>
</div>
</fieldset>
<fieldset className={styles.group}>
<legend>Пакет</legend>
<p className={styles.hint}>
Для каждого условия выберите, предусмотрено ли оно. Пропустить условие нельзя.
</p>
{packageItemKeys.map((key) => {
const field = `package.${key}` as const;
const item = draft.packageItems[key];
const choiceName = `${fieldId(field)}-status`;
return (
<fieldset
key={key}
className={styles.choices}
aria-describedby={describedBy(invalid(field) && errorId(field))}
>
<legend>{packageItemLabels[key]}</legend>
{(["provided", "not_provided"] as const).map((status) => (
<label key={status} className={styles.choice}>
<input
type="radio"
name={choiceName}
value={status}
checked={item.status === status}
aria-invalid={invalid(field)}
onChange={() => changePackage(key, { status: status as PackageChoice })}
/>
{status === "provided" ? "Предусмотрено" : notProvidedLabel}
</label>
))}
{item.status === "provided" ? (
<div className={styles.field}>
<label htmlFor={fieldId(field)}>{`${packageItemLabels[key]}: описание`}</label>
<input
id={fieldId(field)}
value={item.description}
maxLength={300}
aria-invalid={invalid(field)}
aria-describedby={describedBy(invalid(field) && errorId(field))}
onChange={(event) =>
changePackage(key, { description: event.currentTarget.value })
}
/>
</div>
) : null}
<FieldError id={errorId(field)} message={issueOf(field)} />
</fieldset>
);
})}
</fieldset>
<div className={styles.field}>
<label htmlFor={fieldId("responsePeriodDays")}>Срок ответа кандидата</label>
<p className={styles.hint} id={`${fieldId("responsePeriodDays")}-hint`}>
Срок начинается с момента доставки приглашения.
</p>
<select
id={fieldId("responsePeriodDays")}
value={draft.responsePeriodDays}
aria-invalid={invalid("responsePeriodDays")}
aria-describedby={describedBy(
`${fieldId("responsePeriodDays")}-hint`,
invalid("responsePeriodDays") && errorId("responsePeriodDays"),
)}
onChange={(event) =>
change(
{
responsePeriodDays: Number(event.currentTarget.value) as InvitationResponsePeriod,
},
["responsePeriodDays"],
)
}
>
{responsePeriods.map((days) => (
<option key={days} value={days}>
{responsePeriodLabel(days)}
</option>
))}
</select>
<FieldError id={errorId("responsePeriodDays")} message={issueOf("responsePeriodDays")} />
</div>
</fieldset>
{preview ? (
<section
ref={previewRef}
className={styles.preview}
tabIndex={-1}
aria-label="Предпросмотр приглашения"
>
{previewStale ? (
<p className={styles.stale} role="status">
Условия изменены после предпросмотра. Нажмите «Обновить предпросмотр», чтобы увидеть
текущие.
</p>
) : null}
{renderPreview(preview.snapshot)}
</section>
) : null}
{notice ? (
<p
ref={noticeRef}
className={notice.tone === "error" ? styles["form-error"] : styles.notice}
role={notice.tone === "error" ? "alert" : "status"}
tabIndex={-1}
>
{notice.text}
</p>
) : null}
{sending ? (
<p className={styles.notice} role="status">
Отправляем приглашение...
</p>
) : null}
<div className={styles.actions}>
<Button variant="secondary" isBusy={sending} onClick={showPreview}>
{preview ? "Обновить предпросмотр" : "Показать предпросмотр"}
</Button>
<Button type="submit" isBusy={sending}>
Отправить приглашение
</Button>
</div>
<p className={styles.hint}>
Предпросмотр ничего не отправляет. Отправка создает черновик и сразу доставляет его в
кабинет кандидата; запускается срок ответа.
</p>
</form>
);
}