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,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>
);
}