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

@@ -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";