feat(invitations): add the candidate invitation inbox with C4 acceptance and decline

This commit is contained in:
shira committed 2026-10-09 20:30:35 +03:00
1 parent 12a7213d4a
commit a856066316
54 files changed
+3897 -136

No files matched your search

+15 -3
View File
@@ -289,8 +289,20 @@ describe("product readiness", () => {
});
it("labels the remaining cabinet scaffolds as placeholders", async () => {
for (const path of ["/candidate/invitations", "/employer/invitations"]) {
expect(await renderHtml(path)).toContain("Экран будет реализован в одной из следующих задач");
}
expect(await renderHtml("/employer/invitations")).toContain(
"Экран будет реализован в одной из следующих задач",
);
});
it("routes the candidate inbox and one invitation to their own screens, not placeholders", async () => {
const inbox = await renderHtml("/candidate/invitations");
expect(inbox).toMatch(/<h1[^>]*>Приглашения<\/h1>/);
expect(inbox).not.toContain("Экран будет реализован в одной из следующих задач");
const detail = await renderHtml(
`/candidate/invitations/${"0".repeat(8)}-0000-4000-8000-000000000000`,
);
expect(detail).toContain("Открываем приглашение...");
expect(detail).not.toContain("Экран будет реализован в одной из следующих задач");
});
});
+7 -2
View File
@@ -2,6 +2,10 @@ import { redirect, type RouteObject } from "react-router-dom";
import { AssessmentAttemptPage, AssessmentPage } from "../../pages/assessment";
import { AssessmentResultPage, AssessmentResultsPage } from "../../pages/assessment-result";
import { LoginPage, RegisterPage, VerifyEmailPage } from "../../pages/auth";
import {
CandidateInvitationPage,
CandidateInvitationsPage,
} from "../../pages/candidate-invitations";
import { CandidateOnboardingPage } from "../../pages/candidate-onboarding";
import { CompanyPage } from "../../pages/company";
import { PrivacyPage } from "../../pages/privacy";
@@ -80,9 +84,10 @@ export const routes: RouteObject[] = [
},
{ path: paths.candidate.results, element: <AssessmentResultsPage /> },
{ path: `${paths.candidate.results}/:attemptId`, element: <AssessmentResultPage /> },
{ path: paths.candidate.invitations, element: <CandidateInvitationsPage /> },
{
path: paths.candidate.invitations,
element: <PlaceholderPage screen="candidateInvitations" />,
path: `${paths.candidate.invitations}/:invitationId`,
element: <CandidateInvitationPage />,
},
{ path: paths.candidate.notifications, element: <CandidateNotificationsPage /> },
{
@@ -0,0 +1,217 @@
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { ApiRequestError } from "../../../shared/api";
import { candidateInvitationFixture, candidateInvitationId } from "../testing";
import {
acceptCandidateInvitation,
declineCandidateInvitation,
listCandidateInvitations,
readCandidateInvitation,
viewCandidateInvitation,
} from "./candidate-invitations";
const base = "http://localhost/api/v1/me/invitations";
const csrfToken = "A".repeat(43);
const idempotencyKey = "11111111-2222-4333-8444-555555555555";
const server = setupServer();
beforeAll(() => server.listen({ onUnhandledFrame: "error" }));
beforeEach(() => {
// The browser client uses same-origin paths; Node needs an origin.
const realFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
realFetch(new URL(input, "http://localhost"), init),
);
});
afterEach(() => {
vi.unstubAllGlobals();
server.resetHandlers();
});
afterAll(() => server.close());
const problemHeaders = { "Content-Type": "application/problem+json" };
describe("candidate invitation transport", () => {
it("reads the inbox page with its cursor and parses it with the contract", async () => {
let cursor: string | null = null;
server.use(
http.get(base, ({ request }) => {
cursor = new URL(request.url).searchParams.get("cursor");
return HttpResponse.json({
items: [
{
id: candidateInvitationId,
organization: { id: "0199b4f2-7c1e-7d3a-9f00-aabbccdd3201", name: "Северный ветер" },
state: "delivered",
expiry_reason: null,
version: 1,
terms_version: 1,
role_title: "Middle Go-разработчик",
salary: {
salary_from: 100000,
salary_to: 140000,
currency: "RUB",
period: "month",
tax_basis: "net",
},
work_formats: ["remote"],
response_deadline_at: "2099-10-16T10:00:00Z",
delivered_at: "2026-10-09T10:00:00Z",
viewed_at: null,
updated_at: "2026-10-09T10:00:00Z",
},
],
page: { has_more: true, next_cursor: "next-1" },
});
}),
);
const list = await listCandidateInvitations({ cursor: "first-1" });
expect(cursor).toBe("first-1");
expect(list.items[0]?.role_title).toBe("Middle Go-разработчик");
expect(list.page).toEqual({ has_more: true, next_cursor: "next-1" });
});
it("refuses a response that does not match the contract instead of showing it", async () => {
server.use(http.get(base, () => HttpResponse.json({ items: [{ id: "not-an-invitation" }] })));
const failure = await listCandidateInvitations().catch((error: unknown) => error);
expect(failure).toBeInstanceOf(ApiRequestError);
expect((failure as ApiRequestError).code).toBe("invalid_response");
});
it("reads the terms without any side effect and parses the full invitation", async () => {
const methods: string[] = [];
server.use(
http.get(`${base}/${candidateInvitationId}`, ({ request }) => {
methods.push(request.method);
return HttpResponse.json(candidateInvitationFixture());
}),
);
const invitation = await readCandidateInvitation(candidateInvitationId);
expect(methods).toEqual(["GET"]);
expect(invitation.contact_consent?.available_fields).toEqual(["full_name", "email", "phone"]);
});
it("records a view with the CSRF token and no Idempotency-Key", async () => {
const seen: { csrf: string | null; key: string | null; method: string }[] = [];
server.use(
http.post(`${base}/${candidateInvitationId}/view`, ({ request }) => {
seen.push({
csrf: request.headers.get("X-CSRF-Token"),
key: request.headers.get("Idempotency-Key"),
method: request.method,
});
return HttpResponse.json(candidateInvitationFixture({ state: "viewed", version: 2 }));
}),
);
const viewed = await viewCandidateInvitation(candidateInvitationId, { csrfToken });
expect(viewed.state).toBe("viewed");
expect(seen).toEqual([{ csrf: csrfToken, key: null, method: "POST" }]);
});
it("sends the accepted fields, the versions, and the key, and returns the grant", async () => {
let body: unknown = null;
let key: string | null = null;
server.use(
http.post(`${base}/${candidateInvitationId}/accept`, async ({ request }) => {
key = request.headers.get("Idempotency-Key");
body = await request.json();
return HttpResponse.json(
candidateInvitationFixture({
state: "accepted",
version: 2,
contact_grant: {
id: "0199b4f2-7c1e-7d3a-9f00-aabbccdd3301",
fields: ["email"],
status: "active",
readable: true,
blocked_by: null,
terms_version: 1,
consent_text_version: "c4-2026-10",
granted_at: "2026-10-10T09:00:00Z",
revoked_at: null,
revocation_reason: null,
},
}),
);
}),
);
const accepted = await acceptCandidateInvitation({
invitationId: candidateInvitationId,
csrfToken,
idempotencyKey,
body: {
expected_version: 1,
terms_version: 1,
consent_c4: { text_version: "c4-2026-10", accepted: true, fields: ["email"] },
},
});
expect(key).toBe(idempotencyKey);
expect(body).toEqual({
expected_version: 1,
terms_version: 1,
consent_c4: { text_version: "c4-2026-10", accepted: true, fields: ["email"] },
});
expect(accepted.contact_grant?.fields).toEqual(["email"]);
});
it("surfaces a stale terms version as the problem code the contract names", async () => {
server.use(
http.post(`${base}/${candidateInvitationId}/accept`, () =>
HttpResponse.json(
{
type: "urn:lincodex:problem:version_conflict",
title: "Version conflict",
status: 412,
code: "version_conflict",
},
{ status: 412, headers: problemHeaders },
),
),
);
const failure = await acceptCandidateInvitation({
invitationId: candidateInvitationId,
csrfToken,
idempotencyKey,
body: {
expected_version: 1,
terms_version: 1,
consent_c4: { text_version: "c4-2026-10", accepted: true, fields: ["phone"] },
},
}).catch((error: unknown) => error);
expect(failure).toBeInstanceOf(ApiRequestError);
expect(failure).toMatchObject({ status: 412, code: "version_conflict" });
});
it("sends a decline with its reason and without a comment when none was written", async () => {
let body: unknown = null;
server.use(
http.post(`${base}/${candidateInvitationId}/decline`, async ({ request }) => {
body = await request.json();
return HttpResponse.json(candidateInvitationFixture({ state: "declined", version: 2 }));
}),
);
const declined = await declineCandidateInvitation({
invitationId: candidateInvitationId,
csrfToken,
idempotencyKey,
body: { expected_version: 1, reason: "other" },
});
expect(body).toEqual({ expected_version: 1, reason: "other" });
expect(declined.state).toBe("declined");
});
});
@@ -0,0 +1,131 @@
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
import {
acceptMyInvitation,
declineMyInvitation,
getGetMyInvitationQueryKey,
getListMyInvitationsQueryKey,
getMyInvitation,
listMyInvitations,
viewMyInvitation,
} from "../../../shared/api/endpoints/invitation/invitation";
import {
CandidateInvitation as candidateInvitationSchema,
CandidateInvitationList as candidateInvitationListSchema,
type CandidateInvitation,
type CandidateInvitationList,
type InvitationAcceptance,
type InvitationDeclineRequest,
} from "../../../shared/api/schemas";
// Transport adapters of the candidate side of an invitation. The generated
// client does not check response bodies, so every adapter parses the response
// with the generated schema: a body that does not match the contract is an
// invalid response, never a shown invitation.
function invalidResponse(): ApiRequestError {
return new ApiRequestError({
status: 200,
code: invalidResponseCode,
title: "The response does not match the API contract.",
});
}
function parseInvitation(value: unknown): CandidateInvitation {
const parsed = candidateInvitationSchema.safeParse(value);
if (!parsed.success) throw invalidResponse();
return parsed.data;
}
function parseInvitationList(value: unknown): CandidateInvitationList {
const parsed = candidateInvitationListSchema.safeParse(value);
if (!parsed.success) throw invalidResponse();
return parsed.data;
}
type CommandOptions = {
csrfToken: string;
signal?: AbortSignal | undefined;
};
function commandRequest(csrfToken: string, signal: AbortSignal | undefined): RequestInit {
return { headers: { "X-CSRF-Token": csrfToken }, ...(signal ? { signal } : {}) };
}
/** One page of the candidate's inbox, newest first; the cursor comes only from the previous page. */
export async function listCandidateInvitations(
options: { cursor?: string | undefined; signal?: AbortSignal | undefined } = {},
): Promise<CandidateInvitationList> {
const params = options.cursor === undefined ? {} : { cursor: options.cursor };
return parseInvitationList(
await listMyInvitations(params, options.signal ? { signal: options.signal } : {}),
);
}
/** Reads the terms of one invitation. A read never records a view and never answers it. */
export async function readCandidateInvitation(
invitationId: string,
signal: AbortSignal | undefined = undefined,
): Promise<CandidateInvitation> {
return parseInvitation(await getMyInvitation(invitationId, signal ? { signal } : {}));
}
/**
* Records that the candidate opened the terms. The server keeps the first
* view and answers with the current invitation on every repeat, so the call
* needs no Idempotency-Key.
*/
export async function viewCandidateInvitation(
invitationId: string,
options: CommandOptions,
): Promise<CandidateInvitation> {
return parseInvitation(
await viewMyInvitation(invitationId, commandRequest(options.csrfToken, options.signal)),
);
}
/** Accepts the terms version the candidate read and discloses the chosen contact kinds. */
export async function acceptCandidateInvitation(
options: CommandOptions & {
invitationId: string;
body: InvitationAcceptance;
idempotencyKey: string;
},
): Promise<CandidateInvitation> {
return parseInvitation(
await acceptMyInvitation(
options.invitationId,
options.body,
{ "Idempotency-Key": options.idempotencyKey },
commandRequest(options.csrfToken, options.signal),
),
);
}
/** Declines the invitation with a structured reason and an optional comment. */
export async function declineCandidateInvitation(
options: CommandOptions & {
invitationId: string;
body: InvitationDeclineRequest;
idempotencyKey: string;
},
): Promise<CandidateInvitation> {
return parseInvitation(
await declineMyInvitation(
options.invitationId,
options.body,
{ "Idempotency-Key": options.idempotencyKey },
commandRequest(options.csrfToken, options.signal),
),
);
}
/**
* Candidate reads are separate for each signed-in account, so a response for
* one account never fills another account's cache.
*/
export const candidateInvitationQueryKeys = {
/** Every inbox query of the account; invalidating it refreshes all pages. */
inbox: (accountId: string) => [...getListMyInvitationsQueryKey(), accountId] as const,
detail: (accountId: string, invitationId: string) =>
[...getGetMyInvitationQueryKey(invitationId), accountId] as const,
};
+30 -4
View File
@@ -1,7 +1,8 @@
// Public API of the invitation entity: contract-checked transport adapters
// of the organization side, the labels and formatting of terms and states,
// and the client mirror of the salary range rules. The slice holds no
// server state; features own the commands and the query cache owns reads.
// Public API of the invitation entity: contract-checked transport adapters of
// both sides, the labels and formatting of terms and states, the candidate's
// answer rules, and the client mirror of the salary range rules. The slice
// holds no server state; features own the commands and the query cache owns
// reads.
export {
createInvitationDraft,
@@ -10,7 +11,32 @@ export {
sendInvitationDraft,
updateInvitationDraft,
} from "./api/organization-invitations";
export {
acceptCandidateInvitation,
candidateInvitationQueryKeys,
declineCandidateInvitation,
listCandidateInvitations,
readCandidateInvitation,
viewCandidateInvitation,
} from "./api/candidate-invitations";
export { formatRubles, formatSalaryRange, formatServerMoment } from "./model/format";
export {
candidateInvitationStateLabels,
contactKindCodes,
contactKindLabels,
declineReasonCodes,
declineReasonLabels,
orderedContactKinds,
} from "./model/candidate-labels";
export { candidateStatusLabel, isAnswerable, newerInvitation } from "./model/candidate-standing";
export { bindKey, newIdempotencyKey, type KeyBinding } from "./model/command-key";
export { useServerNow } from "./model/server-now";
export {
describeResponseFailure,
type ResponseCommand,
type ResponseFailure,
type ResponseFailureKind,
} from "./model/response-failure";
export {
communicationChannelCodes,
communicationChannelLabels,
@@ -0,0 +1,91 @@
import type {
CandidateInvitation,
ContactConsentOffer,
ContactGrant,
InvitationTerms,
} from "../../../shared/api/schemas";
// Synthetic candidate-side invitation shaped by the contract. The fixtures are
// test inputs; they do not show what the backend returns for a real account.
export const candidateAccountId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd3001";
export const candidateInvitationId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd3101";
export const candidateOrganizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd3201";
export const candidateGrantId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd3301";
/** A deadline far in the future, so the fixture stays open for every test run. */
export const openDeadline = "2099-10-16T10:00:00Z";
/** A deadline in the past, so the fixture reads as expired by the clock. */
export const passedDeadline = "2020-10-16T10:00:00Z";
export const candidateTerms: InvitationTerms = {
role_title: "Middle Go-разработчик в команду платежей",
specialization: "backend",
grade: "middle",
offer_type: "full_time",
tasks: ["Развивать сервис выплат", "Перевести отчеты на события"],
team: "Пять бэкенд-разработчиков\nи QA-инженер",
tech_stack: ["Go", "PostgreSQL"],
work_formats: ["remote", "hybrid"],
location: "Москва",
communication_method: { channel: "video_call", details: "Созвон с тимлидом" },
salary: {
salary_from: 100000,
salary_to: 140000,
currency: "RUB",
period: "month",
tax_basis: "net",
},
package: {
bonus: { status: "provided", description: "Квартальная премия до 20%" },
equipment: { status: "provided", description: "Ноутбук и монитор" },
training: { status: "not_provided" },
health_insurance: { status: "not_provided" },
},
};
/** The consent C4 offer: the text and the kinds the profile holds, nothing preselected. */
export const contactConsentOffer: ContactConsentOffer = {
text: {
text_version: "c4-2026-10",
text: "Я согласен передать компании «Северный ветер» отмеченные контакты из моего профиля.\n\nСогласие относится только к этому приглашению.",
},
available_fields: ["full_name", "email", "phone"],
};
export const emailOnlyGrant: ContactGrant = {
id: candidateGrantId,
fields: ["email"],
status: "active",
readable: true,
blocked_by: null,
terms_version: 1,
consent_text_version: "c4-2026-10",
granted_at: "2026-10-10T09:00:00Z",
revoked_at: null,
revocation_reason: null,
};
/** The invitation as the candidate reads it; the fields can be overridden per test. */
export function candidateInvitationFixture(
overrides: Partial<CandidateInvitation> = {},
): CandidateInvitation {
return {
id: candidateInvitationId,
organization: { id: candidateOrganizationId, name: "Северный ветер" },
state: "delivered",
expiry_reason: null,
version: 1,
terms_version: 1,
terms: candidateTerms,
response_deadline_at: openDeadline,
delivered_at: "2026-10-09T10:00:00Z",
viewed_at: null,
responded_at: null,
updated_at: "2026-10-09T10:00:00Z",
contact_consent: contactConsentOffer,
decline: null,
contact_grant: null,
...overrides,
};
}
@@ -0,0 +1,70 @@
import type {
ContactFieldKind,
InvitationDeclineReason,
InvitationState,
} from "../../../shared/api/schemas";
// Candidate-facing wording. The candidate reads their own state and reasons,
// so these labels say "you" where the organization side says "candidate".
/** Decline reasons in the order the form offers them; "other" stays last. */
export const declineReasonCodes: readonly InvitationDeclineReason[] = [
"salary",
"tasks",
"stack",
"work_format",
"package",
"company",
"not_looking",
"other_offer",
"other",
];
export const declineReasonLabels: Readonly<Record<InvitationDeclineReason, string>> = {
salary: "Вилка зарплаты не подходит",
tasks: "Роль или задачи не подходят",
stack: "Технологии не подходят",
work_format: "Формат работы или место не подходят",
package: "Пакет условий не подходит",
company: "Компания или сфера не подходят",
not_looking: "Сейчас я не ищу работу",
other_offer: "Я принял другое предложение",
other: "Другая причина",
};
/** Contact kinds in the order of the contract's ContactFieldKind. */
export const contactKindCodes: readonly ContactFieldKind[] = [
"full_name",
"email",
"phone",
"telegram",
];
export const contactKindLabels: Readonly<Record<ContactFieldKind, string>> = {
full_name: "ФИО",
email: "Электронная почта",
phone: "Телефон",
telegram: "Telegram",
};
/** The kinds in contract order, so every list of them reads the same way. */
export function orderedContactKinds(kinds: readonly ContactFieldKind[]): ContactFieldKind[] {
return contactKindCodes.filter((code) => kinds.includes(code));
}
export const candidateInvitationStateLabels: Readonly<Record<InvitationState, string>> = {
draft: "Черновик",
delivered: "Ждет вашего решения",
viewed: "Вы открыли условия",
counter: "Встречное предложение",
accepted: "Принято",
interview_scheduled: "Назначено интервью",
interviewed: "Интервью проведено",
negotiation: "Переговоры",
terms_agreed: "Условия согласованы",
no_deal: "Без сделки",
declined: "Вы отклонили приглашение",
expired: "Срок ответа истек",
withdrawn: "Компания отозвала приглашение",
cancelled_by_candidate: "Вы отменили участие",
};
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import { candidateInvitationFixture, openDeadline, passedDeadline } from "../testing";
import { candidateStatusLabel, isAnswerable, newerInvitation } from "./candidate-standing";
const beforeDeadline = Date.parse("2026-10-10T10:00:00Z");
const deadlineMs = Date.parse(openDeadline);
const afterDeadline = deadlineMs + 1_000;
describe("candidate answer window", () => {
it.each(["delivered", "viewed"] as const)(
"is open for a %s invitation before the deadline",
(state) => {
expect(isAnswerable({ state, response_deadline_at: openDeadline }, beforeDeadline)).toBe(
true,
);
},
);
it("closes at the deadline itself and after it, by the server clock", () => {
expect(
isAnswerable({ state: "delivered", response_deadline_at: openDeadline }, deadlineMs),
).toBe(false);
expect(
isAnswerable({ state: "delivered", response_deadline_at: openDeadline }, afterDeadline),
).toBe(false);
});
it.each(["accepted", "declined", "expired", "withdrawn", "cancelled_by_candidate"] as const)(
"is closed for a %s invitation whatever the clock says",
(state) => {
expect(isAnswerable({ state, response_deadline_at: openDeadline }, beforeDeadline)).toBe(
false,
);
},
);
it("reads a delivered invitation past its deadline as expired", () => {
const invitation = candidateInvitationFixture({ response_deadline_at: passedDeadline });
expect(candidateStatusLabel(invitation, beforeDeadline)).toBe("Срок ответа истек");
});
it("names the stored state of a closed invitation", () => {
const invitation = candidateInvitationFixture({ state: "declined" });
expect(candidateStatusLabel(invitation, beforeDeadline)).toBe("Вы отклонили приглашение");
});
});
describe("newer invitation", () => {
it("keeps the higher version, so a late answer never overwrites a newer one", () => {
const accepted = candidateInvitationFixture({ state: "accepted", version: 3 });
const viewed = candidateInvitationFixture({ state: "viewed", version: 2 });
expect(newerInvitation(accepted, viewed)).toBe(accepted);
expect(newerInvitation(viewed, accepted)).toBe(accepted);
});
it("takes the incoming invitation when nothing is cached or the id differs", () => {
const incoming = candidateInvitationFixture({ version: 2 });
expect(newerInvitation(undefined, incoming)).toBe(incoming);
const other = candidateInvitationFixture({
id: "0199b4f2-7c1e-7d3a-9f00-aabbccdd3999",
version: 9,
});
expect(newerInvitation(other, incoming)).toBe(incoming);
});
});
@@ -0,0 +1,46 @@
import type { CandidateInvitation } from "../../../shared/api/schemas";
import { candidateInvitationStateLabels } from "./candidate-labels";
/**
* Whether the candidate can still answer: the state allows an answer and the
* deadline has not passed. The clock is the server's, so a device clock that
* is minutes off does not open or close the answer window.
*/
export function isAnswerable(
invitation: Pick<CandidateInvitation, "state" | "response_deadline_at">,
serverNowMs: number,
): boolean {
if (invitation.state !== "delivered" && invitation.state !== "viewed") return false;
const deadline = Date.parse(invitation.response_deadline_at);
return Number.isFinite(deadline) && deadline > serverNowMs;
}
/**
* The status line for the candidate. A delivered or viewed invitation whose
* deadline has passed reads as expired even before the server applies the
* expiry on the next read.
*/
export function candidateStatusLabel(
invitation: Pick<CandidateInvitation, "state" | "response_deadline_at">,
serverNowMs: number,
): string {
if (
(invitation.state === "delivered" || invitation.state === "viewed") &&
!isAnswerable(invitation, serverNowMs)
) {
return candidateInvitationStateLabels.expired;
}
return candidateInvitationStateLabels[invitation.state];
}
/**
* Keeps the newer of two reads of one invitation. Every command answers with
* the invitation after it, and a late answer must never overwrite a newer one.
*/
export function newerInvitation(
current: CandidateInvitation | undefined,
incoming: CandidateInvitation,
): CandidateInvitation {
if (!current || current.id !== incoming.id) return incoming;
return current.version > incoming.version ? current : incoming;
}
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vitest";
import { bindKey, newIdempotencyKey } from "./command-key";
describe("idempotency keys of an answer", () => {
it("keeps the key of an unchanged request, so a retry replays the same answer", () => {
const first = bindKey(null, "invitation:body");
expect(bindKey(first, "invitation:body")).toBe(first);
});
it("issues a new key when the request changes", () => {
const first = bindKey(null, "invitation:email");
const second = bindKey(first, "invitation:email,phone");
expect(second.fingerprint).toBe("invitation:email,phone");
expect(second.key).not.toBe(first.key);
});
it("issues random keys that the contract accepts", () => {
const key = newIdempotencyKey();
expect(key).toMatch(/^[A-Za-z0-9._:-]{1,255}$/);
expect(newIdempotencyKey()).not.toBe(key);
});
});
@@ -0,0 +1,25 @@
// Idempotency bookkeeping of a candidate's answer. The key belongs to the
// request it protects: a repeated click or a retry after a lost response
// sends the same key with the same body, so the server replays the stored
// answer instead of recording a second one. A changed body gets a new key,
// because the server would answer 422 for the old key with another body.
/** An Idempotency-Key and the request fingerprint it was issued for. */
export interface KeyBinding {
readonly fingerprint: string;
readonly key: string;
}
export function newIdempotencyKey(): string {
if (typeof crypto === "undefined" || typeof crypto.randomUUID !== "function") {
throw new Error("Secure random key generation is unavailable.");
}
return crypto.randomUUID();
}
/** Keeps the previous key while the fingerprint stays the same; otherwise issues a new one. */
export function bindKey(previous: KeyBinding | null, fingerprint: string): KeyBinding {
return previous?.fingerprint === fingerprint
? previous
: { fingerprint, key: newIdempotencyKey() };
}
@@ -0,0 +1,76 @@
import { describe, expect, it } from "vitest";
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
import { describeResponseFailure } from "./response-failure";
function problem(status: number, code: string, pointer?: string): ApiRequestError {
return new ApiRequestError({
status,
code: code as ApiRequestError["code"],
title: "Problem",
fieldErrors: pointer ? [{ in: "body", pointer, code: "invalid", message: "Invalid." }] : [],
});
}
describe("describing a failed answer", () => {
it("treats a stale version as a reason to read the invitation again, for both 412 and 409", () => {
for (const error of [problem(412, "version_conflict"), problem(409, "version_conflict")]) {
const failure = describeResponseFailure("accept", error);
expect(failure).toMatchObject({ kind: "stale-terms", refresh: true });
expect(failure.message).toContain("Приглашение изменилось");
}
});
it("shows the final state for a state conflict instead of a retry", () => {
expect(describeResponseFailure("accept", problem(409, "state_conflict"))).toMatchObject({
kind: "final-state",
refresh: true,
});
});
it("keeps the same key for an outcome that is unknown or temporary", () => {
const retryable = [
new ApiRequestError({ status: 0, code: "network_error", title: "" }),
problem(500, "internal"),
new ApiRequestError({ status: 200, code: invalidResponseCode, title: "" }),
problem(409, "idempotency_in_progress"),
problem(429, "rate_limited"),
new TypeError("not an API error"),
];
for (const error of retryable) {
expect(describeResponseFailure("decline", error)).toMatchObject({
kind: "retry",
refresh: false,
});
}
});
it("sends a consent pointer to the offer, and any other validation error to the page", () => {
expect(
describeResponseFailure("accept", problem(400, "validation_failed", "/consent_c4/fields/1")),
).toMatchObject({ kind: "consent", refresh: true });
expect(
describeResponseFailure("accept", problem(400, "validation_failed", "/terms/salary")),
).toMatchObject({ kind: "blocked", refresh: true });
});
it("separates the session, CSRF, and missing-invitation cases", () => {
expect(describeResponseFailure("accept", problem(403, "csrf_check_failed"))).toMatchObject({
kind: "csrf",
refresh: true,
});
expect(describeResponseFailure("accept", problem(403, "forbidden"))).toMatchObject({
kind: "access",
refresh: true,
});
expect(describeResponseFailure("decline", problem(404, "not_found"))).toMatchObject({
kind: "not-found",
refresh: true,
});
});
it("never shows server text: the messages are the product's own", () => {
const failure = describeResponseFailure("decline", problem(500, "internal"));
expect(failure.message).toContain("Сервер не подтвердил результат");
expect(failure.message).toContain("тем же ключом");
});
});
@@ -0,0 +1,119 @@
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
/** The candidate's answers that can fail: accepting with the consent C4, or declining. */
export type ResponseCommand = "accept" | "decline";
/**
* What the candidate sees after a failed answer.
*
* - stale-terms: the terms version or the version of the invitation changed
* (412, or 409 with `version_conflict`); the new version must be read and
* decided again.
* - final-state: the invitation has ended (409 `state_conflict`), for example
* it expired at the deadline; the final state is shown instead of a retry.
* - retry: the outcome is unknown or temporary; the same control repeats the
* command with the same Idempotency-Key.
* - consent: the text version or a selected kind no longer matches the profile
* (400 with a `/consent_c4` pointer); the offer is read again.
* - access, csrf, not-found, blocked: the page reads the invitation again or
* explains why the answer cannot be sent.
*/
export type ResponseFailureKind =
"stale-terms" | "final-state" | "retry" | "consent" | "access" | "csrf" | "not-found" | "blocked";
export interface ResponseFailure {
readonly kind: ResponseFailureKind;
readonly message: string;
/** Whether the page reads the invitation again before the next decision. */
readonly refresh: boolean;
}
const sameKeyHint = "Повторите нажатие: запрос уйдет с тем же ключом и не создаст второй ответ.";
/** Describes a failed answer without showing any server text or value. */
export function describeResponseFailure(command: ResponseCommand, error: unknown): ResponseFailure {
if (!(error instanceof ApiRequestError)) {
return { kind: "retry", message: `Не удалось отправить ответ. ${sameKeyHint}`, refresh: false };
}
if (error.status === 0 || error.status >= 500 || error.code === invalidResponseCode) {
return {
kind: "retry",
message: `Сервер не подтвердил результат. ${sameKeyHint}`,
refresh: false,
};
}
if (error.status === 412 || (error.status === 409 && error.code === "version_conflict")) {
return {
kind: "stale-terms",
message:
command === "accept"
? "Приглашение изменилось после вашего прочтения. Мы загрузили актуальную версию: проверьте условия и выбор контактов и подтвердите согласие заново."
: "Приглашение изменилось в другом окне. Мы загрузили его текущую версию: проверьте ответ и отправьте его снова.",
refresh: true,
};
}
if (error.status === 409 && error.code === "state_conflict") {
return {
kind: "final-state",
message:
"Приглашение уже завершилось, поэтому ответ не сохранен. Мы обновили его состояние ниже.",
refresh: true,
};
}
if (error.status === 409 && error.code === "idempotency_in_progress") {
return {
kind: "retry",
message: `Предыдущий ответ еще обрабатывается. Подождите несколько секунд. ${sameKeyHint}`,
refresh: false,
};
}
if (error.status === 403 && error.code === "csrf_check_failed") {
return {
kind: "csrf",
message: "Проверка входа устарела. Мы обновили ее; повторите ответ.",
refresh: true,
};
}
if (error.status === 401 || error.status === 403) {
return {
kind: "access",
message:
"Нет доступа к этому приглашению. Обновите страницу; если вход истек, войдите снова.",
refresh: true,
};
}
if (error.status === 404) {
return {
kind: "not-found",
message: "Приглашение не найдено. Возможно, оно уже недоступно.",
refresh: true,
};
}
if (error.status === 400) {
if (error.fieldErrors.some((field) => field.pointer.startsWith("/consent_c4"))) {
return {
kind: "consent",
message:
"Текст согласия или список контактов изменились. Мы обновили приглашение: проверьте выбор и подтвердите его заново.",
refresh: true,
};
}
return {
kind: "blocked",
message: "Сервер не принял ответ. Обновите страницу и проверьте приглашение.",
refresh: true,
};
}
if (error.status === 429) {
return {
kind: "retry",
message: `Слишком много запросов. Подождите немного. ${sameKeyHint}`,
refresh: false,
};
}
return {
kind: "blocked",
message: "Сервер отклонил ответ. Обновите страницу и проверьте состояние приглашения.",
refresh: true,
};
}
@@ -0,0 +1,24 @@
import { useEffect, useState } from "react";
import { toServerTime } from "../../../shared/api";
/** How often the deadline status is recomputed while a screen stays open. */
const refreshIntervalMs = 30_000;
/**
* The current server time in milliseconds, refreshed on an interval. The
* answer window closes at a server deadline, so a screen left open must notice
* the deadline passing without a reload; the device clock is corrected by the
* offset learned from response Date headers.
*/
export function useServerNow(): number {
const [now, setNow] = useState(() => toServerTime(Date.now()));
useEffect(() => {
const timer = window.setInterval(() => {
setNow(toServerTime(Date.now()));
}, refreshIntervalMs);
return () => window.clearInterval(timer);
}, []);
return now;
}
@@ -0,0 +1,17 @@
// Test-only entry of the invitation entity. Tests of the layers above import
// the candidate-side fixtures from here. The fixtures are inputs, not evidence
// about the backend. The lint configuration lets only test files import this
// file, so production code cannot reach it.
export {
candidateAccountId,
candidateGrantId,
candidateInvitationFixture,
candidateInvitationId,
candidateOrganizationId,
candidateTerms,
contactConsentOffer,
emailOnlyGrant,
openDeadline,
passedDeadline,
} from "./model/candidate-invitation.fixtures";
@@ -0,0 +1,5 @@
// Public API of the accept-contact-consent feature: the candidate's acceptance
// of an invitation's current terms with the consent C4, with the contact kinds
// chosen one by one. The page reacts to the outcome and reads the invitation again.
export { AcceptContactConsentForm } from "./ui/accept-contact-consent-form";
@@ -0,0 +1,126 @@
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { ApiRequestError } from "../../../shared/api";
import type { InvitationAcceptance } from "../../../shared/api/schemas";
import {
candidateInvitationFixture,
candidateInvitationId,
} from "../../../entities/invitation/testing";
import { runAcceptCommand } from "./accept-command";
const url = `http://localhost/api/v1/me/invitations/${candidateInvitationId}/accept`;
const csrfToken = "A".repeat(43);
const emailBody: InvitationAcceptance = {
expected_version: 1,
terms_version: 1,
consent_c4: { text_version: "c4-2026-10", accepted: true, fields: ["email"] },
};
const emailAndPhoneBody: InvitationAcceptance = {
...emailBody,
consent_c4: { ...emailBody.consent_c4, fields: ["email", "phone"] },
};
const server = setupServer();
beforeAll(() => server.listen({ onUnhandledFrame: "error" }));
beforeEach(() => {
const realFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
realFetch(new URL(input, "http://localhost"), init),
);
});
afterEach(() => {
vi.unstubAllGlobals();
server.resetHandlers();
});
afterAll(() => server.close());
/**
* A fake of the accept endpoint with the replay rule of the contract: a key
* that was already used with the same body replays the stored answer, and
* `loseFirstResponse` drops the answer of the first request after the server
* recorded it.
*/
function fakeAccept(options: { loseFirstResponse?: boolean; status?: number } = {}) {
const keys: (string | null)[] = [];
let recorded = false;
let lose = options.loseFirstResponse ?? false;
server.use(
http.post(url, async ({ request }) => {
keys.push(request.headers.get("Idempotency-Key"));
await request.json();
if (options.status) {
return HttpResponse.json(
{
type: "urn:lincodex:problem:state_conflict",
title: "State",
status: options.status,
code: "state_conflict",
},
{ status: options.status, headers: { "Content-Type": "application/problem+json" } },
);
}
recorded = true;
if (lose) {
lose = false;
return HttpResponse.error();
}
return HttpResponse.json(candidateInvitationFixture({ state: "accepted", version: 2 }));
}),
);
return { keys, wasRecorded: () => recorded };
}
const request = (body: InvitationAcceptance) => ({
invitationId: candidateInvitationId,
csrfToken,
body,
});
describe("accept command", () => {
it("accepts the chosen contacts with the CSRF token and returns the invitation", async () => {
const fake = fakeAccept();
const outcome = await runAcceptCommand(request(emailBody), null);
expect(outcome.kind).toBe("accepted");
expect(fake.keys).toHaveLength(1);
expect(fake.keys[0]).toBeTruthy();
});
it("repeats the same key after a lost response, so the server records one answer", async () => {
const fake = fakeAccept({ loseFirstResponse: true });
const first = await runAcceptCommand(request(emailBody), null);
expect(first.kind).toBe("failed");
if (first.kind !== "failed") throw new Error("expected a failure");
expect(fake.wasRecorded()).toBe(true);
const retry = await runAcceptCommand(request(emailBody), first.key);
expect(retry.kind).toBe("accepted");
expect(fake.keys[1]).toBe(fake.keys[0]);
});
it("gives a changed choice a new key rather than replaying the old body", async () => {
const fake = fakeAccept({ loseFirstResponse: true });
const first = await runAcceptCommand(request(emailBody), null);
if (first.kind !== "failed") throw new Error("expected a failure");
await runAcceptCommand(request(emailAndPhoneBody), first.key);
expect(fake.keys[1]).not.toBe(fake.keys[0]);
});
it("returns the state conflict as a failure with its problem code", async () => {
fakeAccept({ status: 409 });
const outcome = await runAcceptCommand(request(emailBody), null);
expect(outcome.kind).toBe("failed");
if (outcome.kind !== "failed") throw new Error("expected a failure");
expect(outcome.error).toBeInstanceOf(ApiRequestError);
expect(outcome.error).toMatchObject({ status: 409, code: "state_conflict" });
});
});
@@ -0,0 +1,41 @@
import { acceptCandidateInvitation, bindKey, type KeyBinding } from "../../../entities/invitation";
import type { CandidateInvitation, InvitationAcceptance } from "../../../shared/api/schemas";
export interface AcceptRequest {
readonly invitationId: string;
readonly csrfToken: string;
readonly body: InvitationAcceptance;
}
export type AcceptOutcome =
| { readonly kind: "accepted"; readonly invitation: CandidateInvitation }
| {
readonly kind: "failed";
readonly error: unknown;
/** The key of this attempt; the next attempt of the same choice repeats it. */
readonly key: KeyBinding;
};
/**
* Sends one acceptance and never throws for a request failure. The key is
* bound to the invitation and the whole body, so a repeated click or a retry
* after a lost response replays the same answer, while a changed choice or a
* new terms version gets a new key.
*/
export async function runAcceptCommand(
request: AcceptRequest,
previous: KeyBinding | null,
): Promise<AcceptOutcome> {
const key = bindKey(previous, JSON.stringify([request.invitationId, request.body]));
try {
const invitation = await acceptCandidateInvitation({
invitationId: request.invitationId,
csrfToken: request.csrfToken,
body: request.body,
idempotencyKey: key.key,
});
return { kind: "accepted", invitation };
} catch (error: unknown) {
return { kind: "failed", error, key };
}
}
@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import { contactConsentOffer } from "../../../entities/invitation/testing";
import {
acceptReady,
acceptanceBody,
consentParagraphs,
emptyAcceptDraft,
setAcceptConfirmed,
toggleAcceptField,
} from "./accept-draft";
describe("accept draft", () => {
it("starts with nothing chosen, so no kind is preselected and the send is not ready", () => {
expect(emptyAcceptDraft).toEqual({ fields: [], confirmed: false });
expect(acceptReady(emptyAcceptDraft, contactConsentOffer)).toBe(false);
});
it("chooses each contact kind separately and keeps the contract order", () => {
let draft = toggleAcceptField(emptyAcceptDraft, "phone", true);
draft = toggleAcceptField(draft, "email", true);
expect(draft.fields).toEqual(["email", "phone"]);
draft = toggleAcceptField(draft, "email", false);
expect(draft.fields).toEqual(["phone"]);
expect(toggleAcceptField(draft, "phone", true).fields).toEqual(["phone"]);
});
it("is ready only with the explicit confirmation and at least one offered kind", () => {
const chosen = toggleAcceptField(emptyAcceptDraft, "email", true);
expect(acceptReady(chosen, contactConsentOffer)).toBe(false);
expect(acceptReady(setAcceptConfirmed(chosen, true), contactConsentOffer)).toBe(true);
expect(acceptReady(setAcceptConfirmed(emptyAcceptDraft, true), contactConsentOffer)).toBe(
false,
);
});
it("never sends a kind that the profile did not offer", () => {
const draft = setAcceptConfirmed({ fields: ["telegram"], confirmed: true }, true);
expect(acceptReady(draft, contactConsentOffer)).toBe(false);
});
it("builds the body from the versions the candidate read, the consent text version, and the chosen kinds only", () => {
const draft = setAcceptConfirmed(toggleAcceptField(emptyAcceptDraft, "email", true), true);
expect(
acceptanceBody({ expectedVersion: 3, termsVersion: 2, offer: contactConsentOffer, draft }),
).toEqual({
expected_version: 3,
terms_version: 2,
consent_c4: { text_version: "c4-2026-10", accepted: true, fields: ["email"] },
});
});
it("splits the consent text into paragraphs at empty lines", () => {
expect(consentParagraphs("Первый абзац.\n\nВторой абзац.\n \nТретий.")).toEqual([
"Первый абзац.",
"Второй абзац.",
"Третий.",
]);
});
});
@@ -0,0 +1,76 @@
import type {
ContactConsentOffer,
ContactFieldKind,
InvitationAcceptance,
} from "../../../shared/api/schemas";
import { orderedContactKinds } from "../../../entities/invitation";
// The candidate's choice on the consent form. Nothing is preselected: the
// draft starts with no kind and an unchecked confirmation, and a new terms
// version starts a new draft, because the candidate decides on the new terms.
export interface AcceptDraft {
readonly fields: readonly ContactFieldKind[];
readonly confirmed: boolean;
}
export const emptyAcceptDraft: AcceptDraft = { fields: [], confirmed: false };
/** Adds or removes one contact kind; the list keeps the contract order and never repeats a kind. */
export function toggleAcceptField(
draft: AcceptDraft,
kind: ContactFieldKind,
checked: boolean,
): AcceptDraft {
const others = draft.fields.filter((item) => item !== kind);
return { ...draft, fields: checked ? orderedContactKinds([...others, kind]) : others };
}
export function setAcceptConfirmed(draft: AcceptDraft, confirmed: boolean): AcceptDraft {
return { ...draft, confirmed };
}
/**
* Whether the acceptance may be sent: the explicit confirmation is given, at
* least one kind is chosen, and every chosen kind is one the profile holds.
*/
export function acceptReady(draft: AcceptDraft, offer: ContactConsentOffer): boolean {
return (
draft.confirmed &&
draft.fields.length > 0 &&
draft.fields.every((kind) => offer.available_fields.includes(kind))
);
}
/**
* The request body. It names the terms version and the invitation version
* that the candidate read, and the text version of the consent they saw. It
* never carries contact values.
*/
export function acceptanceBody(input: {
readonly expectedVersion: number;
readonly termsVersion: number;
readonly offer: ContactConsentOffer;
readonly draft: AcceptDraft;
}): InvitationAcceptance {
return {
expected_version: input.expectedVersion,
terms_version: input.termsVersion,
consent_c4: {
text_version: input.offer.text.text_version,
accepted: true,
fields: [...input.draft.fields],
},
};
}
/**
* The consent text as paragraphs. The contract separates paragraphs with an
* empty line; the text is shown as text, never as HTML.
*/
export function consentParagraphs(text: string): string[] {
return text
.split(/\n\s*\n/)
.map((paragraph) => paragraph.trim())
.filter((paragraph) => paragraph.length > 0);
}
@@ -0,0 +1,127 @@
.form {
display: grid;
gap: var(--space-4);
min-width: 0;
padding: var(--space-4);
border: var(--line-strong) solid var(--color-accent);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.title {
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
}
.fieldset {
display: grid;
gap: var(--space-2);
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.legend {
padding: 0;
margin-bottom: var(--space-2);
font-weight: var(--font-weight-bold);
}
.subtitle {
font-size: var(--font-size-s);
font-weight: var(--font-weight-bold);
}
.hint {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
line-height: var(--line-height-body);
}
.consent {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.text {
display: grid;
gap: var(--space-2);
max-height: 16rem;
overflow-y: auto;
padding: var(--space-3);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
background: var(--color-canvas);
color: var(--color-text);
line-height: var(--line-height-body);
overflow-wrap: anywhere;
}
.text p {
margin: 0;
}
.option {
display: flex;
align-items: flex-start;
gap: var(--space-3);
min-height: 2.75rem;
min-width: 0;
padding: var(--space-2) var(--space-3);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
background: var(--color-surface);
line-height: var(--line-height-body);
cursor: pointer;
}
.option input {
flex: none;
width: 1.25rem;
height: 1.25rem;
margin: 0.2rem 0 0;
accent-color: var(--color-accent);
}
.option span {
min-width: 0;
overflow-wrap: anywhere;
}
.option:has(input:focus-visible) {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.alert {
padding: var(--space-3);
border: var(--line-strong) solid var(--color-danger);
border-radius: var(--radius-s);
background: var(--color-surface);
color: var(--color-text);
line-height: var(--line-height-body);
}
.alert:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
}
.submit {
width: 100%;
}
@media (width >= 36rem) {
.submit {
width: auto;
}
}
@@ -0,0 +1,50 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import {
candidateInvitationFixture,
contactConsentOffer,
} from "../../../entities/invitation/testing";
import { AcceptContactConsentForm } from "./accept-contact-consent-form";
function render(): string {
return renderToStaticMarkup(
<AcceptContactConsentForm
invitation={candidateInvitationFixture()}
offer={contactConsentOffer}
organizationName="Северный ветер"
csrfToken={"A".repeat(43)}
onAccepted={() => undefined}
onFailure={() => undefined}
/>,
);
}
describe("accept contact consent form", () => {
it("offers each kind the profile holds as a separate, unchecked choice", () => {
const html = render();
for (const label of ["ФИО", "Электронная почта", "Телефон"]) {
expect(html).toContain(`<span>${label}</span>`);
}
expect(html).not.toContain("<span>Telegram</span>");
expect(html.match(/type="checkbox"/g)).toHaveLength(4);
expect(html).not.toMatch(/checked=""/);
});
it("shows the consent text as paragraphs and the organization in the confirmation", () => {
const html = render();
expect(html).toContain("<p>Я согласен передать компании «Северный ветер» отмеченные контакты");
expect(html).toContain("<p>Согласие относится только к этому приглашению.</p>");
expect(html).toContain("Я прочитал(а) текст согласия и согласен(на) передать");
});
it("is not ready to send until a kind and the confirmation are chosen", () => {
const html = render();
expect(html).toMatch(
/<button[^>]*aria-disabled="true"[^>]*>Принять и передать контакты<\/button>/,
);
expect(html).not.toContain('role="alert"');
});
});
@@ -0,0 +1,191 @@
import { useEffect, useId, useRef, useState, type FormEvent } from "react";
import {
contactKindLabels,
describeResponseFailure,
orderedContactKinds,
type KeyBinding,
type ResponseFailure,
} from "../../../entities/invitation";
import type { CandidateInvitation, ContactConsentOffer } from "../../../shared/api/schemas";
import { Button } from "../../../shared/ui";
import {
acceptReady,
acceptanceBody,
consentParagraphs,
emptyAcceptDraft,
setAcceptConfirmed,
toggleAcceptField,
type AcceptDraft,
} from "../model/accept-draft";
import { runAcceptCommand } from "../model/accept-command";
import styles from "./accept-contact-consent-form.module.css";
type AcceptContactConsentFormProps = {
/** The invitation whose current terms version the candidate is deciding on. */
invitation: CandidateInvitation;
/** The consent C4 offer of that version: the text and the kinds the profile holds. */
offer: ContactConsentOffer;
organizationName: string;
csrfToken: string;
onAccepted: (invitation: CandidateInvitation) => void;
onFailure: (failure: ResponseFailure) => void;
};
/**
* Accepts the terms with the consent C4. Nothing is preselected: the
* candidate ticks each contact kind they agree to disclose and confirms the
* text, and only then can the answer be sent. The form is keyed by the terms
* version by its parent, so a new version starts with an empty choice.
*/
export function AcceptContactConsentForm({
invitation,
offer,
organizationName,
csrfToken,
onAccepted,
onFailure,
}: AcceptContactConsentFormProps) {
const id = useId();
const [draft, setDraft] = useState<AcceptDraft>(emptyAcceptDraft);
const [busy, setBusy] = useState(false);
const [failure, setFailure] = useState<ResponseFailure | null>(null);
const [hint, setHint] = useState<string | null>(null);
const inFlight = useRef(false);
const keyRef = useRef<KeyBinding | null>(null);
const alertRef = useRef<HTMLDivElement>(null);
const ready = acceptReady(draft, offer);
const paragraphs = consentParagraphs(offer.text.text);
const kinds = orderedContactKinds(offer.available_fields);
useEffect(() => {
if (failure) alertRef.current?.focus();
}, [failure]);
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (inFlight.current) return;
if (!ready) {
setHint(
"Отметьте хотя бы один контакт и подтвердите согласие: без этого приглашение не принимается.",
);
return;
}
inFlight.current = true;
setBusy(true);
setFailure(null);
setHint(null);
const body = acceptanceBody({
expectedVersion: invitation.version,
termsVersion: invitation.terms_version,
offer,
draft,
});
void runAcceptCommand({ invitationId: invitation.id, csrfToken, body }, keyRef.current).then(
(outcome) => {
inFlight.current = false;
if (outcome.kind === "accepted") {
keyRef.current = null;
onAccepted(outcome.invitation);
return;
}
keyRef.current = outcome.key;
setBusy(false);
const described = describeResponseFailure("accept", outcome.error);
setFailure(described);
onFailure(described);
},
);
}
return (
<form className={styles.form} onSubmit={submit} noValidate aria-labelledby={`${id}-title`}>
<h3 id={`${id}-title`} className={styles.title}>
Принять приглашение
</h3>
<fieldset className={styles.fieldset} aria-describedby={`${id}-fields-hint`}>
<legend className={styles.legend}>Контакты, которые получит компания</legend>
<p id={`${id}-fields-hint`} className={styles.hint}>
Ничего не отмечено заранее. Отметьте только те контакты, которые компания сможет прочитать
после принятия. Остальные не передаются.
</p>
{kinds.map((kind) => (
<label key={kind} className={styles.option}>
<input
type="checkbox"
name="contact-field"
value={kind}
checked={draft.fields.includes(kind)}
onChange={(event) => {
const checked = event.currentTarget.checked;
setDraft((current) => toggleAcceptField(current, kind, checked));
}}
/>
<span>{contactKindLabels[kind]}</span>
</label>
))}
</fieldset>
<section className={styles.consent} aria-labelledby={`${id}-consent-title`}>
<h4 id={`${id}-consent-title`} className={styles.subtitle}>
Текст согласия C4
</h4>
<div className={styles.text}>
{paragraphs.map((paragraph, index) => (
// The consent text is static for the lifetime of this form.
<p key={index}>{paragraph}</p>
))}
</div>
</section>
<label className={styles.option}>
<input
type="checkbox"
name="consent-confirmed"
checked={draft.confirmed}
onChange={(event) => {
const confirmed = event.currentTarget.checked;
setDraft((current) => setAcceptConfirmed(current, confirmed));
}}
/>
<span>
{`Я прочитал(а) текст согласия и согласен(на) передать отмеченные контакты компании «${organizationName}».`}
</span>
</label>
<p id={`${id}-ready-hint`} className={styles.hint}>
Кнопка станет доступна, когда отмечен хотя бы один контакт и подтверждено согласие.
</p>
{hint ? (
<p className={styles.hint} role="status">
{hint}
</p>
) : null}
{failure ? (
<div
ref={alertRef}
tabIndex={-1}
role="alert"
className={styles.alert}
data-failure={failure.kind}
>
{failure.message}
</div>
) : null}
<div className={styles.actions}>
<Button
type="submit"
isBusy={busy}
aria-disabled={!ready || undefined}
aria-describedby={`${id}-ready-hint`}
className={styles.submit}
>
{busy ? "Отправляем ответ..." : "Принять и передать контакты"}
</Button>
</div>
</form>
);
}
@@ -0,0 +1,5 @@
// Public API of the respond-invitation feature: the candidate's decline of an
// invitation with a structured reason and an optional comment. The page reacts
// to the outcome and reads the invitation again.
export { DeclineInvitationForm } from "./ui/decline-invitation-form";
@@ -0,0 +1,70 @@
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { InvitationDeclineRequest } from "../../../shared/api/schemas";
import {
candidateInvitationFixture,
candidateInvitationId,
} from "../../../entities/invitation/testing";
import { runDeclineCommand } from "./decline-command";
const url = `http://localhost/api/v1/me/invitations/${candidateInvitationId}/decline`;
const server = setupServer();
beforeAll(() => server.listen({ onUnhandledFrame: "error" }));
beforeEach(() => {
const realFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
realFetch(new URL(input, "http://localhost"), init),
);
});
afterEach(() => {
vi.unstubAllGlobals();
server.resetHandlers();
});
afterAll(() => server.close());
describe("decline command", () => {
it("declines with the reason only and reads the declined invitation back", async () => {
const bodies: unknown[] = [];
server.use(
http.post(url, async ({ request }) => {
bodies.push(await request.json());
return HttpResponse.json(candidateInvitationFixture({ state: "declined", version: 2 }));
}),
);
const body: InvitationDeclineRequest = { expected_version: 1, reason: "other" };
const outcome = await runDeclineCommand(
{ invitationId: candidateInvitationId, csrfToken: "A".repeat(43), body },
null,
);
expect(bodies).toEqual([{ expected_version: 1, reason: "other" }]);
expect(outcome.kind).toBe("declined");
if (outcome.kind !== "declined") throw new Error("expected a decline");
expect(outcome.invitation.state).toBe("declined");
});
it("keeps the failure key so that a retry of the same answer replays it", async () => {
const keys: (string | null)[] = [];
server.use(
http.post(url, ({ request }) => {
keys.push(request.headers.get("Idempotency-Key"));
return HttpResponse.error();
}),
);
const request = {
invitationId: candidateInvitationId,
csrfToken: "A".repeat(43),
body: { expected_version: 1, reason: "salary" } as const,
};
const first = await runDeclineCommand(request, null);
if (first.kind !== "failed") throw new Error("expected a failure");
await runDeclineCommand(request, first.key);
expect(keys).toHaveLength(2);
expect(keys[1]).toBe(keys[0]);
});
});
@@ -0,0 +1,40 @@
import { bindKey, declineCandidateInvitation, type KeyBinding } from "../../../entities/invitation";
import type { CandidateInvitation, InvitationDeclineRequest } from "../../../shared/api/schemas";
export interface DeclineRequest {
readonly invitationId: string;
readonly csrfToken: string;
readonly body: InvitationDeclineRequest;
}
export type DeclineOutcome =
| { readonly kind: "declined"; readonly invitation: CandidateInvitation }
| {
readonly kind: "failed";
readonly error: unknown;
/** The key of this attempt; the next attempt of the same answer repeats it. */
readonly key: KeyBinding;
};
/**
* Sends one decline and never throws for a request failure. The key is bound
* to the invitation and the whole body, so a retry of the same answer replays
* it and a changed answer gets a new key.
*/
export async function runDeclineCommand(
request: DeclineRequest,
previous: KeyBinding | null,
): Promise<DeclineOutcome> {
const key = bindKey(previous, JSON.stringify([request.invitationId, request.body]));
try {
const invitation = await declineCandidateInvitation({
invitationId: request.invitationId,
csrfToken: request.csrfToken,
body: request.body,
idempotencyKey: key.key,
});
return { kind: "declined", invitation };
} catch (error: unknown) {
return { kind: "failed", error, key };
}
}
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import {
commentTooLong,
declineBody,
declineComment,
declineCommentLimit,
declineReady,
emptyDeclineDraft,
} from "./decline-draft";
describe("decline draft", () => {
it("needs a reason and nothing else: no reason is preselected", () => {
expect(declineReady(emptyDeclineDraft)).toBe(false);
expect(declineReady({ reason: "other", comment: "" })).toBe(true);
});
it("sends the reason without a comment when the candidate writes none, even for other", () => {
expect(declineBody(2, { reason: "other", comment: " " })).toEqual({
expected_version: 2,
reason: "other",
});
});
it("trims a written comment and keeps its line breaks", () => {
expect(declineComment(" Не сейчас\nСпасибо ")).toBe("Не сейчас\nСпасибо");
expect(declineBody(2, { reason: "salary", comment: " Вилка ниже ожиданий " })).toEqual({
expected_version: 2,
reason: "salary",
comment: "Вилка ниже ожиданий",
});
});
it("counts the comment limit in code points and blocks a longer comment", () => {
const exact = "я".repeat(declineCommentLimit);
expect(commentTooLong(exact)).toBe(false);
expect(commentTooLong(`${exact}я`)).toBe(true);
expect(declineReady({ reason: "tasks", comment: `${exact}я` })).toBe(false);
});
it("refuses to build a body without a reason", () => {
expect(() => declineBody(1, emptyDeclineDraft)).toThrow("A decline needs a reason.");
});
});
@@ -0,0 +1,45 @@
import type {
InvitationDeclineReason,
InvitationDeclineRequest,
} from "../../../shared/api/schemas";
// The candidate's decline form. A reason is required, and the comment is
// optional for every reason, including "other": the neutral reason never
// asks for free text. The comment is never shown to the organization.
/** The contract's limit on the comment, in Unicode code points. */
export const declineCommentLimit = 500;
export interface DeclineDraft {
readonly reason: InvitationDeclineReason | null;
readonly comment: string;
}
export const emptyDeclineDraft: DeclineDraft = { reason: null, comment: "" };
/** The comment as sent, or null when it is blank: a blank comment means none. */
export function declineComment(comment: string): string | null {
const trimmed = comment.trim();
return trimmed.length > 0 ? trimmed : null;
}
export function commentTooLong(comment: string): boolean {
return Array.from(comment.trim()).length > declineCommentLimit;
}
/** Whether the decline may be sent: a reason is chosen and the comment fits the limit. */
export function declineReady(draft: DeclineDraft): boolean {
return draft.reason !== null && !commentTooLong(draft.comment);
}
/** The request body; the comment is absent when the candidate wrote none. */
export function declineBody(
expectedVersion: number,
draft: DeclineDraft,
): InvitationDeclineRequest {
if (draft.reason === null) throw new Error("A decline needs a reason.");
const comment = declineComment(draft.comment);
return comment === null
? { expected_version: expectedVersion, reason: draft.reason }
: { expected_version: expectedVersion, reason: draft.reason, comment };
}
@@ -0,0 +1,129 @@
.form {
display: grid;
gap: var(--space-4);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.title {
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
}
.fieldset {
display: grid;
gap: var(--space-2);
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.legend,
.label {
display: block;
padding: 0;
margin-bottom: var(--space-2);
font-weight: var(--font-weight-bold);
}
.hint {
margin: 0;
color: var(--color-text-secondary);
font-size: var(--font-size-s);
line-height: var(--line-height-body);
}
.option {
display: flex;
align-items: flex-start;
gap: var(--space-3);
min-height: 2.75rem;
min-width: 0;
padding: var(--space-2) var(--space-3);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-s);
background: var(--color-surface);
line-height: var(--line-height-body);
cursor: pointer;
}
.option input {
flex: none;
width: 1.25rem;
height: 1.25rem;
margin: 0.2rem 0 0;
accent-color: var(--color-accent);
}
.option span {
min-width: 0;
overflow-wrap: anywhere;
}
.option:has(input:focus-visible) {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.comment {
display: grid;
gap: var(--space-2);
min-width: 0;
}
.textarea {
box-sizing: border-box;
width: 100%;
min-width: 0;
padding: var(--space-3);
border: var(--line-strong) solid var(--color-border-strong);
border-radius: var(--radius-s);
background: var(--color-surface);
color: var(--color-text);
font: inherit;
line-height: var(--line-height-body);
resize: vertical;
}
.textarea[aria-invalid="true"] {
border-color: var(--color-danger);
}
.textarea:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.alert {
padding: var(--space-3);
border: var(--line-strong) solid var(--color-danger);
border-radius: var(--radius-s);
background: var(--color-surface);
color: var(--color-text);
line-height: var(--line-height-body);
}
.alert:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
}
.submit {
width: 100%;
}
@media (width >= 36rem) {
.submit {
width: auto;
}
}
@@ -0,0 +1,42 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { candidateInvitationFixture } from "../../../entities/invitation/testing";
import { DeclineInvitationForm } from "./decline-invitation-form";
function render(): string {
return renderToStaticMarkup(
<DeclineInvitationForm
invitation={candidateInvitationFixture()}
csrfToken={"A".repeat(43)}
onDeclined={() => undefined}
onFailure={() => undefined}
/>,
);
}
describe("decline invitation form", () => {
it("offers every reason as an unchecked choice, with the neutral reason last", () => {
const html = render();
expect(html.match(/type="radio"/g)).toHaveLength(9);
expect(html).not.toMatch(/checked=""/);
expect(html).toContain("<span>Вилка зарплаты не подходит</span>");
expect(html.indexOf("<span>Другая причина</span>")).toBeGreaterThan(
html.indexOf("<span>Я принял другое предложение</span>"),
);
});
it("keeps the comment optional for every reason and says who reads it", () => {
const html = render();
expect(html).toContain("Комментарий (необязательно)");
expect(html).toContain("Комментарий видите только вы");
expect(html).toContain("Отказ окончательный");
});
it("is not ready to send until a reason is chosen", () => {
expect(render()).toMatch(
/<button[^>]*aria-disabled="true"[^>]*>Отклонить приглашение<\/button>/,
);
});
});
@@ -0,0 +1,170 @@
import { useEffect, useId, useRef, useState, type FormEvent } from "react";
import {
declineReasonCodes,
declineReasonLabels,
describeResponseFailure,
type KeyBinding,
type ResponseFailure,
} from "../../../entities/invitation";
import type { CandidateInvitation } from "../../../shared/api/schemas";
import { Button } from "../../../shared/ui";
import {
commentTooLong,
declineBody,
declineCommentLimit,
declineReady,
emptyDeclineDraft,
type DeclineDraft,
} from "../model/decline-draft";
import { runDeclineCommand } from "../model/decline-command";
import styles from "./decline-invitation-form.module.css";
type DeclineInvitationFormProps = {
/** The invitation the candidate is still able to answer. */
invitation: CandidateInvitation;
csrfToken: string;
onDeclined: (invitation: CandidateInvitation) => void;
onFailure: (failure: ResponseFailure) => void;
};
/**
* Declines the invitation with a structured reason. The reason is chosen by
* the candidate and nothing is preselected; the comment is optional for every
* reason, including "other". The decline is final, so the form says so.
*/
export function DeclineInvitationForm({
invitation,
csrfToken,
onDeclined,
onFailure,
}: DeclineInvitationFormProps) {
const id = useId();
const [draft, setDraft] = useState<DeclineDraft>(emptyDeclineDraft);
const [busy, setBusy] = useState(false);
const [failure, setFailure] = useState<ResponseFailure | null>(null);
const [hint, setHint] = useState<string | null>(null);
const inFlight = useRef(false);
const keyRef = useRef<KeyBinding | null>(null);
const alertRef = useRef<HTMLDivElement>(null);
const ready = declineReady(draft);
const tooLong = commentTooLong(draft.comment);
useEffect(() => {
if (failure) alertRef.current?.focus();
}, [failure]);
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (inFlight.current) return;
if (!ready) {
setHint(
tooLong
? `Комментарий длиннее ${declineCommentLimit} символов. Сократите его, чтобы отправить отказ.`
: "Выберите причину отказа, чтобы отправить ответ.",
);
return;
}
inFlight.current = true;
setBusy(true);
setFailure(null);
setHint(null);
const body = declineBody(invitation.version, draft);
void runDeclineCommand({ invitationId: invitation.id, csrfToken, body }, keyRef.current).then(
(outcome) => {
inFlight.current = false;
if (outcome.kind === "declined") {
keyRef.current = null;
onDeclined(outcome.invitation);
return;
}
keyRef.current = outcome.key;
setBusy(false);
const described = describeResponseFailure("decline", outcome.error);
setFailure(described);
onFailure(described);
},
);
}
return (
<form className={styles.form} onSubmit={submit} noValidate aria-labelledby={`${id}-title`}>
<h3 id={`${id}-title`} className={styles.title}>
Отклонить приглашение
</h3>
<fieldset className={styles.fieldset} aria-describedby={`${id}-reason-hint`}>
<legend className={styles.legend}>Причина отказа</legend>
<p id={`${id}-reason-hint`} className={styles.hint}>
Выберите одну причину. Ни одна не выбрана заранее. Комментарий необязателен, в том числе
для варианта «Другая причина».
</p>
{declineReasonCodes.map((code) => (
<label key={code} className={styles.option}>
<input
type="radio"
name="decline-reason"
value={code}
checked={draft.reason === code}
onChange={() => setDraft((current) => ({ ...current, reason: code }))}
/>
<span>{declineReasonLabels[code]}</span>
</label>
))}
</fieldset>
<div className={styles.comment}>
<label htmlFor={`${id}-comment`} className={styles.label}>
Комментарий (необязательно)
</label>
<textarea
id={`${id}-comment`}
className={styles.textarea}
rows={4}
maxLength={declineCommentLimit}
value={draft.comment}
aria-describedby={`${id}-comment-hint`}
aria-invalid={tooLong || undefined}
onChange={(event) => {
const comment = event.currentTarget.value;
setDraft((current) => ({ ...current, comment }));
}}
/>
<p id={`${id}-comment-hint`} className={styles.hint}>
Комментарий видите только вы. Компания его не получает и не видит причину отказа.
</p>
</div>
<p className={styles.hint}>Отказ окончательный: после него приглашение нельзя принять.</p>
{hint ? (
<p className={styles.hint} role="status">
{hint}
</p>
) : null}
{failure ? (
<div
ref={alertRef}
tabIndex={-1}
role="alert"
className={styles.alert}
data-failure={failure.kind}
>
{failure.message}
</div>
) : null}
<div className={styles.actions}>
<Button
type="submit"
variant="secondary"
isBusy={busy}
aria-disabled={!ready || undefined}
className={styles.submit}
>
{busy ? "Отправляем отказ..." : "Отклонить приглашение"}
</Button>
</div>
</form>
);
}
@@ -0,0 +1,5 @@
// Public API of the candidate-invitations pages: the candidate's inbox and the
// screen of one invitation addressed to the candidate.
export { CandidateInvitationsPage } from "./ui/candidate-invitations-page";
export { CandidateInvitationPage } from "./ui/candidate-invitation-page";
@@ -0,0 +1,155 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { describe, expect, it } from "vitest";
import {
candidateAccountId,
candidateGrantId,
candidateInvitationFixture,
candidateInvitationId,
emailOnlyGrant,
openDeadline,
passedDeadline,
} from "../../../entities/invitation/testing";
import { candidateInvitationQueryKeys } from "../../../entities/invitation";
import type { CandidateInvitation, Session } from "../../../shared/api/schemas";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import { CandidateInvitationPage } from "./candidate-invitation-page";
const session = {
account: {
id: candidateAccountId,
email: "candidate@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "completed",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
} satisfies Session;
function render(
invitation: CandidateInvitation | null,
invitationId = candidateInvitationId,
): string {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
if (invitation) {
queryClient.setQueryData(
candidateInvitationQueryKeys.detail(candidateAccountId, invitation.id),
invitation,
);
}
return renderToStaticMarkup(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[`/candidate/invitations/${invitationId}`]}>
<Routes>
<Route
path="/candidate/invitations/:invitationId"
element={<CandidateInvitationPage />}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
);
}
describe("candidate invitation page", () => {
it("shows the company, the terms, and the deadline with its UTC label before any choice", () => {
const html = render(candidateInvitationFixture());
expect(html).toContain("Приглашение</h1>");
expect(html).toContain("Северный ветер");
expect(html).toMatch(/от 100\s000 ₽ до 140\s000 ₽ в месяц, после налога \(net\)/);
expect(html).toContain(`<time dateTime="${openDeadline}">`);
expect(html).toMatch(/<time dateTime="2099-10-16T10:00:00Z">[^<]*UTC<\/time>/);
expect(html).toContain("Принять и передать контакты");
expect(html).toContain("Отклонить приглашение");
expect(html).not.toMatch(/checked=""/);
});
it("offers the contact kinds unchecked and nothing outside the offer", () => {
const html = render(candidateInvitationFixture());
expect(html.match(/type="checkbox"/g)).toHaveLength(4);
expect(html).toContain("<span>Электронная почта</span>");
expect(html).toContain("<span>Телефон</span>");
expect(html).not.toContain("<span>Telegram</span>");
});
it("asks to add a contact instead of an acceptance when the profile holds none", () => {
const html = render(candidateInvitationFixture({ contact_consent: null }));
expect(html).toContain("Принять приглашение нельзя");
expect(html).toContain('href="/candidate/profile"');
expect(html).not.toContain("Принять и передать контакты");
expect(html).toContain("Отклонить приглашение");
});
it("shows only the contacts that the grant covers after an acceptance", () => {
const html = render(
candidateInvitationFixture({
state: "accepted",
version: 2,
contact_consent: null,
contact_grant: emailOnlyGrant,
}),
);
expect(html).toContain("Итог");
expect(html).toContain("<li>Электронная почта</li>");
expect(html).not.toContain("<li>Телефон</li>");
expect(html).not.toContain("<li>ФИО</li>");
expect(html).toContain("Компания может прочитать эти контакты.");
expect(html).not.toContain("Отклонить приглашение");
});
it("explains a grant that the company cannot read yet, and where to change visibility", () => {
const html = render(
candidateInvitationFixture({
state: "accepted",
version: 2,
contact_consent: null,
contact_grant: { ...emailOnlyGrant, readable: false, blocked_by: "visibility" },
}),
);
expect(html).toContain("Пока карточка не опубликована или скрыта от компании");
expect(html).toContain('href="/candidate/privacy"');
});
it("keeps a declined invitation declined, with the reason and the own comment, and no contacts", () => {
const html = render(
candidateInvitationFixture({
state: "declined",
version: 2,
contact_consent: null,
decline: { reason: "other", comment: null, declined_at: "2026-10-10T09:00:00Z" },
}),
);
expect(html).toContain("Вы отклонили приглашение");
expect(html).toContain("Причина: Другая причина.");
expect(html).not.toContain("Ваш комментарий");
expect(html).not.toContain("Контакты, которые открыты компании");
expect(html).not.toContain("Отклонить приглашение");
});
it("closes the answer at the deadline by the clock, even before the server applies the expiry", () => {
const html = render(
candidateInvitationFixture({ response_deadline_at: passedDeadline, contact_consent: null }),
);
expect(html).toContain("Срок ответа истек. Приглашение закрыто");
expect(html).not.toContain("Принять и передать контакты");
expect(html).not.toContain("Отклонить приглашение");
});
it("says that the invitation is not found for a malformed or foreign identifier", () => {
const html = render(null, "not-a-uuid");
expect(html).toContain("Приглашение не найдено");
expect(html).not.toContain("Принять и передать контакты");
expect(html).not.toContain(candidateGrantId);
});
});
@@ -0,0 +1,370 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useParams } from "react-router-dom";
import { AcceptContactConsentForm } from "../../../features/accept-contact-consent";
import { DeclineInvitationForm } from "../../../features/respond-invitation";
import {
candidateInvitationQueryKeys,
candidateStatusLabel,
contactKindLabels,
declineReasonLabels,
formatServerMoment,
isAnswerable,
newerInvitation,
orderedContactKinds,
readCandidateInvitation,
viewCandidateInvitation,
type ResponseCommand,
type ResponseFailure,
useServerNow,
} from "../../../entities/invitation";
import { ApiRequestError } from "../../../shared/api";
import {
getGetCurrentSessionQueryKey,
useGetCurrentSession,
} from "../../../shared/api/endpoints/identity/identity";
import type {
CandidateInvitation,
ContactGrant,
ContactRevocationReason,
} from "../../../shared/api/schemas";
import { paths } from "../../../shared/config";
import {
ButtonLink,
EmptyState,
ErrorState,
ForbiddenState,
isAccessDenied,
LoadingState,
Page,
Section,
TextLink,
} from "../../../shared/ui";
import { InvitationTermsArticle } from "../../../widgets/invitation-preview";
import styles from "./candidate-invitations.module.css";
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const staleAcceptNotice =
"Приглашение изменилось после вашего прочтения. Мы загрузили актуальную версию: проверьте условия и подтвердите выбор контактов заново.";
const revocationText: Readonly<Record<ContactRevocationReason, string>> = {
consent_revoked: "вы отозвали согласие C4 для этой компании",
participation_cancelled: "вы отменили участие в этом приглашении",
visibility_closed: "вы закрыли публикацию или скрыли профиль от компании",
};
function isMissing(error: unknown): boolean {
return error instanceof ApiRequestError && error.status === 404;
}
function NotFoundState() {
return (
<EmptyState
title="Приглашение не найдено"
description="Оно не адресовано вашему кабинету или уже недоступно."
action={
<ButtonLink to={paths.candidate.invitations} variant="secondary">
К списку приглашений
</ButtonLink>
}
/>
);
}
/** What the candidate can read about the contacts that one acceptance opened. */
function GrantSummary({ grant }: { grant: ContactGrant }) {
const kinds = orderedContactKinds(grant.fields);
let status: ReactNode;
if (grant.status === "revoked") {
status = `Доступ закрыт: ${
grant.revocation_reason ? revocationText[grant.revocation_reason] : "доступ закрыт"
}.`;
} else if (grant.readable) {
status = "Компания может прочитать эти контакты.";
} else {
status = (
<>
{
"Пока карточка не опубликована или скрыта от компании, она не может прочитать эти контакты. Измените видимость в "
}
<TextLink to={paths.candidate.privacy}>настройках приватности</TextLink>.
</>
);
}
return (
<div className={styles.grant}>
<h3 className={styles.subtitle}>Контакты, которые открыты компании</h3>
<ul className={styles.kinds}>
{kinds.map((kind) => (
<li key={kind}>{contactKindLabels[kind]}</li>
))}
</ul>
<p className={styles.text}>{`Открыто ${formatServerMoment(grant.granted_at)}.`}</p>
<p className={styles.text}>{status}</p>
</div>
);
}
function outcomeText(invitation: CandidateInvitation, serverNow: number): string {
if (!isAnswerable(invitation, serverNow) && invitation.state === "delivered") {
return "Срок ответа истек. Приглашение закрыто, контакты не передавались.";
}
switch (invitation.state) {
case "accepted":
return "Вы приняли приглашение. Компания получила доступ только к отмеченным контактам.";
case "declined":
return "Вы отклонили приглашение. Компания не получает контакты и не видит причину отказа.";
case "expired":
return "Срок ответа истек. Контакты не передавались.";
case "withdrawn":
return "Компания отозвала приглашение. Новых решений по нему не нужно.";
case "cancelled_by_candidate":
return "Вы отменили участие. Доступ к контактам по этому приглашению закрыт.";
default:
return candidateStatusLabel(invitation, serverNow);
}
}
function OutcomeSection({
invitation,
serverNow,
}: {
invitation: CandidateInvitation;
serverNow: number;
}) {
const decline = invitation.decline;
return (
<Section title="Итог">
<p className={styles.text}>{outcomeText(invitation, serverNow)}</p>
{decline ? (
<div className={styles.grant}>
<h3 className={styles.subtitle}>Ваш отказ</h3>
<p className={styles.text}>{`Причина: ${declineReasonLabels[decline.reason]}.`}</p>
{decline.comment ? (
<p className={styles.text}>{`Ваш комментарий: ${decline.comment}`}</p>
) : null}
<p className={styles.text}>{`Отказ ${formatServerMoment(decline.declined_at)}.`}</p>
</div>
) : null}
{invitation.contact_grant ? <GrantSummary grant={invitation.contact_grant} /> : null}
</Section>
);
}
type AnswerSectionProps = {
invitation: CandidateInvitation;
csrfToken: string;
onAnswered: (invitation: CandidateInvitation) => void;
onFailure: (command: ResponseCommand, failure: ResponseFailure) => void;
};
/**
* The two answers while the invitation is open. Accepting needs the consent
* offer, which the server returns only when the profile holds a contact.
*/
function AnswerSection({ invitation, csrfToken, onAnswered, onFailure }: AnswerSectionProps) {
const offer = invitation.contact_consent;
return (
<Section
title="Ваш ответ"
description="Ответ нельзя изменить после отправки: принятие открывает отмеченные контакты, отказ закрывает приглашение."
>
<div className={styles.decisions}>
{offer ? (
<AcceptContactConsentForm
key={`${invitation.id}:${invitation.terms_version}`}
invitation={invitation}
offer={offer}
organizationName={invitation.organization.name}
csrfToken={csrfToken}
onAccepted={onAnswered}
onFailure={(failure) => onFailure("accept", failure)}
/>
) : (
<div className={styles["no-offer"]}>
<h3 className={styles.subtitle}>Принять приглашение нельзя</h3>
<p className={styles.text}>
Компании передаются только контакты из профиля. Добавьте хотя бы один контакт в
профиль, чтобы принять приглашение.
</p>
<ButtonLink to={paths.candidate.profile} variant="secondary">
Открыть профиль
</ButtonLink>
</div>
)}
<DeclineInvitationForm
key={invitation.id}
invitation={invitation}
csrfToken={csrfToken}
onDeclined={onAnswered}
onFailure={(failure) => onFailure("decline", failure)}
/>
</div>
</Section>
);
}
type InvitationContentProps = AnswerSectionProps & {
serverNow: number;
notice: string | null;
};
function InvitationContent({
invitation,
serverNow,
notice,
csrfToken,
onAnswered,
onFailure,
}: InvitationContentProps) {
return (
<>
<Section title="Компания и срок">
<dl className={styles.facts}>
<div className={styles.fact}>
<dt>Компания</dt>
<dd>{invitation.organization.name}</dd>
</div>
<div className={styles.fact}>
<dt>Состояние</dt>
<dd data-state={invitation.state}>{candidateStatusLabel(invitation, serverNow)}</dd>
</div>
<div className={styles.fact}>
<dt>Срок ответа</dt>
<dd data-term="deadline">
<time dateTime={invitation.response_deadline_at}>
{`До ${formatServerMoment(invitation.response_deadline_at)}`}
</time>
</dd>
</div>
</dl>
</Section>
{notice ? (
<p className={styles.notice} role="status">
{notice}
</p>
) : null}
<Section title="Условия приглашения">
<InvitationTermsArticle
terms={invitation.terms}
responsePeriodDays={null}
responseDeadlineAt={null}
headingLevel={3}
/>
</Section>
{isAnswerable(invitation, serverNow) ? (
<AnswerSection
invitation={invitation}
csrfToken={csrfToken}
onAnswered={onAnswered}
onFailure={onFailure}
/>
) : (
<OutcomeSection invitation={invitation} serverNow={serverNow} />
)}
</>
);
}
/**
* One invitation addressed to the candidate. Opening it records the view once
* (the first view is what the company sees as "viewed"); reading it never
* does. An answer replaces the shown invitation with the one the server
* returns, and a stale terms version makes the page read the new terms.
*/
export function CandidateInvitationPage() {
const { invitationId = "" } = useParams();
const validId = uuidPattern.test(invitationId);
const session = useGetCurrentSession();
const accountId = session.data?.account.id ?? "";
const csrfToken = session.data?.csrf_token ?? "";
const queryClient = useQueryClient();
const detail = useQuery({
queryKey: candidateInvitationQueryKeys.detail(accountId, invitationId),
queryFn: ({ signal }) => readCandidateInvitation(invitationId, signal),
enabled: validId && accountId !== "",
});
const invitation = detail.data;
const openedId = invitation?.id;
const viewedId = useRef<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
// One view per opened invitation. A failed view changes nothing on screen:
// the terms stay readable and the candidate can still answer.
useEffect(() => {
if (openedId === undefined || csrfToken === "" || viewedId.current === openedId) return;
viewedId.current = openedId;
void viewCandidateInvitation(openedId, { csrfToken }).then(
(viewed) => {
queryClient.setQueryData<CandidateInvitation>(
candidateInvitationQueryKeys.detail(accountId, openedId),
(current) => newerInvitation(current, viewed),
);
},
() => undefined,
);
}, [openedId, csrfToken, accountId, queryClient]);
function handleAnswered(updated: CandidateInvitation) {
queryClient.setQueryData<CandidateInvitation>(
candidateInvitationQueryKeys.detail(accountId, updated.id),
(current) => newerInvitation(current, updated),
);
setNotice(null);
void queryClient.invalidateQueries({ queryKey: candidateInvitationQueryKeys.inbox(accountId) });
}
function handleFailure(command: ResponseCommand, failure: ResponseFailure) {
if (command === "accept" && failure.kind === "stale-terms") setNotice(staleAcceptNotice);
if (failure.kind === "csrf") {
void queryClient.invalidateQueries({ queryKey: getGetCurrentSessionQueryKey() });
}
if (failure.refresh) void detail.refetch();
}
const serverNow = useServerNow();
return (
<Page
title="Приглашение"
eyebrow="Кабинет кандидата"
lead={invitation ? candidateStatusLabel(invitation, serverNow) : undefined}
>
{!validId ? <NotFoundState /> : null}
{validId && accountId !== "" && detail.isPending ? (
<LoadingState label="Открываем приглашение..." />
) : null}
{validId && detail.isError ? (
isMissing(detail.error) ? (
<NotFoundState />
) : isAccessDenied(detail.error) ? (
<ForbiddenState error={detail.error} />
) : (
<ErrorState
error={detail.error}
title={
invitation ? "Не удалось обновить приглашение" : "Не удалось открыть приглашение"
}
isRetrying={detail.isFetching}
onRetry={() => void detail.refetch()}
/>
)
) : null}
{invitation ? (
<InvitationContent
invitation={invitation}
serverNow={serverNow}
notice={notice}
csrfToken={csrfToken}
onAnswered={handleAnswered}
onFailure={handleFailure}
/>
) : null}
</Page>
);
}
@@ -0,0 +1,96 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import {
candidateAccountId,
candidateInvitationFixture,
candidateInvitationId,
} from "../../../entities/invitation/testing";
import { candidateInvitationQueryKeys } from "../../../entities/invitation";
import type { CandidateInvitationList, Session } from "../../../shared/api/schemas";
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
import { CandidateInvitationsPage } from "./candidate-invitations-page";
const session = {
account: {
id: candidateAccountId,
email: "candidate@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "completed",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
} satisfies Session;
function summaryOf(overrides: Record<string, unknown> = {}) {
const invitation = candidateInvitationFixture();
return {
id: invitation.id,
organization: invitation.organization,
state: invitation.state,
expiry_reason: null,
version: invitation.version,
terms_version: invitation.terms_version,
role_title: invitation.terms.role_title,
salary: invitation.terms.salary,
work_formats: invitation.terms.work_formats,
response_deadline_at: invitation.response_deadline_at,
delivered_at: invitation.delivered_at,
viewed_at: null,
updated_at: invitation.updated_at,
...overrides,
};
}
function render(page: CandidateInvitationList): string {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
queryClient.setQueryData([...candidateInvitationQueryKeys.inbox(candidateAccountId), "pages"], {
pages: [page],
pageParams: [undefined],
});
return renderToStaticMarkup(
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<CandidateInvitationsPage />
</MemoryRouter>
</QueryClientProvider>,
);
}
describe("candidate inbox page", () => {
it("lists each invitation with its company, role, salary, deadline, and state, linked to its screen", () => {
const html = render({
items: [summaryOf()] as CandidateInvitationList["items"],
page: { has_more: false, next_cursor: null },
});
expect(html).toContain("<h1");
expect(html).toContain("Приглашения</h1>");
expect(html).toContain(`href="/candidate/invitations/${candidateInvitationId}"`);
expect(html).toContain("Северный ветер");
expect(html).toContain("Middle Go-разработчик в команду платежей");
expect(html).toMatch(/от 100\s000 ₽ до 140\s000 ₽ в месяц, после налога \(net\)/);
expect(html).toContain("UTC");
expect(html).toContain("Ждет вашего решения");
expect(html).not.toContain("Показать еще");
});
it("offers the next page only when the server says there is one", () => {
const html = render({
items: [summaryOf()] as CandidateInvitationList["items"],
page: { has_more: true, next_cursor: "cursor-2" },
});
expect(html).toContain("Показать еще");
});
it("says that the inbox is empty and what happens to contacts", () => {
const html = render({ items: [], page: { has_more: false, next_cursor: null } });
expect(html).toContain("Приглашений пока нет");
expect(html).toContain("Контакты передаются компании только после вашего принятия");
});
});
@@ -0,0 +1,113 @@
import { useInfiniteQuery } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import {
candidateInvitationQueryKeys,
candidateStatusLabel,
formatSalaryRange,
formatServerMoment,
listCandidateInvitations,
useServerNow,
} from "../../../entities/invitation";
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
import { paths } from "../../../shared/config";
import {
Button,
EmptyState,
ErrorState,
ForbiddenState,
isAccessDenied,
LoadingState,
Page,
} from "../../../shared/ui";
import styles from "./candidate-invitations.module.css";
const lead =
"Компании присылают приглашения с условиями, вилкой зарплаты и сроком ответа. Контакты компания получит только после вашего принятия и только те, которые вы отметили.";
/**
* The candidate's inbox: every invitation addressed to the candidate, newest
* first. Listing never records a view, so opening this page changes nothing
* that the company sees.
*/
export function CandidateInvitationsPage() {
const session = useGetCurrentSession();
const accountId = session.data?.account.id ?? "";
const inbox = useInfiniteQuery({
queryKey: [...candidateInvitationQueryKeys.inbox(accountId), "pages"],
queryFn: ({ pageParam, signal }) => listCandidateInvitations({ cursor: pageParam, signal }),
initialPageParam: undefined as string | undefined,
getNextPageParam: (last) =>
last.page.has_more ? (last.page.next_cursor ?? undefined) : undefined,
enabled: accountId !== "",
});
const items = inbox.data?.pages.flatMap((page) => page.items) ?? [];
const serverNow = useServerNow();
return (
<Page title="Приглашения" eyebrow="Кабинет кандидата" lead={lead}>
{inbox.isPending && accountId !== "" ? (
<LoadingState label="Загружаем приглашения..." />
) : null}
{inbox.isError ? (
isAccessDenied(inbox.error) ? (
<ForbiddenState error={inbox.error} />
) : (
<ErrorState
error={inbox.error}
title={
items.length > 0
? "Не удалось загрузить следующую страницу"
: "Не удалось загрузить приглашения"
}
isRetrying={inbox.isFetching}
onRetry={() => void inbox.refetch()}
/>
)
) : null}
{inbox.isSuccess && items.length === 0 ? (
<EmptyState
title="Приглашений пока нет"
description="Когда компания отправит приглашение, оно появится здесь. Контакты передаются компании только после вашего принятия."
/>
) : null}
{items.length > 0 ? (
<section className={styles.inbox} aria-label="Список приглашений">
<ul className={styles.list}>
{items.map((item) => (
<li key={item.id}>
<Link className={styles.card} to={paths.candidate.invitation(item.id)}>
<span className={styles["card-company"]}>
<span className={styles["card-label"]}>Компания</span>
<span className={styles["card-title"]}>{item.organization.name}</span>
</span>
<span className={styles["card-role"]}>{item.role_title}</span>
<span className={styles["card-facts"]}>
<span>{formatSalaryRange(item.salary)}</span>
<span>
{`Срок ответа: до ${formatServerMoment(item.response_deadline_at)}`}
</span>
</span>
<span className={styles["card-status"]} data-state={item.state}>
{candidateStatusLabel(item, serverNow)}
</span>
</Link>
</li>
))}
</ul>
{inbox.hasNextPage ? (
<div className={styles.more}>
<Button
variant="secondary"
isBusy={inbox.isFetchingNextPage}
onClick={() => void inbox.fetchNextPage()}
>
{inbox.isFetchingNextPage ? "Загружаем..." : "Показать еще"}
</Button>
</div>
) : null}
</section>
) : null}
</Page>
);
}
@@ -0,0 +1,168 @@
/* Shared by the inbox and the invitation screen. Phones come first: every
* block is one column and every tap target is at least 44px tall. */
.inbox {
display: grid;
gap: var(--space-4);
min-width: 0;
}
.list {
display: grid;
gap: var(--space-3);
margin: 0;
padding: 0;
list-style: none;
}
.card {
display: grid;
gap: var(--space-2);
min-width: 0;
min-height: 2.75rem;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
color: var(--color-text);
text-decoration: none;
}
.card:hover {
border-color: var(--color-border-strong);
}
.card:focus-visible {
outline: var(--focus-ring-width) solid var(--color-focus-ring);
outline-offset: var(--focus-ring-offset);
}
.card-company {
display: grid;
gap: var(--space-1);
}
.card-label {
color: var(--color-text-secondary);
font-size: var(--font-size-xs);
letter-spacing: var(--letter-spacing-label);
text-transform: uppercase;
}
.card-title {
overflow-wrap: anywhere;
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
}
.card-role {
overflow-wrap: anywhere;
font-weight: var(--font-weight-medium);
}
.card-facts {
display: grid;
gap: var(--space-1);
color: var(--color-text-secondary);
font-size: var(--font-size-s);
}
.card-status {
justify-self: start;
padding: var(--space-1) var(--space-2);
border: var(--line-thin) solid var(--color-border-strong);
border-radius: var(--radius-pill);
font-size: var(--font-size-xs);
}
.more {
display: flex;
justify-content: center;
}
.facts {
display: grid;
gap: var(--space-3);
min-width: 0;
margin: 0;
}
.fact {
display: grid;
gap: var(--space-1);
min-width: 0;
}
.fact > dt {
color: var(--color-text-secondary);
}
.fact > dd {
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.section-title {
font-size: var(--font-size-l);
font-weight: var(--font-weight-bold);
}
.subtitle {
font-size: var(--font-size-m);
font-weight: var(--font-weight-bold);
}
.text {
margin: 0;
line-height: var(--line-height-body);
overflow-wrap: anywhere;
}
.notice {
margin: 0;
padding: var(--space-3);
border: var(--line-strong) solid var(--color-accent);
border-radius: var(--radius-s);
background: var(--color-surface);
line-height: var(--line-height-body);
}
.decisions {
display: grid;
gap: var(--space-5);
min-width: 0;
}
.no-offer {
display: grid;
gap: var(--space-3);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.grant {
display: grid;
gap: var(--space-2);
min-width: 0;
padding: var(--space-4);
border: var(--line-thin) solid var(--color-divider);
border-radius: var(--radius-m);
background: var(--color-surface);
}
.kinds {
display: grid;
gap: var(--space-1);
margin: 0;
padding-left: var(--space-5);
}
@media (width >= 48rem) {
.list {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@@ -91,15 +91,6 @@ export const screens = {
"Разбор результата по компетенциям",
],
},
candidateInvitations: {
area: "candidate",
title: "Приглашения",
planned: [
"Предложения компаний с вилкой зарплаты",
"Принятие или отказ",
"Какие компании получили доступ к контактам",
],
},
candidatePrivacy: {
area: "candidate",
title: "Приватность",
@@ -12,6 +12,7 @@ const cabinets = [
features: [
"Заявленный уровень из анкеты показан отдельно от подтвержденной категории.",
"Категория появляется только по результату теста. Демонстрационный результат помечен как демонстрационный.",
"Приглашения компаний: условия, принятие с выбором контактов и отказ.",
"Согласия, публикация карточки, статус поиска, уведомления и обращения в поддержку.",
],
},
@@ -62,8 +63,8 @@ export function WelcomePage() {
</Section>
<Section title="Пока не готово">
<p>
Входящие приглашения кандидата, их принятие и список приглашений, отправленных компанией,
пока заготовки: эти экраны не показывают данных и не выполняют действий.
Список приглашений, отправленных компанией, пока заготовка: этот экран не показывает
данных и не выполняет действий.
</p>
</Section>
<Section title="Вход и регистрация">
+3
View File
@@ -20,6 +20,9 @@ export const paths = {
results: "/candidate/results",
result: (attemptId: string) => `/candidate/results/${encodeURIComponent(attemptId)}`,
invitations: "/candidate/invitations",
/** One invitation addressed to the current candidate; the id is an opaque UUID. */
invitation: (invitationId: string) =>
`/candidate/invitations/${encodeURIComponent(invitationId)}`,
notifications: "/candidate/notifications",
privacy: "/candidate/privacy",
supportCases: "/candidate/support/cases",
@@ -1,4 +1,6 @@
// Public API of the invitation-preview widget: the company card and the
// terms of an invitation as the candidate sees them.
// terms of an invitation as the candidate sees them, and the terms alone for
// a candidate reading an invitation addressed to them.
export { InvitationPreview } from "./ui/invitation-preview";
export { InvitationTermsArticle } from "./ui/invitation-terms";
@@ -1,17 +1,7 @@
import type { ReactNode } from "react";
import type { CandidateOrganizationCard, InvitationTerms } from "../../../shared/api/schemas";
import { CompanyCardView } from "../../../entities/company";
import {
communicationChannelLabels,
formatSalaryRange,
formatServerMoment,
notProvidedLabel,
offerTypeLabels,
packageItemKeys,
packageItemLabels,
responsePeriodLabel,
} from "../../../entities/invitation";
import { gradeLabels, specializationLabels, workFormatLabels } from "../../../entities/match";
import { InvitationTermsArticle } from "./invitation-terms";
import styles from "./invitation-preview.module.css";
type InvitationPreviewProps = {
@@ -40,12 +30,6 @@ export function InvitationPreview({
responseDeadlineAt,
title = "Так приглашение увидит кандидат",
}: InvitationPreviewProps) {
const location =
terms.location ??
(terms.work_formats.every((format) => format === "remote")
? "Не требуется: только удаленная работа"
: "Не указано");
return (
<div className={styles.root}>
<div className={styles.heading}>
@@ -58,89 +42,11 @@ export function InvitationPreview({
<section className={styles.company} aria-label="Компания">
{card ? <CompanyCardView card={card} headingLevel={4} /> : cardFallback}
</section>
<article className={styles.terms} aria-label="Условия приглашения">
<h4 className={styles.role}>{terms.role_title}</h4>
<dl className={styles.facts}>
<div className={styles.fact}>
<dt>Специализация и грейд</dt>
<dd>{`${specializationLabels[terms.specialization]}, ${gradeLabels[terms.grade]}`}</dd>
</div>
<div className={styles.fact}>
<dt>Тип предложения</dt>
<dd>{offerTypeLabels[terms.offer_type]}</dd>
</div>
<div className={styles.fact}>
<dt>Задачи</dt>
<dd>
<ul className={styles.list}>
{terms.tasks.map((task, index) => (
<li key={`${index}-${task}`}>{task}</li>
))}
</ul>
</dd>
</div>
<div className={styles.fact}>
<dt>Команда</dt>
<dd className={styles.multiline}>{terms.team}</dd>
</div>
<div className={styles.fact}>
<dt>Технологии</dt>
<dd>{terms.tech_stack.join(", ")}</dd>
</div>
<div className={styles.fact}>
<dt>Формат работы</dt>
<dd>{terms.work_formats.map((format) => workFormatLabels[format]).join(", ")}</dd>
</div>
<div className={styles.fact}>
<dt>Место работы</dt>
<dd>{location}</dd>
</div>
<div className={styles.fact}>
<dt>Зарплатная вилка</dt>
<dd data-term="salary">{formatSalaryRange(terms.salary)}</dd>
</div>
<div className={styles.fact}>
<dt>Способ связи после принятия</dt>
<dd data-term="communication">
{communicationChannelLabels[terms.communication_method.channel]}
{terms.communication_method.details
? `. ${terms.communication_method.details}`
: null}
</dd>
</div>
<div className={styles.fact}>
<dt>Пакет</dt>
<dd>
<dl className={styles.package}>
{packageItemKeys.map((key) => {
const item = terms.package[key];
return (
<div key={key} className={styles.fact} data-package={key}>
<dt>{packageItemLabels[key]}</dt>
<dd>{item.status === "provided" ? item.description : notProvidedLabel}</dd>
</div>
);
})}
</dl>
</dd>
</div>
<div className={styles.fact}>
<dt>Срок ответа</dt>
<dd>
{responseDeadlineAt ? (
<>
{"До "}
<time dateTime={responseDeadlineAt}>
{formatServerMoment(responseDeadlineAt)}
</time>
</>
) : (
`${responsePeriodLabel(responsePeriodDays)} с момента доставки`
)}
</dd>
</div>
</dl>
</article>
<InvitationTermsArticle
terms={terms}
responsePeriodDays={responsePeriodDays}
responseDeadlineAt={responseDeadlineAt}
/>
</div>
);
}
@@ -0,0 +1,52 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { candidateTerms, openDeadline } from "../../../entities/invitation/testing";
import { InvitationTermsArticle } from "./invitation-terms";
describe("invitation terms article", () => {
it("shows the server deadline with its UTC label when the invitation is delivered", () => {
const html = renderToStaticMarkup(
<InvitationTermsArticle
terms={candidateTerms}
responsePeriodDays={null}
responseDeadlineAt={openDeadline}
/>,
);
expect(html).toMatch(/<dt>Срок ответа<\/dt><dd>До <time dateTime="2099-10-16T10:00:00Z">/);
expect(html).toMatch(/UTC<\/time>/);
});
it("shows the answer period for an unsent draft and no deadline row without either", () => {
const draft = renderToStaticMarkup(
<InvitationTermsArticle
terms={candidateTerms}
responsePeriodDays={7}
responseDeadlineAt={null}
/>,
);
expect(draft).toContain("7 дней с момента доставки");
const bare = renderToStaticMarkup(
<InvitationTermsArticle
terms={candidateTerms}
responsePeriodDays={null}
responseDeadlineAt={null}
/>,
);
expect(bare).not.toContain("Срок ответа");
});
it("uses the heading level of the page outline", () => {
const html = renderToStaticMarkup(
<InvitationTermsArticle
terms={candidateTerms}
responsePeriodDays={null}
responseDeadlineAt={null}
headingLevel={3}
/>,
);
expect(html).toMatch(/<h3 class="[^"]*">Middle Go-разработчик/);
});
});
@@ -0,0 +1,130 @@
import type { InvitationTerms } from "../../../shared/api/schemas";
import {
communicationChannelLabels,
formatSalaryRange,
formatServerMoment,
notProvidedLabel,
offerTypeLabels,
packageItemKeys,
packageItemLabels,
responsePeriodLabel,
} from "../../../entities/invitation";
import { gradeLabels, specializationLabels, workFormatLabels } from "../../../entities/match";
import styles from "./invitation-preview.module.css";
type InvitationTermsArticleProps = {
terms: InvitationTerms;
/**
* Days to answer, shown while no deadline exists yet (an unsent draft).
* Null when the server deadline is shown instead.
*/
responsePeriodDays: number | null;
/** The server deadline once the invitation is delivered; null for an unsent draft. */
responseDeadlineAt: string | null;
/** The role name is a heading below the section title; the page outline sets its level. */
headingLevel?: 3 | 4;
};
/**
* Every term of an invitation, as the candidate sees it: each package
* condition with its description or as explicitly not provided, the salary
* range with its tax basis, and the answer deadline. It renders data only.
* Both the organization preview and the candidate's invitation use it.
*/
export function InvitationTermsArticle({
terms,
responsePeriodDays,
responseDeadlineAt,
headingLevel = 4,
}: InvitationTermsArticleProps) {
const location =
terms.location ??
(terms.work_formats.every((format) => format === "remote")
? "Не требуется: только удаленная работа"
: "Не указано");
const RoleHeading = headingLevel === 3 ? "h3" : "h4";
const responseLine =
responseDeadlineAt !== null ? (
<>
{"До "}
<time dateTime={responseDeadlineAt}>{formatServerMoment(responseDeadlineAt)}</time>
</>
) : responsePeriodDays !== null ? (
`${responsePeriodLabel(responsePeriodDays)} с момента доставки`
) : null;
return (
<article className={styles.terms} aria-label="Условия приглашения">
<RoleHeading className={styles.role}>{terms.role_title}</RoleHeading>
<dl className={styles.facts}>
<div className={styles.fact}>
<dt>Специализация и грейд</dt>
<dd>{`${specializationLabels[terms.specialization]}, ${gradeLabels[terms.grade]}`}</dd>
</div>
<div className={styles.fact}>
<dt>Тип предложения</dt>
<dd>{offerTypeLabels[terms.offer_type]}</dd>
</div>
<div className={styles.fact}>
<dt>Задачи</dt>
<dd>
<ul className={styles.list}>
{terms.tasks.map((task, index) => (
<li key={`${index}-${task}`}>{task}</li>
))}
</ul>
</dd>
</div>
<div className={styles.fact}>
<dt>Команда</dt>
<dd className={styles.multiline}>{terms.team}</dd>
</div>
<div className={styles.fact}>
<dt>Технологии</dt>
<dd>{terms.tech_stack.join(", ")}</dd>
</div>
<div className={styles.fact}>
<dt>Формат работы</dt>
<dd>{terms.work_formats.map((format) => workFormatLabels[format]).join(", ")}</dd>
</div>
<div className={styles.fact}>
<dt>Место работы</dt>
<dd>{location}</dd>
</div>
<div className={styles.fact}>
<dt>Зарплатная вилка</dt>
<dd data-term="salary">{formatSalaryRange(terms.salary)}</dd>
</div>
<div className={styles.fact}>
<dt>Способ связи после принятия</dt>
<dd data-term="communication">
{communicationChannelLabels[terms.communication_method.channel]}
{terms.communication_method.details ? `. ${terms.communication_method.details}` : null}
</dd>
</div>
<div className={styles.fact}>
<dt>Пакет</dt>
<dd>
<dl className={styles.package}>
{packageItemKeys.map((key) => {
const item = terms.package[key];
return (
<div key={key} className={styles.fact} data-package={key}>
<dt>{packageItemLabels[key]}</dt>
<dd>{item.status === "provided" ? item.description : notProvidedLabel}</dd>
</div>
);
})}
</dl>
</dd>
</div>
{responseLine !== null ? (
<div className={styles.fact}>
<dt>Срок ответа</dt>
<dd>{responseLine}</dd>
</div>
) : null}
</dl>
</article>
);
}