feat(invitations): add the invitation compose screen with a candidate-side preview
This commit is contained in:
1 parent
1a067221f7
commit
cb08f212cc
35 files changed
+4170
-67
No files matched your search
@@ -173,6 +173,7 @@ describe("route groups", () => {
|
||||
["/employer/support/cases", "Мои обращения", "Разделы кабинета работодателя"],
|
||||
["/employer/support/cases/new", "Обратиться в поддержку", "Разделы кабинета работодателя"],
|
||||
["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"],
|
||||
["/employer/invitations/new", "Приглашение кандидату", "Разделы кабинета работодателя"],
|
||||
])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => {
|
||||
const html = await renderHtml(path);
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { CompanyPage } from "../../pages/company";
|
||||
import { PrivacyPage } from "../../pages/privacy";
|
||||
import { SessionGate } from "../../entities/session";
|
||||
import { MatchesPage } from "../../pages/matches";
|
||||
import { InvitationComposePage } from "../../pages/invitation-compose";
|
||||
import { NotFoundPage } from "../../pages/not-found";
|
||||
import { NeedEditorPage } from "../../pages/need-editor";
|
||||
import { NeedListPage } from "../../pages/needs";
|
||||
@@ -131,6 +132,7 @@ export const routes: RouteObject[] = [
|
||||
path: paths.employer.invitations,
|
||||
element: <PlaceholderPage screen="employerInvitations" />,
|
||||
},
|
||||
{ path: paths.employer.invitationNew, element: <InvitationComposePage /> },
|
||||
{ path: paths.employer.notifications, element: <EmployerNotificationsPage /> },
|
||||
{
|
||||
path: "*",
|
||||
|
||||
@@ -13,4 +13,4 @@ export {
|
||||
organizationTrustLevel,
|
||||
candidateCardLevelLabels,
|
||||
} from "./model/verification-labels";
|
||||
export { CandidateCardPreview } from "./ui/candidate-card-preview";
|
||||
export { CandidateCardPreview, CompanyCardView } from "./ui/candidate-card-preview";
|
||||
@@ -63,7 +63,8 @@
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.representatives h4 {
|
||||
.representatives h4,
|
||||
.representatives h5 {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
|
||||
@@ -16,55 +16,74 @@ const contactLabels = {
|
||||
telegram: "Telegram компании",
|
||||
} as const;
|
||||
|
||||
export function CandidateCardPreview({ card }: CandidateCardPreviewProps) {
|
||||
type CompanyCardViewProps = {
|
||||
card: CandidateCard;
|
||||
/** Level of the company name heading inside the surrounding outline. */
|
||||
headingLevel?: 3 | 4;
|
||||
};
|
||||
|
||||
/**
|
||||
* The card of the organization exactly as a candidate sees it, built from
|
||||
* `candidate_card` that the server returns to the owner. It shows no
|
||||
* membership, role, account, or verification basis.
|
||||
*/
|
||||
export function CompanyCardView({ card, headingLevel = 3 }: CompanyCardViewProps) {
|
||||
const contacts = (Object.keys(contactLabels) as (keyof typeof contactLabels)[]).flatMap((key) => {
|
||||
const value = card.contacts[key];
|
||||
return value ? [{ label: contactLabels[key], value }] : [];
|
||||
});
|
||||
const NameHeading = headingLevel === 3 ? "h3" : "h4";
|
||||
const SubHeading = headingLevel === 3 ? "h4" : "h5";
|
||||
|
||||
return (
|
||||
<article className={styles.card} aria-label="Предпросмотр карточки компании">
|
||||
<header className={styles.header}>
|
||||
<div>
|
||||
<NameHeading className={styles.name}>{card.name}</NameHeading>
|
||||
<p className={styles.level}>
|
||||
<TrustLevel
|
||||
level={organizationTrustLevel[card.verification_level]}
|
||||
label={candidateCardLevelLabels[card.verification_level]}
|
||||
/>
|
||||
</p>
|
||||
</div>
|
||||
{card.sphere ? <p className={styles.sphere}>{card.sphere}</p> : null}
|
||||
</header>
|
||||
{card.description ? <p className={styles.description}>{card.description}</p> : null}
|
||||
{contacts.length > 0 ? (
|
||||
<dl className={styles.contacts}>
|
||||
{contacts.map(({ label, value }) => (
|
||||
<div className={styles.contact} key={label}>
|
||||
<dt>{label}</dt>
|
||||
<dd>{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
) : null}
|
||||
{card.representatives && card.representatives.length > 0 ? (
|
||||
<div className={styles.representatives}>
|
||||
<SubHeading>Представители компании</SubHeading>
|
||||
<ul>
|
||||
{card.representatives.map((representative, index) => (
|
||||
<li key={`${representative.name}-${index}`}>
|
||||
<span>{representative.name}</span>
|
||||
<span>{representative.job_title}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export function CandidateCardPreview({ card }: CandidateCardPreviewProps) {
|
||||
return (
|
||||
<Section
|
||||
title="Так карточку увидит кандидат"
|
||||
description="Проверьте описание и контакты, которые увидит кандидат."
|
||||
>
|
||||
<article className={styles.card} aria-label="Предпросмотр карточки компании">
|
||||
<header className={styles.header}>
|
||||
<div>
|
||||
<h3 className={styles.name}>{card.name}</h3>
|
||||
<p className={styles.level}>
|
||||
<TrustLevel
|
||||
level={organizationTrustLevel[card.verification_level]}
|
||||
label={candidateCardLevelLabels[card.verification_level]}
|
||||
/>
|
||||
</p>
|
||||
</div>
|
||||
{card.sphere ? <p className={styles.sphere}>{card.sphere}</p> : null}
|
||||
</header>
|
||||
{card.description ? <p className={styles.description}>{card.description}</p> : null}
|
||||
{contacts.length > 0 ? (
|
||||
<dl className={styles.contacts}>
|
||||
{contacts.map(({ label, value }) => (
|
||||
<div className={styles.contact} key={label}>
|
||||
<dt>{label}</dt>
|
||||
<dd>{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
) : null}
|
||||
{card.representatives && card.representatives.length > 0 ? (
|
||||
<div className={styles.representatives}>
|
||||
<h4>Представители компании</h4>
|
||||
<ul>
|
||||
{card.representatives.map((representative, index) => (
|
||||
<li key={`${representative.name}-${index}`}>
|
||||
<span>{representative.name}</span>
|
||||
<span>{representative.job_title}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
<CompanyCardView card={card} />
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
|
||||
import {
|
||||
createOrganizationInvitation,
|
||||
getGetOrganizationInvitationQueryKey,
|
||||
getOrganizationInvitation,
|
||||
sendOrganizationInvitation,
|
||||
updateOrganizationInvitation,
|
||||
} from "../../../shared/api/endpoints/invitation/invitation";
|
||||
import {
|
||||
OrganizationInvitation as organizationInvitationSchema,
|
||||
type OrganizationInvitation,
|
||||
type OrganizationInvitationCreate,
|
||||
type OrganizationInvitationUpdate,
|
||||
} from "../../../shared/api/schemas";
|
||||
|
||||
// Transport adapters of the organization 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 delivered invitation.
|
||||
|
||||
function invalidResponse(): ApiRequestError {
|
||||
return new ApiRequestError({
|
||||
status: 200,
|
||||
code: invalidResponseCode,
|
||||
title: "The response does not match the API contract.",
|
||||
});
|
||||
}
|
||||
|
||||
function parseInvitation(value: unknown): OrganizationInvitation {
|
||||
const parsed = organizationInvitationSchema.safeParse(value);
|
||||
if (!parsed.success) throw invalidResponse();
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
type CommandOptions = {
|
||||
organizationId: string;
|
||||
csrfToken: string;
|
||||
signal?: AbortSignal | undefined;
|
||||
};
|
||||
|
||||
function requestOptions(csrfToken: string, signal: AbortSignal | undefined): RequestInit {
|
||||
return { headers: { "X-CSRF-Token": csrfToken }, ...(signal ? { signal } : {}) };
|
||||
}
|
||||
|
||||
/** Creates a draft under an Idempotency-Key; a retry with the same key and body replays it. */
|
||||
export async function createInvitationDraft(
|
||||
options: CommandOptions & { body: OrganizationInvitationCreate; idempotencyKey: string },
|
||||
): Promise<OrganizationInvitation> {
|
||||
return parseInvitation(
|
||||
await createOrganizationInvitation(
|
||||
options.organizationId,
|
||||
options.body,
|
||||
{ "Idempotency-Key": options.idempotencyKey },
|
||||
requestOptions(options.csrfToken, options.signal),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Replaces the terms of a draft over the version the client read. */
|
||||
export async function updateInvitationDraft(
|
||||
options: CommandOptions & { invitationId: string; body: OrganizationInvitationUpdate },
|
||||
): Promise<OrganizationInvitation> {
|
||||
return parseInvitation(
|
||||
await updateOrganizationInvitation(
|
||||
options.organizationId,
|
||||
options.invitationId,
|
||||
options.body,
|
||||
requestOptions(options.csrfToken, options.signal),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Sends the current terms version of a draft under an Idempotency-Key. */
|
||||
export async function sendInvitationDraft(
|
||||
options: CommandOptions & {
|
||||
invitationId: string;
|
||||
expectedVersion: number;
|
||||
idempotencyKey: string;
|
||||
},
|
||||
): Promise<OrganizationInvitation> {
|
||||
return parseInvitation(
|
||||
await sendOrganizationInvitation(
|
||||
options.organizationId,
|
||||
options.invitationId,
|
||||
{ expected_version: options.expectedVersion },
|
||||
{ "Idempotency-Key": options.idempotencyKey },
|
||||
requestOptions(options.csrfToken, options.signal),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Reads one invitation of the organization and checks it against the contract. */
|
||||
export async function readOrganizationInvitation(
|
||||
organizationId: string,
|
||||
invitationId: string,
|
||||
signal: AbortSignal | undefined = undefined,
|
||||
): Promise<OrganizationInvitation> {
|
||||
return parseInvitation(
|
||||
await getOrganizationInvitation(organizationId, invitationId, signal ? { signal } : {}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Invitation reads stay separate for each signed-in account. */
|
||||
export const invitationQueryKeys = {
|
||||
detail: (accountId: string, organizationId: string, invitationId: string) =>
|
||||
[...getGetOrganizationInvitationQueryKey(organizationId, invitationId), accountId] as const,
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
// 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.
|
||||
|
||||
export {
|
||||
createInvitationDraft,
|
||||
invitationQueryKeys,
|
||||
readOrganizationInvitation,
|
||||
sendInvitationDraft,
|
||||
updateInvitationDraft,
|
||||
} from "./api/organization-invitations";
|
||||
export { formatRubles, formatSalaryRange, formatServerMoment } from "./model/format";
|
||||
export {
|
||||
communicationChannelCodes,
|
||||
communicationChannelLabels,
|
||||
defaultResponsePeriod,
|
||||
invitationStateLabels,
|
||||
notProvidedLabel,
|
||||
offerTypeCodes,
|
||||
offerTypeLabels,
|
||||
packageItemKeys,
|
||||
packageItemLabels,
|
||||
responsePeriodLabel,
|
||||
responsePeriods,
|
||||
salaryFitLabels,
|
||||
taxBasisLabels,
|
||||
type InvitationPackageKey,
|
||||
} from "./model/labels";
|
||||
export {
|
||||
salaryMax,
|
||||
salaryRangeIssue,
|
||||
salaryStep,
|
||||
type SalaryRangeIssue,
|
||||
} from "./model/salary-range";
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { SalaryRange } from "../../../shared/api/schemas";
|
||||
import { taxBasisLabels } from "./labels";
|
||||
|
||||
const rubles = new Intl.NumberFormat("ru-RU", { maximumFractionDigits: 0 });
|
||||
|
||||
/** Whole rubles with the Russian digit grouping, for example "140 000 ₽". */
|
||||
export function formatRubles(amount: number): string {
|
||||
return `${rubles.format(amount)} ₽`;
|
||||
}
|
||||
|
||||
/** The salary range with its period and tax basis; the basis is never implied. */
|
||||
export function formatSalaryRange(salary: SalaryRange): string {
|
||||
return `от ${formatRubles(salary.salary_from)} до ${formatRubles(salary.salary_to)} в месяц, ${taxBasisLabels[salary.tax_basis].toLocaleLowerCase("ru-RU")}`;
|
||||
}
|
||||
|
||||
const moment = new Intl.DateTimeFormat("ru-RU", {
|
||||
dateStyle: "long",
|
||||
timeStyle: "short",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
/**
|
||||
* A server timestamp in UTC with the zone named, so the deadline reads the
|
||||
* same for both parties regardless of the browser's zone.
|
||||
*/
|
||||
export function formatServerMoment(value: string): string {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
return `${moment.format(date)} UTC`;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type {
|
||||
InvitationCommunicationChannel,
|
||||
InvitationOfferType,
|
||||
InvitationPackage,
|
||||
InvitationResponsePeriod,
|
||||
InvitationSalaryFit,
|
||||
InvitationState,
|
||||
SalaryTaxBasis,
|
||||
} from "../../../shared/api/schemas";
|
||||
|
||||
export type InvitationPackageKey = keyof InvitationPackage;
|
||||
|
||||
export const offerTypeLabels: Readonly<Record<InvitationOfferType, string>> = {
|
||||
full_time: "Полная занятость",
|
||||
part_time: "Частичная занятость",
|
||||
contract: "Договор на проект или срок",
|
||||
internship: "Стажировка",
|
||||
};
|
||||
|
||||
export const offerTypeCodes = Object.keys(offerTypeLabels) as InvitationOfferType[];
|
||||
|
||||
export const communicationChannelLabels: Readonly<Record<InvitationCommunicationChannel, string>> =
|
||||
{
|
||||
email: "Электронная почта",
|
||||
phone: "Телефон",
|
||||
telegram: "Telegram",
|
||||
video_call: "Видеозвонок",
|
||||
};
|
||||
|
||||
export const communicationChannelCodes = Object.keys(
|
||||
communicationChannelLabels,
|
||||
) as InvitationCommunicationChannel[];
|
||||
|
||||
/** The four required conditions of the package in the order of the contract. */
|
||||
export const packageItemLabels: Readonly<Record<InvitationPackageKey, string>> = {
|
||||
bonus: "Премии и бонусы",
|
||||
equipment: "Оборудование",
|
||||
training: "Обучение",
|
||||
health_insurance: "ДМС",
|
||||
};
|
||||
|
||||
export const packageItemKeys = Object.keys(packageItemLabels) as InvitationPackageKey[];
|
||||
|
||||
/** Wording of an explicit `not_provided` condition, as the contract names it. */
|
||||
export const notProvidedLabel = "Не предусмотрено";
|
||||
|
||||
export const taxBasisLabels: Readonly<Record<SalaryTaxBasis, string>> = {
|
||||
net: "После налога (net)",
|
||||
gross: "До налога (gross)",
|
||||
};
|
||||
|
||||
export const responsePeriods: readonly InvitationResponsePeriod[] = [3, 7, 14];
|
||||
|
||||
export const defaultResponsePeriod: InvitationResponsePeriod = 7;
|
||||
|
||||
export function responsePeriodLabel(days: number): string {
|
||||
const lastTwo = days % 100;
|
||||
const last = days % 10;
|
||||
if (lastTwo >= 11 && lastTwo <= 14) return `${days} дней`;
|
||||
if (last === 1) return `${days} день`;
|
||||
if (last >= 2 && last <= 4) return `${days} дня`;
|
||||
return `${days} дней`;
|
||||
}
|
||||
|
||||
export const invitationStateLabels: Readonly<Record<InvitationState, string>> = {
|
||||
draft: "Черновик",
|
||||
delivered: "Доставлено",
|
||||
viewed: "Просмотрено кандидатом",
|
||||
counter: "Встречное предложение",
|
||||
accepted: "Принято",
|
||||
interview_scheduled: "Назначено интервью",
|
||||
interviewed: "Интервью проведено",
|
||||
negotiation: "Переговоры",
|
||||
terms_agreed: "Условия согласованы",
|
||||
no_deal: "Без сделки",
|
||||
declined: "Отклонено",
|
||||
expired: "Срок ответа истек",
|
||||
withdrawn: "Отозвано компанией",
|
||||
cancelled_by_candidate: "Отменено кандидатом",
|
||||
};
|
||||
|
||||
export const salaryFitLabels: Readonly<Record<InvitationSalaryFit, string>> = {
|
||||
within_range: "Ожидания кандидата не выше верхней границы вилки",
|
||||
up_to_10_percent_above: "Ожидания выше верхней границы не более чем на 10%",
|
||||
above: "Ожидания выше верхней границы более чем на 10%",
|
||||
withheld: "Индикатор временно скрыт: много изменений вилок за неделю",
|
||||
not_available: "Индикатор недоступен: кандидат не задал ожидания для этих условий",
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { salaryRangeIssue } from "./salary-range";
|
||||
|
||||
describe("salary range rules", () => {
|
||||
it.each([
|
||||
[100_000, 140_000],
|
||||
[95_000, 105_000],
|
||||
[80_000, 120_000],
|
||||
])("accepts [%i; %i], including the 10%% and 40%% edges", (from, to) => {
|
||||
expect(salaryRangeIssue(from, to)).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[100_500, 140_000, "bound"],
|
||||
[0, 140_000, "bound"],
|
||||
[100_000, 100_001_000, "bound"],
|
||||
[140_000, 100_000, "order"],
|
||||
[100_000, 100_000, "order"],
|
||||
[100_000, 105_000, "narrow"],
|
||||
[79_000, 121_000, "wide"],
|
||||
] as const)("rejects [%i; %i] as %s", (from, to, issue) => {
|
||||
expect(salaryRangeIssue(from, to)).toBe(issue);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
// Client mirror of the SalaryRange rules of the contract, for immediate
|
||||
// feedback only: the server checks the same rules in integer arithmetic and
|
||||
// stays the source of truth.
|
||||
|
||||
export const salaryStep = 1000;
|
||||
export const salaryMax = 100_000_000;
|
||||
|
||||
/**
|
||||
* Why a salary range is not acceptable.
|
||||
*
|
||||
* - bound: a bound is not a positive whole multiple of 1000 within the limit.
|
||||
* - order: the lower bound is not below the upper bound.
|
||||
* - narrow: the width is below 10% of the midpoint.
|
||||
* - wide: the width is above 40% of the midpoint.
|
||||
*/
|
||||
export type SalaryRangeIssue = "bound" | "order" | "narrow" | "wide";
|
||||
|
||||
function validBound(value: number): boolean {
|
||||
return (
|
||||
Number.isSafeInteger(value) &&
|
||||
value >= salaryStep &&
|
||||
value <= salaryMax &&
|
||||
value % salaryStep === 0
|
||||
);
|
||||
}
|
||||
|
||||
/** Checks `[from; to]`; widths of exactly 10% and 40% are accepted. */
|
||||
export function salaryRangeIssue(from: number, to: number): SalaryRangeIssue | null {
|
||||
if (!validBound(from) || !validBound(to)) return "bound";
|
||||
if (from >= to) return "order";
|
||||
const width = to - from;
|
||||
const total = from + to;
|
||||
if (20 * width < total) return "narrow";
|
||||
if (5 * width > total) return "wide";
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Public API of the send-invitation feature: the draft of the terms, its
|
||||
// client validation, the idempotent create-update-send command, and the form
|
||||
// that runs it. The page supplies the preview and reacts to the result.
|
||||
|
||||
export {
|
||||
emptyInvitationDraft,
|
||||
invitationDraftFromNeed,
|
||||
invitationDraftFromTerms,
|
||||
toInvitationTerms,
|
||||
type InvitationDraft,
|
||||
} from "./model/draft";
|
||||
export { initialSendProgress, type SendProgress } from "./model/send-command";
|
||||
export {
|
||||
InvitationForm,
|
||||
type InvitationFormProps,
|
||||
type InvitationPreviewSnapshot,
|
||||
} from "./ui/invitation-form";
|
||||
@@ -0,0 +1,29 @@
|
||||
import { emptyInvitationDraft, type InvitationDraft } from "./draft";
|
||||
|
||||
/** A draft that passes validation: [100000; 140000] net and a mixed package. */
|
||||
export function completeDraft(overrides: Partial<InvitationDraft> = {}): InvitationDraft {
|
||||
const base = emptyInvitationDraft("backend");
|
||||
return {
|
||||
...base,
|
||||
roleTitle: "Middle Go-разработчик в команду платежей",
|
||||
grade: "middle",
|
||||
offerType: "full_time",
|
||||
tasks: "Развивать сервис выплат\n \nПеревести отчеты на события",
|
||||
team: "Пять бэкенд-разработчиков и QA-инженер.",
|
||||
techStack: "Go, PostgreSQL,\nKafka",
|
||||
workFormats: ["remote", "hybrid"],
|
||||
location: "Москва",
|
||||
channel: "video_call",
|
||||
channelDetails: "Созвон с тимлидом в течение трех рабочих дней",
|
||||
salaryFrom: "100000",
|
||||
salaryTo: "140000",
|
||||
taxBasis: "net",
|
||||
packageItems: {
|
||||
bonus: { status: "provided", description: "Квартальная премия до 20%" },
|
||||
equipment: { status: "provided", description: "Ноутбук и монитор" },
|
||||
training: { status: "not_provided", description: "" },
|
||||
health_insurance: { status: "not_provided", description: "" },
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import type {
|
||||
GradeCode,
|
||||
InvitationCommunicationChannel,
|
||||
InvitationOfferType,
|
||||
InvitationResponsePeriod,
|
||||
InvitationTerms,
|
||||
Need,
|
||||
SalaryTaxBasis,
|
||||
SpecializationCode,
|
||||
WorkFormat,
|
||||
} from "../../../shared/api/schemas";
|
||||
import {
|
||||
defaultResponsePeriod,
|
||||
packageItemKeys,
|
||||
type InvitationPackageKey,
|
||||
} from "../../../entities/invitation";
|
||||
import { fromTransport } from "../../../entities/need";
|
||||
|
||||
// The form draft of an invitation. It keeps what the employer typed as
|
||||
// strings, so a half-filled field is never coerced into a default value;
|
||||
// toInvitationTerms turns a validated draft into the transport terms.
|
||||
|
||||
export type PackageChoice = "" | "provided" | "not_provided";
|
||||
|
||||
export interface PackageItemDraft {
|
||||
readonly status: PackageChoice;
|
||||
readonly description: string;
|
||||
}
|
||||
|
||||
export interface InvitationDraft {
|
||||
readonly roleTitle: string;
|
||||
readonly specialization: SpecializationCode | "";
|
||||
readonly grade: GradeCode | "";
|
||||
readonly offerType: InvitationOfferType | "";
|
||||
/** One task per line. */
|
||||
readonly tasks: string;
|
||||
readonly team: string;
|
||||
/** Technologies separated by commas or line breaks. */
|
||||
readonly techStack: string;
|
||||
readonly workFormats: readonly WorkFormat[];
|
||||
readonly location: string;
|
||||
readonly channel: InvitationCommunicationChannel | "";
|
||||
readonly channelDetails: string;
|
||||
readonly salaryFrom: string;
|
||||
readonly salaryTo: string;
|
||||
readonly taxBasis: SalaryTaxBasis | "";
|
||||
readonly packageItems: Readonly<Record<InvitationPackageKey, PackageItemDraft>>;
|
||||
readonly responsePeriodDays: InvitationResponsePeriod;
|
||||
}
|
||||
|
||||
const emptyPackageItem: PackageItemDraft = { status: "", description: "" };
|
||||
|
||||
/** A blank draft; no package condition is preselected, because each is an explicit choice. */
|
||||
export function emptyInvitationDraft(
|
||||
specialization: SpecializationCode | "" = "",
|
||||
): InvitationDraft {
|
||||
return {
|
||||
roleTitle: "",
|
||||
specialization,
|
||||
grade: "",
|
||||
offerType: "",
|
||||
tasks: "",
|
||||
team: "",
|
||||
techStack: "",
|
||||
workFormats: [],
|
||||
location: "",
|
||||
channel: "",
|
||||
channelDetails: "",
|
||||
salaryFrom: "",
|
||||
salaryTo: "",
|
||||
taxBasis: "",
|
||||
packageItems: Object.fromEntries(
|
||||
packageItemKeys.map((key) => [key, emptyPackageItem]),
|
||||
) as Record<InvitationPackageKey, PackageItemDraft>,
|
||||
responsePeriodDays: defaultResponsePeriod,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefills a draft from the confirmed requirements of a need. Values that
|
||||
* nobody confirmed stay empty, and the specialization of the search entry
|
||||
* wins over the need, because the invitation is for that entry.
|
||||
*/
|
||||
export function invitationDraftFromNeed(
|
||||
need: Need,
|
||||
specialization: SpecializationCode | "",
|
||||
): InvitationDraft {
|
||||
const values = fromTransport(need);
|
||||
const draft = emptyInvitationDraft(specialization);
|
||||
const confirmed = <T>(state: { status: string; value?: T }): T | undefined =>
|
||||
state.status === "confirmed" ? state.value : undefined;
|
||||
const salary = confirmed(values.salary);
|
||||
const workFormats = confirmed(values.workFormats);
|
||||
const needSpecialization = confirmed(values.specialization);
|
||||
return {
|
||||
...draft,
|
||||
roleTitle: need.title,
|
||||
specialization: specialization || needSpecialization || "",
|
||||
grade: confirmed(values.grade) ?? "",
|
||||
tasks: values.tasks
|
||||
.filter((task) => task.status === "confirmed")
|
||||
.map((task) => task.text)
|
||||
.join("\n"),
|
||||
techStack: values.requiredSkills
|
||||
.filter((skill) => skill.status === "confirmed")
|
||||
.map((skill) => skill.name)
|
||||
.join(", "),
|
||||
workFormats: workFormats ? [...workFormats] : [],
|
||||
location: confirmed(values.location) ?? "",
|
||||
salaryFrom: salary ? String(salary.from) : "",
|
||||
salaryTo: salary ? String(salary.to) : "",
|
||||
taxBasis: salary?.taxBasis ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
/** Restores the draft of stored terms, for example when a saved draft is reopened. */
|
||||
export function invitationDraftFromTerms(
|
||||
terms: InvitationTerms,
|
||||
responsePeriodDays: InvitationResponsePeriod,
|
||||
): InvitationDraft {
|
||||
return {
|
||||
roleTitle: terms.role_title,
|
||||
specialization: terms.specialization,
|
||||
grade: terms.grade,
|
||||
offerType: terms.offer_type,
|
||||
tasks: terms.tasks.join("\n"),
|
||||
team: terms.team,
|
||||
techStack: terms.tech_stack.join(", "),
|
||||
workFormats: [...terms.work_formats],
|
||||
location: terms.location ?? "",
|
||||
channel: terms.communication_method.channel,
|
||||
channelDetails: terms.communication_method.details ?? "",
|
||||
salaryFrom: String(terms.salary.salary_from),
|
||||
salaryTo: String(terms.salary.salary_to),
|
||||
taxBasis: terms.salary.tax_basis,
|
||||
packageItems: Object.fromEntries(
|
||||
packageItemKeys.map((key) => {
|
||||
const item = terms.package[key];
|
||||
return [
|
||||
key,
|
||||
item.status === "provided"
|
||||
? { status: "provided", description: item.description }
|
||||
: { status: "not_provided", description: "" },
|
||||
];
|
||||
}),
|
||||
) as Record<InvitationPackageKey, PackageItemDraft>,
|
||||
responsePeriodDays,
|
||||
};
|
||||
}
|
||||
|
||||
/** Splits the task text into trimmed, non-empty lines. */
|
||||
export function taskLines(value: string): string[] {
|
||||
return value
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/** Splits the technology text at commas and line breaks. */
|
||||
export function techStackItems(value: string): string[] {
|
||||
return value
|
||||
.split(/[,\n]/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function optionalLine(value: string): string | null {
|
||||
const trimmed = value.trim();
|
||||
return trimmed === "" ? null : trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the transport terms of a draft. Call it only for a draft without
|
||||
* validation issues: it assumes every required choice is made.
|
||||
*/
|
||||
export function toInvitationTerms(draft: InvitationDraft): InvitationTerms {
|
||||
if (
|
||||
!draft.specialization ||
|
||||
!draft.grade ||
|
||||
!draft.offerType ||
|
||||
!draft.channel ||
|
||||
!draft.taxBasis
|
||||
) {
|
||||
throw new Error("The invitation draft has an unanswered required choice.");
|
||||
}
|
||||
return {
|
||||
role_title: draft.roleTitle.trim(),
|
||||
specialization: draft.specialization,
|
||||
grade: draft.grade,
|
||||
offer_type: draft.offerType,
|
||||
tasks: taskLines(draft.tasks),
|
||||
team: draft.team.trim(),
|
||||
tech_stack: techStackItems(draft.techStack),
|
||||
work_formats: [...draft.workFormats],
|
||||
// A remote-only role may still name a place; the server requires one
|
||||
// only for the office and hybrid formats.
|
||||
location: optionalLine(draft.location),
|
||||
communication_method: {
|
||||
channel: draft.channel,
|
||||
details: optionalLine(draft.channelDetails),
|
||||
},
|
||||
salary: {
|
||||
salary_from: Number(draft.salaryFrom),
|
||||
salary_to: Number(draft.salaryTo),
|
||||
currency: "RUB",
|
||||
period: "month",
|
||||
tax_basis: draft.taxBasis,
|
||||
},
|
||||
package: Object.fromEntries(
|
||||
packageItemKeys.map((key) => {
|
||||
const item = draft.packageItems[key];
|
||||
return [
|
||||
key,
|
||||
item.status === "provided"
|
||||
? { status: "provided", description: item.description.trim() }
|
||||
: { status: "not_provided" },
|
||||
];
|
||||
}),
|
||||
) as InvitationTerms["package"],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
|
||||
import { formatRetryAfter } from "../../../entities/match";
|
||||
import { issuesOfProblem, type InvitationIssue } from "./validate";
|
||||
import type { SendStage } from "./send-command";
|
||||
|
||||
/**
|
||||
* What the form shows after a failed attempt.
|
||||
*
|
||||
* - fields: the server rejected values; the issues are bound to fields.
|
||||
* - retry: the outcome is unknown or temporary; the next click repeats the
|
||||
* same command with the same Idempotency-Key.
|
||||
* - blocked: the server refused the command for a reason the form cannot fix.
|
||||
* - access: the session, the membership, or the role no longer allows it.
|
||||
* - csrf: the CSRF token is stale; the session must be read again.
|
||||
*/
|
||||
export type SendFailure =
|
||||
| {
|
||||
readonly kind: "fields";
|
||||
readonly issues: readonly InvitationIssue[];
|
||||
readonly message: string;
|
||||
}
|
||||
| { readonly kind: "retry"; readonly message: string }
|
||||
| { readonly kind: "blocked"; readonly message: string }
|
||||
| { readonly kind: "access"; readonly message: string }
|
||||
| { readonly kind: "csrf"; readonly message: string };
|
||||
|
||||
const sameKeyHint =
|
||||
"Нажмите «Отправить приглашение» еще раз: повтор использует тот же ключ и не создаст второе приглашение.";
|
||||
|
||||
function isAmbiguous(error: ApiRequestError): boolean {
|
||||
return error.status === 0 || error.status >= 500 || error.code === invalidResponseCode;
|
||||
}
|
||||
|
||||
/** Describes a failed send command without any value the employer did not type. */
|
||||
export function describeSendFailure(stage: SendStage, error: unknown): SendFailure {
|
||||
if (!(error instanceof ApiRequestError)) {
|
||||
return { kind: "retry", message: `Не удалось завершить отправку. ${sameKeyHint}` };
|
||||
}
|
||||
if (isAmbiguous(error)) {
|
||||
return {
|
||||
kind: "retry",
|
||||
message: `Сервер не подтвердил результат. ${sameKeyHint}`,
|
||||
};
|
||||
}
|
||||
if (error.status === 403 && error.code === "csrf_check_failed") {
|
||||
return {
|
||||
kind: "csrf",
|
||||
message: "Проверка входа устарела. Мы обновили ее; отправьте приглашение еще раз.",
|
||||
};
|
||||
}
|
||||
if (error.status === 401 || error.status === 403 || error.status === 404) {
|
||||
return {
|
||||
kind: "access",
|
||||
message:
|
||||
error.status === 401
|
||||
? "Сессия завершилась. Войдите снова; заполненные условия останутся на странице до перезагрузки."
|
||||
: "Нет доступа к приглашениям этой компании. Приглашать кандидатов может только владелец.",
|
||||
};
|
||||
}
|
||||
if (error.status === 400) {
|
||||
if (error.fieldErrors.some((field) => field.pointer === "/candidate_handle")) {
|
||||
return {
|
||||
kind: "blocked",
|
||||
message:
|
||||
"Кандидат больше недоступен компании. Вернитесь к поиску и выберите кандидата заново.",
|
||||
};
|
||||
}
|
||||
if (error.fieldErrors.some((field) => field.pointer.startsWith("/need"))) {
|
||||
return {
|
||||
kind: "blocked",
|
||||
message:
|
||||
"Потребность не найдена или ее версия устарела. Откройте приглашение из поиска заново.",
|
||||
};
|
||||
}
|
||||
const issues = issuesOfProblem(error.fieldErrors);
|
||||
return {
|
||||
kind: "fields",
|
||||
issues,
|
||||
message:
|
||||
issues.length > 0
|
||||
? "Сервер не принял условия. Исправьте отмеченные поля."
|
||||
: "Сервер не принял запрос. Проверьте условия и повторите.",
|
||||
};
|
||||
}
|
||||
if (error.status === 409 && error.code === "idempotency_in_progress") {
|
||||
return {
|
||||
kind: "retry",
|
||||
message: `Предыдущая попытка еще обрабатывается. Подождите несколько секунд. ${sameKeyHint}`,
|
||||
};
|
||||
}
|
||||
if (error.status === 409) {
|
||||
return {
|
||||
kind: "blocked",
|
||||
message:
|
||||
stage === "send"
|
||||
? "Сейчас этому кандидату нельзя отправить приглашение: профиль стал недоступен компании или действует ограничение. Приглашение не отправлено."
|
||||
: "Черновик уже нельзя изменить. Обновите страницу, чтобы увидеть его состояние.",
|
||||
};
|
||||
}
|
||||
if (error.status === 412) {
|
||||
return {
|
||||
kind: "retry",
|
||||
message:
|
||||
"Черновик изменился в другом окне. Мы загрузили его текущую версию; ваши условия применятся при следующей отправке.",
|
||||
};
|
||||
}
|
||||
if (error.status === 429) {
|
||||
const wait = formatRetryAfter(error.retryAfterSeconds);
|
||||
return {
|
||||
kind: "retry",
|
||||
message:
|
||||
stage === "send"
|
||||
? `Исчерпан лимит приглашений компании на неделю. ${wait ? `Повторить можно ${wait}.` : "Повторите позже."}`
|
||||
: `Слишком много изменений зарплатных вилок. ${wait ? `Повторить можно ${wait}.` : "Повторите позже."}`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: "blocked",
|
||||
message: "Сервер отклонил запрос. Обновите страницу и проверьте состояние приглашения.",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { setupServer } from "msw/node";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import type {
|
||||
InvitationTerms,
|
||||
OrganizationInvitation,
|
||||
OrganizationInvitationCreate,
|
||||
OrganizationInvitationUpdate,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { toInvitationTerms } from "./draft";
|
||||
import { completeDraft } from "./draft.fixtures";
|
||||
import { describeSendFailure } from "./failure";
|
||||
import {
|
||||
initialSendProgress,
|
||||
runSendCommand,
|
||||
type SendOutcome,
|
||||
type SendRequest,
|
||||
} from "./send-command";
|
||||
|
||||
const organizationId = "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01";
|
||||
const invitationId = "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f";
|
||||
const candidateHandle = `cv1_${"A".repeat(43)}`;
|
||||
const base = `http://localhost/api/v1/organizations/${organizationId}/invitations`;
|
||||
const deadline = "2026-10-16T10:00:00Z";
|
||||
|
||||
const server = setupServer();
|
||||
beforeAll(() => server.listen());
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
server.resetHandlers();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
function stubRelativeFetch(): void {
|
||||
const realFetch = globalThis.fetch;
|
||||
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
|
||||
realFetch(new URL(input, "http://localhost"), init),
|
||||
);
|
||||
}
|
||||
|
||||
function invitation(
|
||||
terms: InvitationTerms,
|
||||
overrides: Partial<OrganizationInvitation> = {},
|
||||
): OrganizationInvitation {
|
||||
return {
|
||||
id: invitationId,
|
||||
organization_id: organizationId,
|
||||
candidate_handle: candidateHandle,
|
||||
need: null,
|
||||
state: "draft",
|
||||
expiry_reason: null,
|
||||
version: 1,
|
||||
terms_version: 1,
|
||||
terms,
|
||||
response_period_days: 7,
|
||||
response_deadline_at: null,
|
||||
salary_raise_used: false,
|
||||
salary_fit: "not_available",
|
||||
contact_access: { status: "not_granted", fields: [] },
|
||||
created_at: "2026-10-09T10:00:00Z",
|
||||
updated_at: "2026-10-09T10:00:00Z",
|
||||
delivered_at: null,
|
||||
viewed_at: null,
|
||||
responded_at: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
type Recorded = {
|
||||
method: string;
|
||||
path: string;
|
||||
key: string | null;
|
||||
csrf: string | null;
|
||||
body: unknown;
|
||||
};
|
||||
|
||||
/**
|
||||
* A small fake of the invitation endpoints with the replay rules of the
|
||||
* contract: a known key replays the stored answer, and `lose` drops the
|
||||
* response of the next matching request after the server applied it.
|
||||
*/
|
||||
function fakeBackend(options: { lose?: "create" | "send"; sendStatus?: number } = {}) {
|
||||
const requests: Recorded[] = [];
|
||||
let stored: OrganizationInvitation | null = null;
|
||||
let deliveries = 0;
|
||||
let lose = options.lose;
|
||||
const createReplies = new Map<string, OrganizationInvitation>();
|
||||
const sendReplies = new Map<string, OrganizationInvitation>();
|
||||
|
||||
async function record(request: Request): Promise<Recorded> {
|
||||
const entry: Recorded = {
|
||||
method: request.method,
|
||||
path: new URL(request.url).pathname,
|
||||
key: request.headers.get("Idempotency-Key"),
|
||||
csrf: request.headers.get("X-CSRF-Token"),
|
||||
body: request.method === "GET" ? null : await request.json(),
|
||||
};
|
||||
requests.push(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
server.use(
|
||||
http.post(base, async ({ request }) => {
|
||||
const entry = await record(request);
|
||||
const key = entry.key ?? "";
|
||||
let reply = createReplies.get(key);
|
||||
if (!reply) {
|
||||
const body = entry.body as OrganizationInvitationCreate;
|
||||
reply = invitation(body.terms, { response_period_days: body.response_period_days ?? 7 });
|
||||
stored = reply;
|
||||
createReplies.set(key, reply);
|
||||
}
|
||||
if (lose === "create") {
|
||||
lose = undefined;
|
||||
return HttpResponse.error();
|
||||
}
|
||||
return HttpResponse.json(reply, { status: 201 });
|
||||
}),
|
||||
http.patch(`${base}/${invitationId}`, async ({ request }) => {
|
||||
const entry = await record(request);
|
||||
const body = entry.body as OrganizationInvitationUpdate;
|
||||
if (!stored || body.expected_version !== stored.version) {
|
||||
return HttpResponse.json(
|
||||
{ type: "about:blank", title: "Version conflict", status: 412, code: "version_conflict" },
|
||||
{ status: 412, headers: { "Content-Type": "application/problem+json" } },
|
||||
);
|
||||
}
|
||||
stored = invitation(body.terms ?? stored.terms, {
|
||||
version: stored.version + 1,
|
||||
terms_version: stored.terms_version + 1,
|
||||
});
|
||||
return HttpResponse.json(stored);
|
||||
}),
|
||||
http.get(`${base}/${invitationId}`, async ({ request }) => {
|
||||
await record(request);
|
||||
return HttpResponse.json(stored);
|
||||
}),
|
||||
http.post(`${base}/${invitationId}/send`, async ({ request }) => {
|
||||
const entry = await record(request);
|
||||
if (options.sendStatus) {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
type: "about:blank",
|
||||
title: "Rejected",
|
||||
status: options.sendStatus,
|
||||
code: "version_conflict",
|
||||
},
|
||||
{ status: options.sendStatus, headers: { "Content-Type": "application/problem+json" } },
|
||||
);
|
||||
}
|
||||
const key = entry.key ?? "";
|
||||
let reply = sendReplies.get(key);
|
||||
if (!reply && stored) {
|
||||
deliveries += 1;
|
||||
stored = {
|
||||
...stored,
|
||||
state: "delivered",
|
||||
version: stored.version + 1,
|
||||
delivered_at: "2026-10-09T10:00:00Z",
|
||||
response_deadline_at: deadline,
|
||||
};
|
||||
reply = stored;
|
||||
sendReplies.set(key, reply);
|
||||
}
|
||||
if (lose === "send") {
|
||||
lose = undefined;
|
||||
return HttpResponse.error();
|
||||
}
|
||||
return HttpResponse.json(reply);
|
||||
}),
|
||||
);
|
||||
return { requests, deliveries: () => deliveries };
|
||||
}
|
||||
|
||||
const terms = toInvitationTerms(completeDraft());
|
||||
|
||||
function request(overrides: Partial<SendRequest> = {}): SendRequest {
|
||||
return {
|
||||
organizationId,
|
||||
candidateHandle,
|
||||
need: null,
|
||||
terms,
|
||||
responsePeriodDays: 7,
|
||||
csrfToken: "csrf-token",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function keys(): () => string {
|
||||
let next = 0;
|
||||
return () => `key-${++next}`;
|
||||
}
|
||||
|
||||
describe("send invitation command", () => {
|
||||
it("creates the draft and sends it with separate keys and the CSRF token", async () => {
|
||||
stubRelativeFetch();
|
||||
const backend = fakeBackend();
|
||||
const onDraft = vi.fn();
|
||||
|
||||
const outcome = await runSendCommand(request(), initialSendProgress, {
|
||||
newKey: keys(),
|
||||
onDraft,
|
||||
});
|
||||
|
||||
expect(outcome.kind).toBe("sent");
|
||||
if (outcome.kind !== "sent") return;
|
||||
expect(outcome.invitation.state).toBe("delivered");
|
||||
expect(outcome.invitation.response_deadline_at).toBe(deadline);
|
||||
expect(outcome.progress).toMatchObject({ createKey: null, sendKey: null });
|
||||
expect(onDraft).toHaveBeenCalledOnce();
|
||||
expect(backend.requests.map((item) => [item.method, item.key, item.csrf])).toEqual([
|
||||
["POST", "key-1", "csrf-token"],
|
||||
["POST", "key-2", "csrf-token"],
|
||||
]);
|
||||
expect(backend.requests[0]?.body).toEqual({
|
||||
candidate_handle: candidateHandle,
|
||||
need: null,
|
||||
response_period_days: 7,
|
||||
terms,
|
||||
});
|
||||
expect(backend.requests[1]?.body).toEqual({ expected_version: 1 });
|
||||
});
|
||||
|
||||
it("repeats a send whose response was lost with the same key and delivers once", async () => {
|
||||
stubRelativeFetch();
|
||||
const backend = fakeBackend({ lose: "send" });
|
||||
const newKey = keys();
|
||||
|
||||
const first = await runSendCommand(request(), initialSendProgress, { newKey });
|
||||
expect(first).toMatchObject({ kind: "failed", stage: "send" });
|
||||
if (first.kind !== "failed") return;
|
||||
expect(describeSendFailure(first.stage, first.error).kind).toBe("retry");
|
||||
|
||||
const second = await runSendCommand(request(), first.progress, { newKey });
|
||||
|
||||
expect(second.kind).toBe("sent");
|
||||
const sends = backend.requests.filter((item) => item.path.endsWith("/send"));
|
||||
expect(sends.map((item) => item.key)).toEqual(["key-2", "key-2"]);
|
||||
expect(backend.requests.filter((item) => item.path.endsWith("/invitations"))).toHaveLength(1);
|
||||
expect(backend.deliveries()).toBe(1);
|
||||
});
|
||||
|
||||
it("repeats a create whose response was lost with the same key", async () => {
|
||||
stubRelativeFetch();
|
||||
const backend = fakeBackend({ lose: "create" });
|
||||
const newKey = keys();
|
||||
|
||||
const first = await runSendCommand(request(), initialSendProgress, { newKey });
|
||||
expect(first).toMatchObject({ kind: "failed", stage: "create" });
|
||||
const second = await runSendCommand(
|
||||
request(),
|
||||
(first as Extract<SendOutcome, { kind: "failed" }>).progress,
|
||||
{ newKey },
|
||||
);
|
||||
|
||||
expect(second.kind).toBe("sent");
|
||||
const creates = backend.requests.filter((item) => item.path.endsWith("/invitations"));
|
||||
expect(creates.map((item) => item.key)).toEqual(["key-1", "key-1"]);
|
||||
});
|
||||
|
||||
it("binds server field errors of a rejected draft to the form and sends nothing", async () => {
|
||||
stubRelativeFetch();
|
||||
const sent: string[] = [];
|
||||
server.use(
|
||||
http.post(base, () =>
|
||||
HttpResponse.json(
|
||||
{
|
||||
type: "about:blank",
|
||||
title: "Validation failed",
|
||||
status: 400,
|
||||
code: "validation_failed",
|
||||
errors: [
|
||||
{
|
||||
in: "body",
|
||||
pointer: "/terms/communication_method",
|
||||
code: "required",
|
||||
message: "x",
|
||||
},
|
||||
{ in: "body", pointer: "/terms/salary/salary_to", code: "invalid", message: "x" },
|
||||
],
|
||||
},
|
||||
{ status: 400, headers: { "Content-Type": "application/problem+json" } },
|
||||
),
|
||||
),
|
||||
http.post(`${base}/${invitationId}/send`, () => {
|
||||
sent.push("send");
|
||||
return HttpResponse.json({}, { status: 500 });
|
||||
}),
|
||||
);
|
||||
|
||||
const outcome = await runSendCommand(request(), initialSendProgress, { newKey: keys() });
|
||||
|
||||
expect(outcome).toMatchObject({ kind: "failed", stage: "create" });
|
||||
if (outcome.kind !== "failed") return;
|
||||
const failure = describeSendFailure(outcome.stage, outcome.error);
|
||||
expect(failure.kind).toBe("fields");
|
||||
expect(failure.kind === "fields" ? failure.issues.map((issue) => issue.field) : []).toEqual([
|
||||
"channel",
|
||||
"salaryTo",
|
||||
]);
|
||||
expect(outcome.progress.draft).toBeNull();
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it("updates a saved draft whose terms changed before sending it under a new key", async () => {
|
||||
stubRelativeFetch();
|
||||
const recorded: { method: string; body: unknown }[] = [];
|
||||
const newKey = keys();
|
||||
// A draft that was saved but not sent, for example reopened from the address.
|
||||
const saved = invitation(terms);
|
||||
const changed = { ...terms, role_title: "Senior Go-разработчик" };
|
||||
server.use(
|
||||
http.patch(`${base}/${invitationId}`, async ({ request: patch }) => {
|
||||
const body = (await patch.json()) as OrganizationInvitationUpdate;
|
||||
recorded.push({ method: "PATCH", body });
|
||||
return HttpResponse.json(invitation(changed, { version: 2, terms_version: 2 }));
|
||||
}),
|
||||
http.post(`${base}/${invitationId}/send`, async ({ request: send }) => {
|
||||
recorded.push({
|
||||
method: `POST ${send.headers.get("Idempotency-Key")}`,
|
||||
body: await send.json(),
|
||||
});
|
||||
return HttpResponse.json(
|
||||
invitation(changed, {
|
||||
state: "delivered",
|
||||
version: 3,
|
||||
terms_version: 2,
|
||||
delivered_at: "2026-10-09T10:00:00Z",
|
||||
response_deadline_at: deadline,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const outcome = await runSendCommand(
|
||||
request({ terms: changed }),
|
||||
{ ...initialSendProgress, draft: saved },
|
||||
{ newKey },
|
||||
);
|
||||
|
||||
expect(outcome.kind).toBe("sent");
|
||||
expect(recorded.map((item) => [item.method, item.body])).toEqual([
|
||||
["PATCH", { expected_version: 1, need: null, response_period_days: 7, terms: changed }],
|
||||
["POST key-1", { expected_version: 2 }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("reloads the draft after a version conflict and keeps the form's terms for the retry", async () => {
|
||||
stubRelativeFetch();
|
||||
const backend = fakeBackend({ sendStatus: 412 });
|
||||
|
||||
const outcome = await runSendCommand(request(), initialSendProgress, { newKey: keys() });
|
||||
|
||||
expect(outcome).toMatchObject({ kind: "failed", stage: "send" });
|
||||
if (outcome.kind !== "failed") return;
|
||||
expect(backend.requests.map((item) => item.method)).toEqual(["POST", "POST", "GET"]);
|
||||
expect(outcome.progress.draft?.id).toBe(invitationId);
|
||||
expect(describeSendFailure("send", outcome.error).message).toContain("другом окне");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import type {
|
||||
InvitationNeedReference,
|
||||
InvitationResponsePeriod,
|
||||
InvitationTerms,
|
||||
OrganizationInvitation,
|
||||
OrganizationInvitationCreate,
|
||||
} from "../../../shared/api/schemas";
|
||||
import {
|
||||
createInvitationDraft,
|
||||
readOrganizationInvitation,
|
||||
sendInvitationDraft,
|
||||
updateInvitationDraft,
|
||||
} from "../../../entities/invitation";
|
||||
|
||||
// Sending an invitation is three contract operations: create the draft
|
||||
// (Idempotency-Key), bring its terms up to date when the form changed after
|
||||
// the draft was created (expected_version), and send it (Idempotency-Key).
|
||||
// The progress object is the client side of that command: it remembers the
|
||||
// draft and the key of each keyed step, so a repeated click, a retry after a
|
||||
// lost response, or a retry after a server error replays the same key and
|
||||
// never creates a second draft or a second delivery. A key is bound to what
|
||||
// it protects (the create body, or the draft id and version) and changes only
|
||||
// when that changes, which is when the server would answer 422 for the old key.
|
||||
|
||||
/** An Idempotency-Key and the request it was issued for. */
|
||||
export interface KeyBinding {
|
||||
readonly fingerprint: string;
|
||||
readonly key: string;
|
||||
}
|
||||
|
||||
export interface SendProgress {
|
||||
readonly createKey: KeyBinding | null;
|
||||
/** The draft as the server last returned it, or null before it exists. */
|
||||
readonly draft: OrganizationInvitation | null;
|
||||
readonly sendKey: KeyBinding | null;
|
||||
}
|
||||
|
||||
export const initialSendProgress: SendProgress = { createKey: null, draft: null, sendKey: null };
|
||||
|
||||
export interface SendRequest {
|
||||
readonly organizationId: string;
|
||||
readonly candidateHandle: string;
|
||||
readonly need: InvitationNeedReference | null;
|
||||
readonly terms: InvitationTerms;
|
||||
readonly responsePeriodDays: InvitationResponsePeriod;
|
||||
readonly csrfToken: string;
|
||||
}
|
||||
|
||||
export type SendStage = "create" | "update" | "send";
|
||||
|
||||
export type SendOutcome =
|
||||
| {
|
||||
readonly kind: "sent";
|
||||
/** The invitation after the send; its state is no longer `draft`. */
|
||||
readonly invitation: OrganizationInvitation;
|
||||
readonly progress: SendProgress;
|
||||
}
|
||||
| {
|
||||
readonly kind: "failed";
|
||||
readonly stage: SendStage;
|
||||
readonly error: unknown;
|
||||
readonly progress: SendProgress;
|
||||
};
|
||||
|
||||
export interface SendDependencies {
|
||||
readonly newKey: () => string;
|
||||
/** Called once the draft exists on the server, before it is sent. */
|
||||
readonly onDraft?: ((draft: OrganizationInvitation) => void) | undefined;
|
||||
}
|
||||
|
||||
export function newIdempotencyKey(): string {
|
||||
if (typeof crypto === "undefined" || typeof crypto.randomUUID !== "function") {
|
||||
throw new Error("Secure random key generation is unavailable.");
|
||||
}
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
|
||||
/** JSON with object keys in a fixed order, so equal values give equal text. */
|
||||
export function stableJson(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
||||
if (value !== null && typeof value === "object") {
|
||||
const entries = Object.entries(value as Record<string, unknown>)
|
||||
.filter(([, item]) => item !== undefined)
|
||||
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
|
||||
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`).join(",")}}`;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function bind(previous: KeyBinding | null, fingerprint: string, newKey: () => string): KeyBinding {
|
||||
return previous?.fingerprint === fingerprint ? previous : { fingerprint, key: newKey() };
|
||||
}
|
||||
|
||||
function draftMatches(draft: OrganizationInvitation, request: SendRequest): boolean {
|
||||
return (
|
||||
stableJson(draft.terms) === stableJson(request.terms) &&
|
||||
draft.response_period_days === request.responsePeriodDays &&
|
||||
stableJson(draft.need) === stableJson(request.need)
|
||||
);
|
||||
}
|
||||
|
||||
function versionConflict(error: unknown): boolean {
|
||||
return error instanceof ApiRequestError && error.status === 412;
|
||||
}
|
||||
|
||||
/** Reads the current draft after a version conflict; keeps the old one when the read fails. */
|
||||
async function reloadDraft(
|
||||
request: SendRequest,
|
||||
progress: SendProgress,
|
||||
draft: OrganizationInvitation,
|
||||
): Promise<SendProgress> {
|
||||
try {
|
||||
const latest = await readOrganizationInvitation(request.organizationId, draft.id);
|
||||
return { ...progress, draft: latest };
|
||||
} catch {
|
||||
return progress;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the send command from the given progress. It never throws for a
|
||||
* request failure: the outcome carries the stage, the error, and the progress
|
||||
* to pass to the next attempt.
|
||||
*/
|
||||
export async function runSendCommand(
|
||||
request: SendRequest,
|
||||
initial: SendProgress,
|
||||
dependencies: SendDependencies,
|
||||
): Promise<SendOutcome> {
|
||||
let progress = initial;
|
||||
|
||||
if (progress.draft === null) {
|
||||
const body: OrganizationInvitationCreate = {
|
||||
candidate_handle: request.candidateHandle,
|
||||
need: request.need,
|
||||
response_period_days: request.responsePeriodDays,
|
||||
terms: request.terms,
|
||||
};
|
||||
const createKey = bind(progress.createKey, stableJson(body), dependencies.newKey);
|
||||
progress = { ...progress, createKey };
|
||||
try {
|
||||
const draft = await createInvitationDraft({
|
||||
organizationId: request.organizationId,
|
||||
csrfToken: request.csrfToken,
|
||||
body,
|
||||
idempotencyKey: createKey.key,
|
||||
});
|
||||
progress = { ...progress, draft };
|
||||
dependencies.onDraft?.(draft);
|
||||
} catch (error: unknown) {
|
||||
return { kind: "failed", stage: "create", error, progress };
|
||||
}
|
||||
}
|
||||
|
||||
let draft = progress.draft;
|
||||
if (draft === null) throw new Error("The draft must exist after its creation.");
|
||||
if (draft.state !== "draft") return { kind: "sent", invitation: draft, progress };
|
||||
|
||||
if (!draftMatches(draft, request)) {
|
||||
try {
|
||||
draft = await updateInvitationDraft({
|
||||
organizationId: request.organizationId,
|
||||
csrfToken: request.csrfToken,
|
||||
invitationId: draft.id,
|
||||
body: {
|
||||
expected_version: draft.version,
|
||||
need: request.need,
|
||||
response_period_days: request.responsePeriodDays,
|
||||
terms: request.terms,
|
||||
},
|
||||
});
|
||||
progress = { ...progress, draft };
|
||||
} catch (error: unknown) {
|
||||
if (versionConflict(error)) progress = await reloadDraft(request, progress, draft);
|
||||
return { kind: "failed", stage: "update", error, progress };
|
||||
}
|
||||
if (draft.state !== "draft") return { kind: "sent", invitation: draft, progress };
|
||||
}
|
||||
|
||||
const sendKey = bind(progress.sendKey, `${draft.id}:${draft.version}`, dependencies.newKey);
|
||||
progress = { ...progress, sendKey };
|
||||
try {
|
||||
const sent = await sendInvitationDraft({
|
||||
organizationId: request.organizationId,
|
||||
csrfToken: request.csrfToken,
|
||||
invitationId: draft.id,
|
||||
expectedVersion: draft.version,
|
||||
idempotencyKey: sendKey.key,
|
||||
});
|
||||
// The command is complete: the next command starts with fresh keys.
|
||||
return {
|
||||
kind: "sent",
|
||||
invitation: sent,
|
||||
progress: { createKey: null, draft: sent, sendKey: null },
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
if (versionConflict(error)) progress = await reloadDraft(request, progress, draft);
|
||||
return { kind: "failed", stage: "send", error, progress };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { InvitationTerms as InvitationTermsSchema } from "../../../shared/api/schemas";
|
||||
import {
|
||||
emptyInvitationDraft,
|
||||
invitationDraftFromTerms,
|
||||
toInvitationTerms,
|
||||
type InvitationDraft,
|
||||
} from "./draft";
|
||||
import { completeDraft } from "./draft.fixtures";
|
||||
import { fieldOfPointer, issuesOfProblem, validateInvitationDraft } from "./validate";
|
||||
|
||||
const fieldsOf = (draft: InvitationDraft) => validateInvitationDraft(draft).map((i) => i.field);
|
||||
|
||||
describe("invitation draft validation", () => {
|
||||
it("accepts a complete draft and builds terms the contract accepts", () => {
|
||||
const draft = completeDraft();
|
||||
|
||||
expect(validateInvitationDraft(draft)).toEqual([]);
|
||||
const terms = toInvitationTerms(draft);
|
||||
expect(InvitationTermsSchema.safeParse(terms).success).toBe(true);
|
||||
expect(terms.tasks).toEqual(["Развивать сервис выплат", "Перевести отчеты на события"]);
|
||||
expect(terms.tech_stack).toEqual(["Go", "PostgreSQL", "Kafka"]);
|
||||
expect(terms.salary).toEqual({
|
||||
salary_from: 100000,
|
||||
salary_to: 140000,
|
||||
currency: "RUB",
|
||||
period: "month",
|
||||
tax_basis: "net",
|
||||
});
|
||||
expect(terms.package.training).toEqual({ status: "not_provided" });
|
||||
expect(terms.communication_method).toEqual({
|
||||
channel: "video_call",
|
||||
details: "Созвон с тимлидом в течение трех рабочих дней",
|
||||
});
|
||||
});
|
||||
|
||||
it("blocks a blank draft on every required term in the order of the form", () => {
|
||||
expect(fieldsOf(emptyInvitationDraft())).toEqual([
|
||||
"roleTitle",
|
||||
"specialization",
|
||||
"grade",
|
||||
"offerType",
|
||||
"tasks",
|
||||
"team",
|
||||
"techStack",
|
||||
"workFormats",
|
||||
"channel",
|
||||
"salaryFrom",
|
||||
"salaryTo",
|
||||
"taxBasis",
|
||||
"package.bonus",
|
||||
"package.equipment",
|
||||
"package.training",
|
||||
"package.health_insurance",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ salaryTo: "" }, ["salaryTo"]],
|
||||
[{ salaryFrom: "" }, ["salaryFrom"]],
|
||||
[{ taxBasis: "" as const }, ["taxBasis"]],
|
||||
[{ salaryFrom: "100500" }, ["salaryTo"]],
|
||||
[{ salaryFrom: "140000", salaryTo: "100000" }, ["salaryTo"]],
|
||||
[{ salaryTo: "105000" }, ["salaryTo"]],
|
||||
[{ salaryFrom: "79000", salaryTo: "121000" }, ["salaryTo"]],
|
||||
])("does not allow sending an incomplete or invalid salary range %j", (overrides, fields) => {
|
||||
expect(fieldsOf(completeDraft(overrides))).toEqual(fields);
|
||||
});
|
||||
|
||||
it("requires the communication method, a place for office formats, and each package choice", () => {
|
||||
expect(fieldsOf(completeDraft({ channel: "" }))).toEqual(["channel"]);
|
||||
expect(fieldsOf(completeDraft({ location: "" }))).toEqual(["location"]);
|
||||
expect(fieldsOf(completeDraft({ location: "", workFormats: ["remote"] }))).toEqual([]);
|
||||
const draft = completeDraft();
|
||||
expect(
|
||||
fieldsOf({
|
||||
...draft,
|
||||
packageItems: {
|
||||
...draft.packageItems,
|
||||
training: { status: "", description: "" },
|
||||
bonus: { status: "provided", description: " " },
|
||||
},
|
||||
}),
|
||||
).toEqual(["package.bonus", "package.training"]);
|
||||
});
|
||||
|
||||
it("finds a technology repeated in another letter case", () => {
|
||||
const issues = validateInvitationDraft(completeDraft({ techStack: "Go, PostgreSQL, GO" }));
|
||||
expect(issues).toEqual([{ field: "techStack", message: "Технология «GO» указана дважды." }]);
|
||||
});
|
||||
|
||||
it("restores the same terms from a stored invitation", () => {
|
||||
const terms = toInvitationTerms(completeDraft());
|
||||
expect(toInvitationTerms(invitationDraftFromTerms(terms, 14))).toEqual(terms);
|
||||
expect(invitationDraftFromTerms(terms, 14).responsePeriodDays).toBe(14);
|
||||
});
|
||||
});
|
||||
|
||||
describe("server field errors", () => {
|
||||
it.each([
|
||||
["/terms/salary/salary_to", "salaryTo"],
|
||||
["/terms/salary/tax_basis", "taxBasis"],
|
||||
["/terms/communication_method", "channel"],
|
||||
["/terms/communication_method/channel", "channel"],
|
||||
["/terms/communication_method/details", "channelDetails"],
|
||||
["/terms/tech_stack/1", "techStack"],
|
||||
["/terms/tasks/0", "tasks"],
|
||||
["/terms/location", "location"],
|
||||
["/terms/package/training", "package.training"],
|
||||
["/terms/package/bonus/description", "package.bonus"],
|
||||
["/response_period_days", "responsePeriodDays"],
|
||||
["/candidate_handle", null],
|
||||
["/expected_version", null],
|
||||
["", null],
|
||||
])("maps the pointer %s to %s", (pointer, field) => {
|
||||
expect(fieldOfPointer(pointer)).toBe(field);
|
||||
});
|
||||
|
||||
it("binds each body error to its field once, in the order of the form", () => {
|
||||
const issues = issuesOfProblem([
|
||||
{ in: "body", pointer: "/terms/salary/salary_to", code: "invalid", message: "Width." },
|
||||
{ in: "body", pointer: "/terms/communication_method", code: "required", message: "Missing." },
|
||||
{ in: "body", pointer: "/terms/package/training", code: "required", message: "Missing." },
|
||||
{ in: "body", pointer: "/terms/salary/salary_to", code: "invalid", message: "Again." },
|
||||
{ in: "header", pointer: "/Idempotency-Key", code: "invalid", message: "Key." },
|
||||
]);
|
||||
|
||||
expect(issues.map((issue) => issue.field)).toEqual(["channel", "salaryTo", "package.training"]);
|
||||
expect(issues[2]?.message).toContain("незаполненным");
|
||||
expect(JSON.stringify(issues)).not.toMatch(/Width|Missing|Again/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,267 @@
|
||||
import type { ProblemFieldError } from "../../../shared/api/schemas";
|
||||
import { OrganizationInvitationCreate } from "../../../shared/api/schemas";
|
||||
import {
|
||||
packageItemKeys,
|
||||
packageItemLabels,
|
||||
salaryRangeIssue,
|
||||
type InvitationPackageKey,
|
||||
} from "../../../entities/invitation";
|
||||
import { taskLines, techStackItems, toInvitationTerms, type InvitationDraft } from "./draft";
|
||||
|
||||
// Client validation mirrors the contract for immediate feedback: the per-field
|
||||
// limits and the cross-field rules of the terms (salary range, place of work,
|
||||
// repeated technology). The server stays the source of truth; its RFC 9457
|
||||
// field errors come back through fieldOfPointer and land on the same fields.
|
||||
|
||||
export type InvitationField =
|
||||
| "roleTitle"
|
||||
| "specialization"
|
||||
| "grade"
|
||||
| "offerType"
|
||||
| "tasks"
|
||||
| "team"
|
||||
| "techStack"
|
||||
| "workFormats"
|
||||
| "location"
|
||||
| "channel"
|
||||
| "channelDetails"
|
||||
| "salaryFrom"
|
||||
| "salaryTo"
|
||||
| "taxBasis"
|
||||
| `package.${InvitationPackageKey}`
|
||||
| "responsePeriodDays";
|
||||
|
||||
/** Field order of the form, used to order the issue summary and to pick the first field. */
|
||||
export const invitationFieldOrder: readonly InvitationField[] = [
|
||||
"roleTitle",
|
||||
"specialization",
|
||||
"grade",
|
||||
"offerType",
|
||||
"tasks",
|
||||
"team",
|
||||
"techStack",
|
||||
"workFormats",
|
||||
"location",
|
||||
"channel",
|
||||
"channelDetails",
|
||||
"salaryFrom",
|
||||
"salaryTo",
|
||||
"taxBasis",
|
||||
...packageItemKeys.map((key) => `package.${key}` as const),
|
||||
"responsePeriodDays",
|
||||
];
|
||||
|
||||
export interface InvitationIssue {
|
||||
readonly field: InvitationField;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
const singleLine = /^\S(?:.*\S)?$/;
|
||||
|
||||
const salaryIssueMessages = {
|
||||
bound: "Суммы должны быть целыми, положительными и кратными 1 000 рублей.",
|
||||
order: "Верхняя граница вилки должна быть больше нижней.",
|
||||
narrow: "Вилка слишком узкая: ширина должна быть не меньше 10% от середины.",
|
||||
wide: "Вилка слишком широкая: ширина должна быть не больше 40% от середины.",
|
||||
} as const;
|
||||
|
||||
function lineIssue(value: string, max: number, empty: string, field: InvitationField) {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed === "") return { field, message: empty };
|
||||
if (trimmed.length > max) return { field, message: `Не больше ${max} символов.` };
|
||||
if (!singleLine.test(trimmed)) return { field, message: "Текст должен быть в одну строку." };
|
||||
return null;
|
||||
}
|
||||
|
||||
function checkSalary(draft: InvitationDraft): InvitationIssue[] {
|
||||
const issues: InvitationIssue[] = [];
|
||||
const from = draft.salaryFrom.trim();
|
||||
const to = draft.salaryTo.trim();
|
||||
if (from === "") issues.push({ field: "salaryFrom", message: "Укажите нижнюю границу вилки." });
|
||||
if (to === "") issues.push({ field: "salaryTo", message: "Укажите верхнюю границу вилки." });
|
||||
if (!draft.taxBasis) {
|
||||
issues.push({ field: "taxBasis", message: "Выберите базу суммы: до или после налога." });
|
||||
}
|
||||
if (from === "" || to === "") return issues;
|
||||
const issue = salaryRangeIssue(Number(from), Number(to));
|
||||
if (issue) issues.push({ field: "salaryTo", message: salaryIssueMessages[issue] });
|
||||
return issues;
|
||||
}
|
||||
|
||||
function checkTechStack(value: string): InvitationIssue | null {
|
||||
const items = techStackItems(value);
|
||||
if (items.length === 0) {
|
||||
return { field: "techStack", message: "Укажите хотя бы одну технологию." };
|
||||
}
|
||||
if (items.length > 30) return { field: "techStack", message: "Не больше 30 технологий." };
|
||||
if (items.some((item) => item.length > 100)) {
|
||||
return { field: "techStack", message: "Название технологии не длиннее 100 символов." };
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
for (const item of items) {
|
||||
const folded = item.toLocaleLowerCase("ru-RU");
|
||||
if (seen.has(folded)) {
|
||||
return { field: "techStack", message: `Технология «${item}» указана дважды.` };
|
||||
}
|
||||
seen.add(folded);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function checkTasks(value: string): InvitationIssue | null {
|
||||
const lines = taskLines(value);
|
||||
if (lines.length === 0) return { field: "tasks", message: "Опишите хотя бы одну задачу." };
|
||||
if (lines.length > 20) return { field: "tasks", message: "Не больше 20 задач." };
|
||||
if (lines.some((line) => line.length > 300)) {
|
||||
return { field: "tasks", message: "Каждая задача не длиннее 300 символов." };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Every issue of a draft in the order of the form; an empty list means it can be sent. */
|
||||
export function validateInvitationDraft(draft: InvitationDraft): InvitationIssue[] {
|
||||
const issues: (InvitationIssue | null)[] = [
|
||||
lineIssue(draft.roleTitle, 200, "Укажите название роли.", "roleTitle"),
|
||||
draft.specialization ? null : { field: "specialization", message: "Выберите специализацию." },
|
||||
draft.grade ? null : { field: "grade", message: "Выберите грейд." },
|
||||
draft.offerType ? null : { field: "offerType", message: "Выберите тип предложения." },
|
||||
checkTasks(draft.tasks),
|
||||
draft.team.trim() === ""
|
||||
? { field: "team", message: "Опишите команду." }
|
||||
: draft.team.trim().length > 1000
|
||||
? { field: "team", message: "Не больше 1000 символов." }
|
||||
: null,
|
||||
checkTechStack(draft.techStack),
|
||||
draft.workFormats.length === 0
|
||||
? { field: "workFormats", message: "Выберите хотя бы один формат работы." }
|
||||
: null,
|
||||
];
|
||||
|
||||
const officeFormat = draft.workFormats.includes("office") || draft.workFormats.includes("hybrid");
|
||||
if (draft.location.trim() !== "" || officeFormat) {
|
||||
issues.push(
|
||||
lineIssue(draft.location, 100, "Для офиса или гибрида укажите место работы.", "location"),
|
||||
);
|
||||
}
|
||||
issues.push(
|
||||
draft.channel
|
||||
? null
|
||||
: { field: "channel", message: "Выберите способ связи после принятия приглашения." },
|
||||
);
|
||||
if (draft.channelDetails.trim() !== "") {
|
||||
issues.push(lineIssue(draft.channelDetails, 300, "", "channelDetails"));
|
||||
}
|
||||
issues.push(...checkSalary(draft));
|
||||
for (const key of packageItemKeys) {
|
||||
const item = draft.packageItems[key];
|
||||
const field = `package.${key}` as const;
|
||||
if (!item.status) {
|
||||
issues.push({
|
||||
field,
|
||||
message: `${packageItemLabels[key]}: выберите «Предусмотрено» или «Не предусмотрено».`,
|
||||
});
|
||||
} else if (item.status === "provided") {
|
||||
const issue = lineIssue(
|
||||
item.description,
|
||||
300,
|
||||
`${packageItemLabels[key]}: опишите условие.`,
|
||||
field,
|
||||
);
|
||||
issues.push(issue);
|
||||
}
|
||||
}
|
||||
|
||||
const found = issues.filter((issue): issue is InvitationIssue => issue !== null);
|
||||
if (found.length > 0) return found;
|
||||
|
||||
// Safety net: the generated request schema must accept the built terms.
|
||||
const parsed = OrganizationInvitationCreate.safeParse({
|
||||
candidate_handle: `cv1_${"A".repeat(43)}`,
|
||||
terms: toInvitationTerms(draft),
|
||||
});
|
||||
if (parsed.success) return [];
|
||||
return parsed.error.issues.map((issue) => ({
|
||||
field: fieldOfPath(issue.path) ?? "roleTitle",
|
||||
message: "Проверьте это значение.",
|
||||
}));
|
||||
}
|
||||
|
||||
const termsFields: Readonly<Record<string, InvitationField>> = {
|
||||
role_title: "roleTitle",
|
||||
specialization: "specialization",
|
||||
grade: "grade",
|
||||
offer_type: "offerType",
|
||||
tasks: "tasks",
|
||||
team: "team",
|
||||
tech_stack: "techStack",
|
||||
work_formats: "workFormats",
|
||||
location: "location",
|
||||
};
|
||||
|
||||
function fieldOfTermsPath(path: readonly string[]): InvitationField | null {
|
||||
const [head, next] = path;
|
||||
if (head === undefined) return null;
|
||||
const direct = termsFields[head];
|
||||
if (direct) return direct;
|
||||
if (head === "communication_method") {
|
||||
return next === "details" ? "channelDetails" : "channel";
|
||||
}
|
||||
if (head === "salary") {
|
||||
if (next === "salary_from") return "salaryFrom";
|
||||
if (next === "tax_basis") return "taxBasis";
|
||||
return "salaryTo";
|
||||
}
|
||||
if (head === "package") {
|
||||
const key = packageItemKeys.find((item) => item === next);
|
||||
return key ? `package.${key}` : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Maps a request body path, such as ["terms", "salary", "salary_to"], to its form field. */
|
||||
export function fieldOfPath(path: readonly PropertyKey[]): InvitationField | null {
|
||||
const parts = path.map(String);
|
||||
if (parts[0] === "terms") return fieldOfTermsPath(parts.slice(1));
|
||||
if (parts[0] === "response_period_days") return "responsePeriodDays";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Maps an RFC 6901 pointer of a problem, such as "/terms/tech_stack/1", to its form field. */
|
||||
export function fieldOfPointer(pointer: string): InvitationField | null {
|
||||
if (!pointer.startsWith("/")) return null;
|
||||
const path = pointer
|
||||
.slice(1)
|
||||
.split("/")
|
||||
.map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
||||
return fieldOfPath(path);
|
||||
}
|
||||
|
||||
const serverMessages: Partial<Record<InvitationField, string>> = {
|
||||
salaryTo:
|
||||
"Сервер не принял вилку: границы кратны 1 000 рублей, нижняя меньше верхней, ширина от 10% до 40%.",
|
||||
location: "Сервер требует место работы для офиса или гибрида.",
|
||||
techStack: "Сервер не принял список технологий: проверьте повторы и длину названий.",
|
||||
channel: "Сервер не принял способ связи: выберите канал.",
|
||||
};
|
||||
|
||||
/** Field issues of a server problem; pointers outside the terms are left to the caller. */
|
||||
export function issuesOfProblem(errors: readonly ProblemFieldError[]): InvitationIssue[] {
|
||||
const issues: InvitationIssue[] = [];
|
||||
for (const error of errors) {
|
||||
if (error.in !== "body") continue;
|
||||
const field = fieldOfPointer(error.pointer);
|
||||
if (!field || issues.some((issue) => issue.field === field)) continue;
|
||||
issues.push({
|
||||
field,
|
||||
message:
|
||||
serverMessages[field] ??
|
||||
(error.code === "required"
|
||||
? "Сервер считает это поле незаполненным. Заполните его."
|
||||
: "Сервер не принял это значение. Исправьте его."),
|
||||
});
|
||||
}
|
||||
return issues.sort(
|
||||
(left, right) =>
|
||||
invitationFieldOrder.indexOf(left.field) - invitationFieldOrder.indexOf(right.field),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.intro,
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.issue-summary {
|
||||
min-width: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-strong) solid var(--color-danger);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.issue-summary h2 {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-l);
|
||||
}
|
||||
|
||||
.issue-summary ul {
|
||||
margin: var(--space-3) 0 0;
|
||||
padding-left: var(--space-5);
|
||||
}
|
||||
|
||||
.group {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.group > legend {
|
||||
max-width: 100%;
|
||||
padding: 0 var(--space-2);
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
align-content: start;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field > label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field select,
|
||||
.field textarea {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
color: var(--color-text);
|
||||
background: var(--color-surface);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.field textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.field :is(input, select, textarea):focus-visible,
|
||||
.choice input:focus-visible {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.field [aria-invalid="true"] {
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.choices {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3) var(--space-5);
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-s);
|
||||
}
|
||||
|
||||
.choices > legend {
|
||||
padding: 0 var(--space-2);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.choice {
|
||||
display: inline-flex;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
min-height: 2.75rem;
|
||||
}
|
||||
|
||||
.field-error,
|
||||
.form-error {
|
||||
margin: 0;
|
||||
color: var(--color-danger);
|
||||
font-weight: var(--font-weight-bold);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.notice,
|
||||
.stale {
|
||||
margin: 0;
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.preview {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.choices > .field,
|
||||
.choices > .field-error {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.issue-summary:focus,
|
||||
.preview:focus,
|
||||
.notice:focus,
|
||||
.form-error:focus {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
@media (width < 42rem) {
|
||||
.group {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,711 @@
|
||||
import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from "react";
|
||||
import type {
|
||||
GradeCode,
|
||||
InvitationCommunicationChannel,
|
||||
InvitationNeedReference,
|
||||
InvitationOfferType,
|
||||
InvitationResponsePeriod,
|
||||
InvitationTerms,
|
||||
OrganizationInvitation,
|
||||
SalaryTaxBasis,
|
||||
SpecializationCode,
|
||||
WorkFormat,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { Button } from "../../../shared/ui";
|
||||
import {
|
||||
communicationChannelCodes,
|
||||
communicationChannelLabels,
|
||||
notProvidedLabel,
|
||||
offerTypeCodes,
|
||||
offerTypeLabels,
|
||||
packageItemKeys,
|
||||
packageItemLabels,
|
||||
responsePeriodLabel,
|
||||
responsePeriods,
|
||||
taxBasisLabels,
|
||||
type InvitationPackageKey,
|
||||
} from "../../../entities/invitation";
|
||||
import {
|
||||
gradeCodes,
|
||||
gradeLabels,
|
||||
specializationCodes,
|
||||
specializationLabels,
|
||||
workFormatCodes,
|
||||
workFormatLabels,
|
||||
} from "../../../entities/match";
|
||||
import { toInvitationTerms, type InvitationDraft, type PackageChoice } from "../model/draft";
|
||||
import { describeSendFailure, type SendFailure } from "../model/failure";
|
||||
import {
|
||||
newIdempotencyKey,
|
||||
runSendCommand,
|
||||
stableJson,
|
||||
type SendProgress,
|
||||
} from "../model/send-command";
|
||||
import {
|
||||
invitationFieldOrder,
|
||||
validateInvitationDraft,
|
||||
type InvitationField,
|
||||
type InvitationIssue,
|
||||
} from "../model/validate";
|
||||
import styles from "./invitation-form.module.css";
|
||||
|
||||
/** Terms of a preview, frozen at the moment the employer asked for it. */
|
||||
export interface InvitationPreviewSnapshot {
|
||||
readonly terms: InvitationTerms;
|
||||
readonly responsePeriodDays: InvitationResponsePeriod;
|
||||
}
|
||||
|
||||
export type InvitationFormProps = {
|
||||
organizationId: string;
|
||||
candidateHandle: string;
|
||||
need: InvitationNeedReference | null;
|
||||
csrfToken: string;
|
||||
initialDraft: InvitationDraft;
|
||||
/** Progress of an earlier attempt, for example a saved draft reopened from the address. */
|
||||
initialProgress: SendProgress;
|
||||
/** False once the session that rendered the form is no longer the current one. */
|
||||
isSessionCurrent: () => boolean;
|
||||
/** Renders the preview of the given terms; the form never sends anything for it. */
|
||||
renderPreview: (snapshot: InvitationPreviewSnapshot) => ReactNode;
|
||||
onDraftSaved: (draft: OrganizationInvitation) => void;
|
||||
onSent: (invitation: OrganizationInvitation) => void;
|
||||
onCsrfFailed: () => void;
|
||||
};
|
||||
|
||||
type Notice = { tone: "error" | "info"; text: string };
|
||||
type FocusTarget = "summary" | "preview" | "notice";
|
||||
|
||||
function describedBy(...ids: (string | false | undefined)[]): string | undefined {
|
||||
const present = ids.filter((id): id is string => typeof id === "string" && id.length > 0);
|
||||
return present.length > 0 ? present.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function FieldError({ id, message }: { id: string; message: string | undefined }) {
|
||||
return message ? (
|
||||
<p className={styles["field-error"]} id={id}>
|
||||
{message}
|
||||
</p>
|
||||
) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The terms of an invitation for one search entry, with a local preview and
|
||||
* the send command. The form validates like the contract before any request;
|
||||
* the server answer is still authoritative and its field errors are shown on
|
||||
* the same fields. A click that repeats an unfinished command reuses its
|
||||
* Idempotency-Key, and a click while a command runs does nothing.
|
||||
*/
|
||||
export function InvitationForm({
|
||||
organizationId,
|
||||
candidateHandle,
|
||||
need,
|
||||
csrfToken,
|
||||
initialDraft,
|
||||
initialProgress,
|
||||
isSessionCurrent,
|
||||
renderPreview,
|
||||
onDraftSaved,
|
||||
onSent,
|
||||
onCsrfFailed,
|
||||
}: InvitationFormProps) {
|
||||
const prefix = `invitation-${useId().replaceAll(":", "")}`;
|
||||
const [draft, setDraft] = useState<InvitationDraft>(initialDraft);
|
||||
const [issues, setIssues] = useState<readonly InvitationIssue[]>([]);
|
||||
const [summaryVisible, setSummaryVisible] = useState(false);
|
||||
const [notice, setNotice] = useState<Notice | null>(null);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [preview, setPreview] = useState<{
|
||||
snapshot: InvitationPreviewSnapshot;
|
||||
source: string;
|
||||
} | null>(null);
|
||||
const progress = useRef<SendProgress>(initialProgress);
|
||||
const inFlight = useRef(false);
|
||||
const mounted = useRef(false);
|
||||
const summaryRef = useRef<HTMLDivElement>(null);
|
||||
const previewRef = useRef<HTMLElement>(null);
|
||||
const noticeRef = useRef<HTMLParagraphElement>(null);
|
||||
// A new object per request, so asking for the same target twice moves focus twice.
|
||||
const [focusRequest, setFocusRequest] = useState<{ target: FocusTarget } | null>(null);
|
||||
const setFocusTarget = (target: FocusTarget) => setFocusRequest({ target });
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Focus moves after the target is rendered: to the issue list, the preview, or the notice.
|
||||
useEffect(() => {
|
||||
if (focusRequest?.target === "summary") summaryRef.current?.focus();
|
||||
if (focusRequest?.target === "preview") previewRef.current?.focus();
|
||||
if (focusRequest?.target === "notice") noticeRef.current?.focus();
|
||||
}, [focusRequest]);
|
||||
|
||||
const fieldId = (field: InvitationField) => `${prefix}-${field.replace(".", "-")}`;
|
||||
const errorId = (field: InvitationField) => `${fieldId(field)}-error`;
|
||||
const issueOf = (field: InvitationField) => issues.find((item) => item.field === field)?.message;
|
||||
const invalid = (field: InvitationField) => Boolean(issueOf(field));
|
||||
const previewStale = preview !== null && preview.source !== stableJson(draft);
|
||||
|
||||
function change(next: Partial<InvitationDraft>, fields: readonly InvitationField[]): void {
|
||||
setDraft((current) => ({ ...current, ...next }));
|
||||
if (fields.length > 0) {
|
||||
setIssues((current) => current.filter((item) => !fields.includes(item.field)));
|
||||
}
|
||||
}
|
||||
|
||||
function changePackage(
|
||||
key: InvitationPackageKey,
|
||||
next: Partial<InvitationDraft["packageItems"][InvitationPackageKey]>,
|
||||
) {
|
||||
change(
|
||||
{ packageItems: { ...draft.packageItems, [key]: { ...draft.packageItems[key], ...next } } },
|
||||
[`package.${key}`],
|
||||
);
|
||||
}
|
||||
|
||||
function toggleFormat(format: WorkFormat, checked: boolean): void {
|
||||
const formats = checked
|
||||
? workFormatCodes.filter((code) => code === format || draft.workFormats.includes(code))
|
||||
: draft.workFormats.filter((code) => code !== format);
|
||||
change({ workFormats: formats }, ["workFormats", "location"]);
|
||||
}
|
||||
|
||||
function showIssues(found: readonly InvitationIssue[]): void {
|
||||
const ordered = [...found].sort(
|
||||
(left, right) =>
|
||||
invitationFieldOrder.indexOf(left.field) - invitationFieldOrder.indexOf(right.field),
|
||||
);
|
||||
setIssues(ordered);
|
||||
setSummaryVisible(true);
|
||||
setFocusTarget("summary");
|
||||
}
|
||||
|
||||
function validated(): InvitationPreviewSnapshot | null {
|
||||
const found = validateInvitationDraft(draft);
|
||||
if (found.length > 0) {
|
||||
showIssues(found);
|
||||
return null;
|
||||
}
|
||||
setIssues([]);
|
||||
setSummaryVisible(false);
|
||||
return { terms: toInvitationTerms(draft), responsePeriodDays: draft.responsePeriodDays };
|
||||
}
|
||||
|
||||
function showPreview(): void {
|
||||
if (sending) return;
|
||||
setNotice(null);
|
||||
const snapshot = validated();
|
||||
if (!snapshot) return;
|
||||
setPreview({ snapshot, source: stableJson(draft) });
|
||||
setFocusTarget("preview");
|
||||
}
|
||||
|
||||
function applyFailure(failure: SendFailure): void {
|
||||
if (failure.kind === "fields") {
|
||||
setNotice({ tone: "error", text: failure.message });
|
||||
if (failure.issues.length > 0) showIssues(failure.issues);
|
||||
else setFocusTarget("notice");
|
||||
return;
|
||||
}
|
||||
if (failure.kind === "csrf") onCsrfFailed();
|
||||
setNotice({ tone: failure.kind === "retry" ? "info" : "error", text: failure.message });
|
||||
setFocusTarget("notice");
|
||||
}
|
||||
|
||||
async function send(): Promise<void> {
|
||||
// A click while the command runs neither starts a second request nor
|
||||
// issues a new key; the running command finishes for both clicks.
|
||||
if (inFlight.current) return;
|
||||
setNotice(null);
|
||||
const snapshot = validated();
|
||||
if (!snapshot) return;
|
||||
if (!isSessionCurrent()) {
|
||||
setNotice({
|
||||
tone: "error",
|
||||
text: "Вход изменился. Обновите страницу и проверьте, от чьего имени отправляется приглашение.",
|
||||
});
|
||||
setFocusTarget("notice");
|
||||
return;
|
||||
}
|
||||
inFlight.current = true;
|
||||
setSending(true);
|
||||
try {
|
||||
const outcome = await runSendCommand(
|
||||
{
|
||||
organizationId,
|
||||
candidateHandle,
|
||||
need,
|
||||
terms: snapshot.terms,
|
||||
responsePeriodDays: snapshot.responsePeriodDays,
|
||||
csrfToken,
|
||||
},
|
||||
progress.current,
|
||||
{ newKey: newIdempotencyKey, onDraft: onDraftSaved },
|
||||
);
|
||||
progress.current = outcome.progress;
|
||||
if (!mounted.current) return;
|
||||
if (outcome.kind === "sent") {
|
||||
onSent(outcome.invitation);
|
||||
return;
|
||||
}
|
||||
applyFailure(describeSendFailure(outcome.stage, outcome.error));
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
if (mounted.current) setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
function submit(event: FormEvent<HTMLFormElement>): void {
|
||||
event.preventDefault();
|
||||
void send();
|
||||
}
|
||||
|
||||
const salaryHintId = `${fieldId("salaryFrom")}-hint`;
|
||||
const locationHintId = `${fieldId("location")}-hint`;
|
||||
|
||||
return (
|
||||
<form className={styles.form} onSubmit={submit} noValidate aria-describedby={`${prefix}-intro`}>
|
||||
<p className={styles.intro} id={`${prefix}-intro`}>
|
||||
Кандидат увидит все условия до решения и до раскрытия контактов. Все поля обязательны, кроме
|
||||
комментария к способу связи; каждое условие пакета выберите явно.
|
||||
</p>
|
||||
{summaryVisible && issues.length > 0 ? (
|
||||
<div
|
||||
className={styles["issue-summary"]}
|
||||
ref={summaryRef}
|
||||
role="alert"
|
||||
aria-labelledby={`${prefix}-issues-title`}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<h2 id={`${prefix}-issues-title`}>Проверьте условия приглашения</h2>
|
||||
<ul>
|
||||
{issues.map((item) => (
|
||||
<li key={item.field}>{item.message}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<fieldset className={styles.fields} disabled={sending}>
|
||||
<legend className={styles["visually-hidden"]}>Условия приглашения</legend>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Роль</legend>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("roleTitle")}>Название роли</label>
|
||||
<input
|
||||
id={fieldId("roleTitle")}
|
||||
value={draft.roleTitle}
|
||||
maxLength={200}
|
||||
aria-invalid={invalid("roleTitle")}
|
||||
aria-describedby={describedBy(invalid("roleTitle") && errorId("roleTitle"))}
|
||||
onChange={(event) => change({ roleTitle: event.currentTarget.value }, ["roleTitle"])}
|
||||
/>
|
||||
<FieldError id={errorId("roleTitle")} message={issueOf("roleTitle")} />
|
||||
</div>
|
||||
<div className={styles.row}>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("specialization")}>Специализация</label>
|
||||
<select
|
||||
id={fieldId("specialization")}
|
||||
value={draft.specialization}
|
||||
aria-invalid={invalid("specialization")}
|
||||
aria-describedby={describedBy(
|
||||
invalid("specialization") && errorId("specialization"),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
change({ specialization: event.currentTarget.value as SpecializationCode | "" }, [
|
||||
"specialization",
|
||||
])
|
||||
}
|
||||
>
|
||||
<option value="">Не выбрана</option>
|
||||
{specializationCodes.map((code) => (
|
||||
<option key={code} value={code}>
|
||||
{specializationLabels[code]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<FieldError id={errorId("specialization")} message={issueOf("specialization")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("grade")}>Грейд</label>
|
||||
<select
|
||||
id={fieldId("grade")}
|
||||
value={draft.grade}
|
||||
aria-invalid={invalid("grade")}
|
||||
aria-describedby={describedBy(invalid("grade") && errorId("grade"))}
|
||||
onChange={(event) =>
|
||||
change({ grade: event.currentTarget.value as GradeCode | "" }, ["grade"])
|
||||
}
|
||||
>
|
||||
<option value="">Не выбран</option>
|
||||
{gradeCodes.map((code) => (
|
||||
<option key={code} value={code}>
|
||||
{gradeLabels[code]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<FieldError id={errorId("grade")} message={issueOf("grade")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("offerType")}>Тип предложения</label>
|
||||
<select
|
||||
id={fieldId("offerType")}
|
||||
value={draft.offerType}
|
||||
aria-invalid={invalid("offerType")}
|
||||
aria-describedby={describedBy(invalid("offerType") && errorId("offerType"))}
|
||||
onChange={(event) =>
|
||||
change({ offerType: event.currentTarget.value as InvitationOfferType | "" }, [
|
||||
"offerType",
|
||||
])
|
||||
}
|
||||
>
|
||||
<option value="">Не выбран</option>
|
||||
{offerTypeCodes.map((code) => (
|
||||
<option key={code} value={code}>
|
||||
{offerTypeLabels[code]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<FieldError id={errorId("offerType")} message={issueOf("offerType")} />
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Работа и команда</legend>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("tasks")}>Задачи</label>
|
||||
<p className={styles.hint} id={`${fieldId("tasks")}-hint`}>
|
||||
По одной задаче в строке, до 20 задач.
|
||||
</p>
|
||||
<textarea
|
||||
id={fieldId("tasks")}
|
||||
rows={4}
|
||||
value={draft.tasks}
|
||||
aria-invalid={invalid("tasks")}
|
||||
aria-describedby={describedBy(
|
||||
`${fieldId("tasks")}-hint`,
|
||||
invalid("tasks") && errorId("tasks"),
|
||||
)}
|
||||
onChange={(event) => change({ tasks: event.currentTarget.value }, ["tasks"])}
|
||||
/>
|
||||
<FieldError id={errorId("tasks")} message={issueOf("tasks")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("team")}>Команда</label>
|
||||
<p className={styles.hint} id={`${fieldId("team")}-hint`}>
|
||||
Размер, роли и способ работы. Без персональных данных сотрудников.
|
||||
</p>
|
||||
<textarea
|
||||
id={fieldId("team")}
|
||||
rows={3}
|
||||
maxLength={1000}
|
||||
value={draft.team}
|
||||
aria-invalid={invalid("team")}
|
||||
aria-describedby={describedBy(
|
||||
`${fieldId("team")}-hint`,
|
||||
invalid("team") && errorId("team"),
|
||||
)}
|
||||
onChange={(event) => change({ team: event.currentTarget.value }, ["team"])}
|
||||
/>
|
||||
<FieldError id={errorId("team")} message={issueOf("team")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("techStack")}>Технологии</label>
|
||||
<p className={styles.hint} id={`${fieldId("techStack")}-hint`}>
|
||||
Через запятую, например: Go, PostgreSQL, Kafka. Регистр не различается.
|
||||
</p>
|
||||
<input
|
||||
id={fieldId("techStack")}
|
||||
value={draft.techStack}
|
||||
aria-invalid={invalid("techStack")}
|
||||
aria-describedby={describedBy(
|
||||
`${fieldId("techStack")}-hint`,
|
||||
invalid("techStack") && errorId("techStack"),
|
||||
)}
|
||||
onChange={(event) => change({ techStack: event.currentTarget.value }, ["techStack"])}
|
||||
/>
|
||||
<FieldError id={errorId("techStack")} message={issueOf("techStack")} />
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Формат и место работы</legend>
|
||||
<fieldset
|
||||
className={styles.choices}
|
||||
aria-describedby={describedBy(invalid("workFormats") && errorId("workFormats"))}
|
||||
>
|
||||
<legend>Формат работы</legend>
|
||||
{workFormatCodes.map((code) => (
|
||||
<label key={code} className={styles.choice}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={draft.workFormats.includes(code)}
|
||||
aria-invalid={invalid("workFormats")}
|
||||
onChange={(event) => toggleFormat(code, event.currentTarget.checked)}
|
||||
/>
|
||||
{workFormatLabels[code]}
|
||||
</label>
|
||||
))}
|
||||
<FieldError id={errorId("workFormats")} message={issueOf("workFormats")} />
|
||||
</fieldset>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("location")}>Место работы</label>
|
||||
<p className={styles.hint} id={locationHintId}>
|
||||
Город или адрес офиса. Обязательно для офиса и гибрида.
|
||||
</p>
|
||||
<input
|
||||
id={fieldId("location")}
|
||||
value={draft.location}
|
||||
maxLength={100}
|
||||
aria-invalid={invalid("location")}
|
||||
aria-describedby={describedBy(
|
||||
locationHintId,
|
||||
invalid("location") && errorId("location"),
|
||||
)}
|
||||
onChange={(event) => change({ location: event.currentTarget.value }, ["location"])}
|
||||
/>
|
||||
<FieldError id={errorId("location")} message={issueOf("location")} />
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Способ связи после принятия</legend>
|
||||
<div className={styles.row}>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("channel")}>Канал связи</label>
|
||||
<select
|
||||
id={fieldId("channel")}
|
||||
value={draft.channel}
|
||||
aria-invalid={invalid("channel")}
|
||||
aria-describedby={describedBy(invalid("channel") && errorId("channel"))}
|
||||
onChange={(event) =>
|
||||
change(
|
||||
{ channel: event.currentTarget.value as InvitationCommunicationChannel | "" },
|
||||
["channel"],
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Не выбран</option>
|
||||
{communicationChannelCodes.map((code) => (
|
||||
<option key={code} value={code}>
|
||||
{communicationChannelLabels[code]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<FieldError id={errorId("channel")} message={issueOf("channel")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("channelDetails")}>Комментарий (необязательно)</label>
|
||||
<input
|
||||
id={fieldId("channelDetails")}
|
||||
value={draft.channelDetails}
|
||||
maxLength={300}
|
||||
aria-invalid={invalid("channelDetails")}
|
||||
aria-describedby={describedBy(
|
||||
invalid("channelDetails") && errorId("channelDetails"),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
change({ channelDetails: event.currentTarget.value }, ["channelDetails"])
|
||||
}
|
||||
/>
|
||||
<FieldError id={errorId("channelDetails")} message={issueOf("channelDetails")} />
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group} aria-describedby={salaryHintId}>
|
||||
<legend>Зарплатная вилка, рублей в месяц</legend>
|
||||
<p className={styles.hint} id={salaryHintId}>
|
||||
Целые рубли с шагом 1 000. Нижняя граница меньше верхней, ширина вилки от 10% до 40% от
|
||||
середины. База суммы указывается явно.
|
||||
</p>
|
||||
<div className={styles.row}>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("salaryFrom")}>От, ₽</label>
|
||||
<input
|
||||
id={fieldId("salaryFrom")}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1000}
|
||||
step={1000}
|
||||
value={draft.salaryFrom}
|
||||
aria-invalid={invalid("salaryFrom")}
|
||||
aria-describedby={describedBy(invalid("salaryFrom") && errorId("salaryFrom"))}
|
||||
onChange={(event) =>
|
||||
change({ salaryFrom: event.currentTarget.value }, ["salaryFrom", "salaryTo"])
|
||||
}
|
||||
/>
|
||||
<FieldError id={errorId("salaryFrom")} message={issueOf("salaryFrom")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("salaryTo")}>До, ₽</label>
|
||||
<input
|
||||
id={fieldId("salaryTo")}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1000}
|
||||
step={1000}
|
||||
value={draft.salaryTo}
|
||||
aria-invalid={invalid("salaryTo")}
|
||||
aria-describedby={describedBy(invalid("salaryTo") && errorId("salaryTo"))}
|
||||
onChange={(event) => change({ salaryTo: event.currentTarget.value }, ["salaryTo"])}
|
||||
/>
|
||||
<FieldError id={errorId("salaryTo")} message={issueOf("salaryTo")} />
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("taxBasis")}>База суммы</label>
|
||||
<select
|
||||
id={fieldId("taxBasis")}
|
||||
value={draft.taxBasis}
|
||||
aria-invalid={invalid("taxBasis")}
|
||||
aria-describedby={describedBy(invalid("taxBasis") && errorId("taxBasis"))}
|
||||
onChange={(event) =>
|
||||
change({ taxBasis: event.currentTarget.value as SalaryTaxBasis | "" }, [
|
||||
"taxBasis",
|
||||
])
|
||||
}
|
||||
>
|
||||
<option value="">Не выбрана</option>
|
||||
<option value="net">{taxBasisLabels.net}</option>
|
||||
<option value="gross">{taxBasisLabels.gross}</option>
|
||||
</select>
|
||||
<FieldError id={errorId("taxBasis")} message={issueOf("taxBasis")} />
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset className={styles.group}>
|
||||
<legend>Пакет</legend>
|
||||
<p className={styles.hint}>
|
||||
Для каждого условия выберите, предусмотрено ли оно. Пропустить условие нельзя.
|
||||
</p>
|
||||
{packageItemKeys.map((key) => {
|
||||
const field = `package.${key}` as const;
|
||||
const item = draft.packageItems[key];
|
||||
const choiceName = `${fieldId(field)}-status`;
|
||||
return (
|
||||
<fieldset
|
||||
key={key}
|
||||
className={styles.choices}
|
||||
aria-describedby={describedBy(invalid(field) && errorId(field))}
|
||||
>
|
||||
<legend>{packageItemLabels[key]}</legend>
|
||||
{(["provided", "not_provided"] as const).map((status) => (
|
||||
<label key={status} className={styles.choice}>
|
||||
<input
|
||||
type="radio"
|
||||
name={choiceName}
|
||||
value={status}
|
||||
checked={item.status === status}
|
||||
aria-invalid={invalid(field)}
|
||||
onChange={() => changePackage(key, { status: status as PackageChoice })}
|
||||
/>
|
||||
{status === "provided" ? "Предусмотрено" : notProvidedLabel}
|
||||
</label>
|
||||
))}
|
||||
{item.status === "provided" ? (
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId(field)}>{`${packageItemLabels[key]}: описание`}</label>
|
||||
<input
|
||||
id={fieldId(field)}
|
||||
value={item.description}
|
||||
maxLength={300}
|
||||
aria-invalid={invalid(field)}
|
||||
aria-describedby={describedBy(invalid(field) && errorId(field))}
|
||||
onChange={(event) =>
|
||||
changePackage(key, { description: event.currentTarget.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<FieldError id={errorId(field)} message={issueOf(field)} />
|
||||
</fieldset>
|
||||
);
|
||||
})}
|
||||
</fieldset>
|
||||
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={fieldId("responsePeriodDays")}>Срок ответа кандидата</label>
|
||||
<p className={styles.hint} id={`${fieldId("responsePeriodDays")}-hint`}>
|
||||
Срок начинается с момента доставки приглашения.
|
||||
</p>
|
||||
<select
|
||||
id={fieldId("responsePeriodDays")}
|
||||
value={draft.responsePeriodDays}
|
||||
aria-invalid={invalid("responsePeriodDays")}
|
||||
aria-describedby={describedBy(
|
||||
`${fieldId("responsePeriodDays")}-hint`,
|
||||
invalid("responsePeriodDays") && errorId("responsePeriodDays"),
|
||||
)}
|
||||
onChange={(event) =>
|
||||
change(
|
||||
{
|
||||
responsePeriodDays: Number(event.currentTarget.value) as InvitationResponsePeriod,
|
||||
},
|
||||
["responsePeriodDays"],
|
||||
)
|
||||
}
|
||||
>
|
||||
{responsePeriods.map((days) => (
|
||||
<option key={days} value={days}>
|
||||
{responsePeriodLabel(days)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<FieldError id={errorId("responsePeriodDays")} message={issueOf("responsePeriodDays")} />
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
{preview ? (
|
||||
<section
|
||||
ref={previewRef}
|
||||
className={styles.preview}
|
||||
tabIndex={-1}
|
||||
aria-label="Предпросмотр приглашения"
|
||||
>
|
||||
{previewStale ? (
|
||||
<p className={styles.stale} role="status">
|
||||
Условия изменены после предпросмотра. Нажмите «Обновить предпросмотр», чтобы увидеть
|
||||
текущие.
|
||||
</p>
|
||||
) : null}
|
||||
{renderPreview(preview.snapshot)}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{notice ? (
|
||||
<p
|
||||
ref={noticeRef}
|
||||
className={notice.tone === "error" ? styles["form-error"] : styles.notice}
|
||||
role={notice.tone === "error" ? "alert" : "status"}
|
||||
tabIndex={-1}
|
||||
>
|
||||
{notice.text}
|
||||
</p>
|
||||
) : null}
|
||||
{sending ? (
|
||||
<p className={styles.notice} role="status">
|
||||
Отправляем приглашение...
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className={styles.actions}>
|
||||
<Button variant="secondary" isBusy={sending} onClick={showPreview}>
|
||||
{preview ? "Обновить предпросмотр" : "Показать предпросмотр"}
|
||||
</Button>
|
||||
<Button type="submit" isBusy={sending}>
|
||||
Отправить приглашение
|
||||
</Button>
|
||||
</div>
|
||||
<p className={styles.hint}>
|
||||
Предпросмотр ничего не отправляет. Отправка создает черновик и сразу доставляет его в
|
||||
кабинет кандидата; запускается срок ответа.
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { InvitationComposePage } from "./ui/invitation-compose-page";
|
||||
@@ -0,0 +1,91 @@
|
||||
.content {
|
||||
display: grid;
|
||||
gap: var(--space-6);
|
||||
min-width: 0;
|
||||
max-width: 56rem;
|
||||
}
|
||||
|
||||
.entry,
|
||||
.summary {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.entry {
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.fact {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(9rem, 14rem) minmax(0, 1fr);
|
||||
gap: var(--space-1) var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fact > dt {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.fact > dd {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.result {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: var(--font-size-xl);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.title:focus {
|
||||
outline: var(--line-strong) solid var(--color-focus-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.state {
|
||||
display: inline-block;
|
||||
padding: var(--space-1) var(--space-3);
|
||||
border: var(--line-strong) solid var(--color-accent);
|
||||
border-radius: var(--radius-pill);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.notice {
|
||||
margin: 0;
|
||||
padding: var(--space-3);
|
||||
border-inline-start: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
@media (width < 36rem) {
|
||||
.fact {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.entry {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { MyOrganizationList, Session } from "../../../shared/api/schemas";
|
||||
import { needQueryKeys } from "../../../entities/need";
|
||||
import { InvitationComposePage } from "./invitation-compose-page";
|
||||
|
||||
const organizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccddee01";
|
||||
const handle = `cv1_${"B".repeat(43)}`;
|
||||
const session = {
|
||||
account: {
|
||||
id: "0199b4f2-7c1e-7d3a-9f00-aabbccddee02",
|
||||
email: "owner@example.test",
|
||||
email_verified: true,
|
||||
scenario: "employer",
|
||||
onboarding_step: "completed",
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "A".repeat(43),
|
||||
} satisfies Session;
|
||||
|
||||
function render(path: string, role: "owner" | "recruiter" = "owner"): string {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
|
||||
const page: MyOrganizationList = {
|
||||
items: [
|
||||
{
|
||||
organization: { id: organizationId, name: "Северный ветер", verification_level: "e0" },
|
||||
membership: {
|
||||
organization_id: organizationId,
|
||||
role,
|
||||
state: "active",
|
||||
joined_at: "2026-09-01T00:00:00Z",
|
||||
},
|
||||
},
|
||||
],
|
||||
page: { has_more: false, next_cursor: null },
|
||||
};
|
||||
queryClient.setQueryData(needQueryKeys.directory(session.account.id), {
|
||||
pages: [page],
|
||||
pageParams: [undefined],
|
||||
});
|
||||
return renderToString(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<InvitationComposePage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
const entryPath = `/employer/invitations/new?organization_id=${organizationId}&candidate_handle=${handle}&specialization=backend`;
|
||||
|
||||
describe("invitation compose page", () => {
|
||||
it("offers the terms form for a search entry of an owned organization", () => {
|
||||
const html = render(entryPath);
|
||||
|
||||
expect(html).toContain("Приглашение кандидату</h1>");
|
||||
expect(html).toContain("cv1_BBBB");
|
||||
expect(html).not.toContain(handle);
|
||||
expect(html).toContain("Северный ветер");
|
||||
for (const label of [
|
||||
"Название роли",
|
||||
"Специализация",
|
||||
"Грейд",
|
||||
"Тип предложения",
|
||||
"Задачи",
|
||||
"Команда",
|
||||
"Технологии",
|
||||
"Формат работы",
|
||||
"Место работы",
|
||||
"Канал связи",
|
||||
"От, ₽",
|
||||
"До, ₽",
|
||||
"База суммы",
|
||||
"Премии и бонусы",
|
||||
"Оборудование",
|
||||
"Обучение",
|
||||
"ДМС",
|
||||
"Срок ответа кандидата",
|
||||
]) {
|
||||
expect(html).toContain(label);
|
||||
}
|
||||
// The specialization of the search entry is preselected; nothing else is.
|
||||
expect(html).toMatch(/<option value="backend" selected="">Backend<\/option>/);
|
||||
expect(html).not.toMatch(/type="radio"[^>]*checked=""/);
|
||||
expect(html).toContain("Показать предпросмотр");
|
||||
expect(html).toContain("Отправить приглашение");
|
||||
expect(html).not.toContain("Так приглашение увидит кандидат");
|
||||
expect(html).not.toContain('role="alert"');
|
||||
});
|
||||
|
||||
it("does not offer the invitation to a member who is not the owner", () => {
|
||||
const html = render(entryPath, "recruiter");
|
||||
|
||||
expect(html).toContain("Нужны права владельца компании");
|
||||
expect(html).not.toContain("Отправить приглашение");
|
||||
});
|
||||
|
||||
it("asks to pick a candidate in the search when the address names none", () => {
|
||||
const html = render(`/employer/invitations/new?organization_id=${organizationId}`);
|
||||
|
||||
expect(html).toContain("Кандидат не выбран");
|
||||
expect(html).toContain(`href="/employer/candidates?organization_id=${organizationId}"`);
|
||||
expect(html).not.toContain("Отправить приглашение");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,527 @@
|
||||
import { useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import {
|
||||
getGetCurrentSessionQueryKey,
|
||||
useGetCurrentSession,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import { getOrganizationNeed } from "../../../shared/api/endpoints/need/need";
|
||||
import { useGetOrganization } from "../../../shared/api/endpoints/organization/organization";
|
||||
import {
|
||||
CandidateHandleRegExp,
|
||||
type InvitationNeedReference,
|
||||
type Organization,
|
||||
type OrganizationInvitation,
|
||||
type Session,
|
||||
type SpecializationCode,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
isAccessDenied,
|
||||
LoadingState,
|
||||
Mono,
|
||||
Page,
|
||||
StatusView,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
formatServerMoment,
|
||||
invitationQueryKeys,
|
||||
invitationStateLabels,
|
||||
readOrganizationInvitation,
|
||||
salaryFitLabels,
|
||||
} from "../../../entities/invitation";
|
||||
import { shortHandle, specializationCodes, specializationLabels } from "../../../entities/match";
|
||||
import {
|
||||
activeNeedOrganizations,
|
||||
isNeedSessionCurrent,
|
||||
needQueryKeys,
|
||||
useNeedOrganizationDirectory,
|
||||
type NeedOrganization,
|
||||
} from "../../../entities/need";
|
||||
import {
|
||||
emptyInvitationDraft,
|
||||
initialSendProgress,
|
||||
invitationDraftFromNeed,
|
||||
invitationDraftFromTerms,
|
||||
InvitationForm,
|
||||
type InvitationPreviewSnapshot,
|
||||
} from "../../../features/send-invitation";
|
||||
import { InvitationPreview } from "../../../widgets/invitation-preview";
|
||||
import styles from "./invitation-compose-page.module.css";
|
||||
|
||||
function isAccessLoss(error: unknown): error is ApiRequestError {
|
||||
return (
|
||||
error instanceof ApiRequestError &&
|
||||
(error.status === 401 || error.status === 403 || error.status === 404)
|
||||
);
|
||||
}
|
||||
|
||||
function specializationOf(value: string | null): SpecializationCode | "" {
|
||||
return specializationCodes.find((code) => code === value) ?? "";
|
||||
}
|
||||
|
||||
type OrganizationQuery = UseQueryResult<Organization, ApiRequestError>;
|
||||
|
||||
/** What the preview shows while the company card is not available. */
|
||||
function cardFallbackOf(organization: OrganizationQuery) {
|
||||
if (organization.isPending) return <LoadingState label="Загружаем карточку компании..." />;
|
||||
if (organization.isError) {
|
||||
return (
|
||||
<ErrorState
|
||||
error={organization.error}
|
||||
title="Не удалось загрузить карточку компании"
|
||||
isRetrying={organization.isFetching}
|
||||
onRetry={() => void organization.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type SentInvitationProps = {
|
||||
invitation: OrganizationInvitation;
|
||||
organization: OrganizationQuery;
|
||||
organizationId: string;
|
||||
};
|
||||
|
||||
/** The invitation after sending, with the state and the deadline the server stored. */
|
||||
function SentInvitation({ invitation, organization, organizationId }: SentInvitationProps) {
|
||||
const headingRef = useRef<HTMLHeadingElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
headingRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<section className={styles.result} aria-labelledby="invitation-result-title">
|
||||
<h2 id="invitation-result-title" ref={headingRef} tabIndex={-1} className={styles.title}>
|
||||
{invitation.state === "delivered" ? "Приглашение доставлено" : "Приглашение уже отправлено"}
|
||||
</h2>
|
||||
<dl className={styles.summary}>
|
||||
<div className={styles.fact}>
|
||||
<dt>Состояние</dt>
|
||||
<dd>
|
||||
<strong className={styles.state} data-state={invitation.state}>
|
||||
{invitationStateLabels[invitation.state]}
|
||||
</strong>
|
||||
</dd>
|
||||
</div>
|
||||
{invitation.delivered_at ? (
|
||||
<div className={styles.fact}>
|
||||
<dt>Доставлено</dt>
|
||||
<dd>
|
||||
<time dateTime={invitation.delivered_at}>
|
||||
{formatServerMoment(invitation.delivered_at)}
|
||||
</time>
|
||||
</dd>
|
||||
</div>
|
||||
) : null}
|
||||
{invitation.response_deadline_at ? (
|
||||
<div className={styles.fact}>
|
||||
<dt>Кандидат может ответить до</dt>
|
||||
<dd data-term="deadline">
|
||||
<time dateTime={invitation.response_deadline_at}>
|
||||
{formatServerMoment(invitation.response_deadline_at)}
|
||||
</time>
|
||||
</dd>
|
||||
</div>
|
||||
) : null}
|
||||
<div className={styles.fact}>
|
||||
<dt>Версия условий</dt>
|
||||
<dd>{invitation.terms_version}</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Зарплатный индикатор</dt>
|
||||
<dd>{salaryFitLabels[invitation.salary_fit]}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className={styles.hint}>
|
||||
Срок ответа задал сервер при доставке; письмо кандидату его не сдвигает. Контакты кандидата
|
||||
появятся только после принятия приглашения.
|
||||
</p>
|
||||
<InvitationPreview
|
||||
title="Отправленные условия"
|
||||
card={organization.data?.candidate_card ?? null}
|
||||
cardFallback={cardFallbackOf(organization)}
|
||||
terms={invitation.terms}
|
||||
responsePeriodDays={invitation.response_period_days}
|
||||
responseDeadlineAt={invitation.response_deadline_at}
|
||||
/>
|
||||
<div className={styles.actions}>
|
||||
<ButtonLink
|
||||
variant="secondary"
|
||||
to={`${paths.employer.candidates}?organization_id=${encodeURIComponent(organizationId)}`}
|
||||
>
|
||||
Вернуться к поиску кандидатов
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
type WorkspaceProps = {
|
||||
session: Session;
|
||||
organization: NeedOrganization;
|
||||
candidateHandle: string;
|
||||
specialization: SpecializationCode | "";
|
||||
needId: string | null;
|
||||
/** Saved draft to reopen, from the address the page was opened with. */
|
||||
initialInvitationId: string | null;
|
||||
onDropNeed: () => void;
|
||||
onRestart: () => void;
|
||||
onDraftSaved: (draft: OrganizationInvitation) => void;
|
||||
};
|
||||
|
||||
/** One invitation for one search entry; remounted when the organization or the entry changes. */
|
||||
function InvitationWorkspace({
|
||||
session,
|
||||
organization,
|
||||
candidateHandle,
|
||||
specialization,
|
||||
needId,
|
||||
initialInvitationId,
|
||||
onDropNeed,
|
||||
onRestart,
|
||||
onDraftSaved,
|
||||
}: WorkspaceProps) {
|
||||
const queryClient = useQueryClient();
|
||||
// The id that this page writes into the address after creating a draft
|
||||
// changes nothing here: the workspace already holds that draft.
|
||||
const [resumeId] = useState(initialInvitationId);
|
||||
const [sent, setSent] = useState<OrganizationInvitation | null>(null);
|
||||
const accountId = session.account.id;
|
||||
const organizationId = organization.organization.id;
|
||||
const sessionCurrent = isNeedSessionCurrent(queryClient, session);
|
||||
|
||||
const company = useGetOrganization(organizationId, {
|
||||
query: {
|
||||
enabled: sessionCurrent,
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
},
|
||||
});
|
||||
const resume = useQuery({
|
||||
queryKey: invitationQueryKeys.detail(accountId, organizationId, resumeId ?? "none"),
|
||||
queryFn: ({ signal }) => readOrganizationInvitation(organizationId, resumeId ?? "", signal),
|
||||
enabled: sessionCurrent && resumeId !== null,
|
||||
gcTime: 0,
|
||||
staleTime: Number.POSITIVE_INFINITY,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
});
|
||||
const need = useQuery({
|
||||
queryKey: [...needQueryKeys.detail(accountId, organizationId, needId ?? "none"), "invite"],
|
||||
queryFn: ({ signal }) => getOrganizationNeed(organizationId, needId ?? "", { signal }),
|
||||
enabled: sessionCurrent && needId !== null && resumeId === null,
|
||||
gcTime: 0,
|
||||
staleTime: Number.POSITIVE_INFINITY,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const header = (
|
||||
<dl className={styles.entry}>
|
||||
<div className={styles.fact}>
|
||||
<dt>Кандидат</dt>
|
||||
<dd>
|
||||
<Mono>{shortHandle(candidateHandle)}</Mono>
|
||||
{specialization ? `, ${specializationLabels[specialization]}` : null}
|
||||
</dd>
|
||||
</div>
|
||||
<div className={styles.fact}>
|
||||
<dt>Компания</dt>
|
||||
<dd>{organization.organization.name}</dd>
|
||||
</div>
|
||||
{need.data ? (
|
||||
<div className={styles.fact}>
|
||||
<dt>Потребность</dt>
|
||||
<dd>{`${need.data.title}, версия требований ${need.data.requirements_version}`}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
</dl>
|
||||
);
|
||||
|
||||
if (sent) {
|
||||
return (
|
||||
<>
|
||||
{header}
|
||||
<SentInvitation invitation={sent} organization={company} organizationId={organizationId} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (resumeId !== null) {
|
||||
if (resume.isPending) return <LoadingState label="Открываем сохраненный черновик..." />;
|
||||
if (resume.isError) {
|
||||
return isAccessLoss(resume.error) ? (
|
||||
<StatusView
|
||||
kind="forbidden"
|
||||
title="Черновик не найден"
|
||||
description="Черновик не найден в этой компании или доступ к нему закрыт."
|
||||
action={
|
||||
<Button variant="secondary" onClick={onRestart}>
|
||||
Начать новое приглашение
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<ErrorState
|
||||
error={resume.error}
|
||||
title="Не удалось открыть черновик"
|
||||
isRetrying={resume.isFetching}
|
||||
onRetry={() => void resume.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (resume.data.candidate_handle !== candidateHandle) {
|
||||
return (
|
||||
<StatusView
|
||||
kind="error"
|
||||
title="Черновик относится к другому кандидату"
|
||||
description="Откройте приглашение заново из поиска кандидатов."
|
||||
action={
|
||||
<Button variant="secondary" onClick={onRestart}>
|
||||
Начать новое приглашение
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (resume.data.state !== "draft") {
|
||||
return (
|
||||
<>
|
||||
{header}
|
||||
<SentInvitation
|
||||
invitation={resume.data}
|
||||
organization={company}
|
||||
organizationId={organizationId}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
} else if (needId !== null) {
|
||||
if (need.isPending) return <LoadingState label="Загружаем потребность..." />;
|
||||
if (need.isError) {
|
||||
return (
|
||||
<div className={styles.content}>
|
||||
<ErrorState
|
||||
error={need.error}
|
||||
title={
|
||||
isAccessLoss(need.error)
|
||||
? "Потребность не найдена"
|
||||
: "Не удалось загрузить потребность"
|
||||
}
|
||||
isRetrying={need.isFetching}
|
||||
onRetry={isAccessLoss(need.error) ? undefined : () => void need.refetch()}
|
||||
/>
|
||||
<div className={styles.actions}>
|
||||
<Button variant="secondary" onClick={onDropNeed}>
|
||||
Пригласить без потребности
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const draft = resume.data ?? null;
|
||||
const needReference: InvitationNeedReference | null = draft
|
||||
? draft.need
|
||||
: need.data
|
||||
? { need_id: need.data.id, requirements_version: need.data.requirements_version }
|
||||
: null;
|
||||
const initialDraft = draft
|
||||
? invitationDraftFromTerms(draft.terms, draft.response_period_days)
|
||||
: need.data
|
||||
? invitationDraftFromNeed(need.data, specialization)
|
||||
: emptyInvitationDraft(specialization);
|
||||
|
||||
const renderPreview = (snapshot: InvitationPreviewSnapshot) => (
|
||||
<InvitationPreview
|
||||
card={company.data?.candidate_card ?? null}
|
||||
cardFallback={cardFallbackOf(company)}
|
||||
terms={snapshot.terms}
|
||||
responsePeriodDays={snapshot.responsePeriodDays}
|
||||
responseDeadlineAt={null}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{header}
|
||||
{draft ? (
|
||||
<p className={styles.notice} role="status">
|
||||
{`Открыт сохраненный черновик, версия ${draft.version}. Он еще не отправлен.`}
|
||||
</p>
|
||||
) : null}
|
||||
<InvitationForm
|
||||
organizationId={organizationId}
|
||||
candidateHandle={candidateHandle}
|
||||
need={needReference}
|
||||
csrfToken={session.csrf_token}
|
||||
initialDraft={initialDraft}
|
||||
initialProgress={draft ? { ...initialSendProgress, draft } : initialSendProgress}
|
||||
isSessionCurrent={() => isNeedSessionCurrent(queryClient, session)}
|
||||
renderPreview={renderPreview}
|
||||
onDraftSaved={onDraftSaved}
|
||||
onSent={(invitation) => {
|
||||
queryClient.setQueryData(
|
||||
invitationQueryKeys.detail(accountId, organizationId, invitation.id),
|
||||
invitation,
|
||||
);
|
||||
setSent(invitation);
|
||||
}}
|
||||
onCsrfFailed={() =>
|
||||
void queryClient.invalidateQueries({ queryKey: getGetCurrentSessionQueryKey() })
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The invitation of one search entry by the owner of an organization: the
|
||||
* terms form, the preview of the company card and the terms as the candidate
|
||||
* sees them, and the send result with the server deadline. The candidate is
|
||||
* named only by the organization-scoped handle from the search.
|
||||
*/
|
||||
export function InvitationComposePage() {
|
||||
const queryClient = useQueryClient();
|
||||
const sessionQuery = useGetCurrentSession({ query: { retry: false } });
|
||||
const session = sessionQuery.data;
|
||||
const sessionReady =
|
||||
Boolean(session && session.account.scenario === "employer") &&
|
||||
isNeedSessionCurrent(queryClient, session);
|
||||
const directory = useNeedOrganizationDirectory(session, sessionReady);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [generation, setGeneration] = useState(0);
|
||||
const organizationId = searchParams.get("organization_id");
|
||||
const candidateHandle = searchParams.get("candidate_handle");
|
||||
const specialization = specializationOf(searchParams.get("specialization"));
|
||||
const needId = searchParams.get("need_id");
|
||||
const validEntry = Boolean(
|
||||
organizationId && candidateHandle && CandidateHandleRegExp.test(candidateHandle),
|
||||
);
|
||||
|
||||
const pages = directory.data?.pages;
|
||||
const owners = useMemo(() => activeNeedOrganizations(pages ?? []), [pages]);
|
||||
const selected = owners.find((item) => item.organization.id === organizationId);
|
||||
const member = (pages ?? [])
|
||||
.flatMap((page) => page.items)
|
||||
.find((item) => item.organization.id === organizationId);
|
||||
const hasMore = directory.hasNextPage;
|
||||
const fetchNext = directory.fetchNextPage;
|
||||
const fetching = directory.isFetchingNextPage;
|
||||
|
||||
// The organization of the address may sit on a later page of the directory.
|
||||
useEffect(() => {
|
||||
if (!directory.data || directory.isError || fetching) return;
|
||||
if (hasMore && !member) void fetchNext();
|
||||
}, [directory.data, directory.isError, fetchNext, fetching, hasMore, member]);
|
||||
|
||||
const loading =
|
||||
!sessionQuery.isError &&
|
||||
(!sessionReady || directory.isPending || (hasMore && !member && !directory.isError));
|
||||
|
||||
function updateParams(change: (params: URLSearchParams) => void): void {
|
||||
setSearchParams(
|
||||
(current) => {
|
||||
const next = new URLSearchParams(current);
|
||||
change(next);
|
||||
return next;
|
||||
},
|
||||
{ replace: true },
|
||||
);
|
||||
}
|
||||
|
||||
const searchLink = organizationId
|
||||
? `${paths.employer.candidates}?organization_id=${encodeURIComponent(organizationId)}`
|
||||
: paths.employer.candidates;
|
||||
|
||||
return (
|
||||
<Page
|
||||
title="Приглашение кандидату"
|
||||
eyebrow="Кабинет работодателя"
|
||||
lead="Заполните условия, проверьте, как приглашение увидит кандидат, и отправьте его. Кандидат получит приглашение в кабинет сразу после отправки."
|
||||
width="wide"
|
||||
>
|
||||
{!validEntry ? (
|
||||
<EmptyState
|
||||
title="Кандидат не выбран"
|
||||
description="Приглашение создается из результата поиска: откройте поиск кандидатов и нажмите «Пригласить» у нужной записи."
|
||||
action={<ButtonLink to={searchLink}>Перейти к поиску кандидатов</ButtonLink>}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{sessionQuery.isError ? (
|
||||
isAccessLoss(sessionQuery.error) ? (
|
||||
<ForbiddenState error={sessionQuery.error} title="Текущий вход не подтвержден" />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={sessionQuery.error}
|
||||
isRetrying={sessionQuery.isFetching}
|
||||
onRetry={() => void sessionQuery.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{directory.isError ? (
|
||||
isAccessDenied(directory.error) ? (
|
||||
<ForbiddenState error={directory.error} />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={directory.error}
|
||||
isRetrying={directory.isFetching}
|
||||
onRetry={() => void directory.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{loading ? <LoadingState label="Проверяем компанию..." /> : null}
|
||||
{session && sessionReady && directory.data && !directory.isError && !loading ? (
|
||||
<div className={styles.content}>
|
||||
{selected && candidateHandle ? (
|
||||
<InvitationWorkspace
|
||||
key={`${session.account.id}:${selected.organization.id}:${candidateHandle}:${generation}`}
|
||||
session={session}
|
||||
organization={selected}
|
||||
candidateHandle={candidateHandle}
|
||||
specialization={specialization}
|
||||
needId={needId}
|
||||
initialInvitationId={generation === 0 ? searchParams.get("invitation_id") : null}
|
||||
onDropNeed={() => updateParams((params) => params.delete("need_id"))}
|
||||
onRestart={() => {
|
||||
updateParams((params) => params.delete("invitation_id"));
|
||||
setGeneration((current) => current + 1);
|
||||
}}
|
||||
onDraftSaved={(draft) =>
|
||||
updateParams((params) => params.set("invitation_id", draft.id))
|
||||
}
|
||||
/>
|
||||
) : member ? (
|
||||
<ForbiddenState
|
||||
title="Нужны права владельца компании"
|
||||
description="Приглашать кандидатов в этой версии может только владелец компании."
|
||||
/>
|
||||
) : (
|
||||
<EmptyState
|
||||
title="Компания не найдена среди ваших"
|
||||
description="Откройте приглашение из поиска кандидатов компании, где вы владелец."
|
||||
action={
|
||||
<ButtonLink to={paths.employer.candidates}>К поиску кандидатов</ButtonLink>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -42,8 +42,9 @@ export const paths = {
|
||||
candidatesForNeed: (needId: string, organizationId: string) =>
|
||||
`/employer/candidates?organization_id=${encodeURIComponent(organizationId)}&need_id=${encodeURIComponent(needId)}`,
|
||||
invitations: "/employer/invitations",
|
||||
invitationNew: "/employer/invitations/new",
|
||||
/**
|
||||
* Opens the invitations section for one search result. The handle is the
|
||||
* Opens the invitation form for one search result. The handle is the
|
||||
* organization-scoped alias from the search, never a candidate identifier.
|
||||
*/
|
||||
inviteCandidate: (input: {
|
||||
@@ -58,7 +59,7 @@ export const paths = {
|
||||
specialization: input.specialization,
|
||||
});
|
||||
if (input.needId) query.set("need_id", input.needId);
|
||||
return `/employer/invitations?${query.toString()}`;
|
||||
return `/employer/invitations/new?${query.toString()}`;
|
||||
},
|
||||
notifications: "/employer/notifications",
|
||||
supportCases: "/employer/support/cases",
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// Public API of the invitation-preview widget: the company card and the
|
||||
// terms of an invitation as the candidate sees them.
|
||||
|
||||
export { InvitationPreview } from "./ui/invitation-preview";
|
||||
@@ -0,0 +1,97 @@
|
||||
.root {
|
||||
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-canvas);
|
||||
}
|
||||
|
||||
.heading {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-text-secondary);
|
||||
line-height: var(--line-height-body);
|
||||
}
|
||||
|
||||
.company {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.terms {
|
||||
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);
|
||||
}
|
||||
|
||||
.role {
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--font-size-l);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.facts,
|
||||
.package {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.fact {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(9rem, 14rem) minmax(0, 1fr);
|
||||
gap: var(--space-1) var(--space-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fact > dt {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.fact > dd {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.package .fact {
|
||||
grid-template-columns: minmax(7rem, 10rem) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.multiline {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.list {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
margin: 0;
|
||||
padding-left: var(--space-5);
|
||||
}
|
||||
|
||||
@media (width < 36rem) {
|
||||
.root,
|
||||
.terms {
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.fact,
|
||||
.package .fact {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CandidateOrganizationCard, InvitationTerms } from "../../../shared/api/schemas";
|
||||
import { InvitationPreview } from "./invitation-preview";
|
||||
|
||||
const card: CandidateOrganizationCard = {
|
||||
id: "0199b4f2-7c1e-7d3a-9f00-aabbccddee01",
|
||||
name: "Северный ветер",
|
||||
description: "Платежная инфраструктура для малого бизнеса",
|
||||
sphere: "Финтех",
|
||||
contacts: { website: "https://north.example", email: null, phone: null, telegram: null },
|
||||
verification_level: "e0",
|
||||
};
|
||||
|
||||
const terms: 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" },
|
||||
},
|
||||
};
|
||||
|
||||
const text = (html: string) => html.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ");
|
||||
|
||||
describe("invitation preview", () => {
|
||||
it("shows the company card and every term as the candidate sees them", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<InvitationPreview
|
||||
card={card}
|
||||
terms={terms}
|
||||
responsePeriodDays={7}
|
||||
responseDeadlineAt={null}
|
||||
/>,
|
||||
);
|
||||
const content = text(html);
|
||||
|
||||
for (const value of [
|
||||
"Северный ветер",
|
||||
"Платежная инфраструктура для малого бизнеса",
|
||||
"Уровень E0",
|
||||
"Middle Go-разработчик",
|
||||
"Backend, Middle",
|
||||
"Полная занятость",
|
||||
"Развивать сервис выплат",
|
||||
"Перевести отчеты на события",
|
||||
"Go, PostgreSQL",
|
||||
"Удаленно, Гибридно",
|
||||
"Москва",
|
||||
"Видеозвонок. Созвон с тимлидом",
|
||||
"Квартальная премия до 20%",
|
||||
"Ноутбук и монитор",
|
||||
"7 дней с момента доставки",
|
||||
]) {
|
||||
expect(content).toContain(value);
|
||||
}
|
||||
expect(content).toMatch(/от 100\s000 ₽ до 140\s000 ₽ в месяц, после налога \(net\)/);
|
||||
expect(html.match(/Не предусмотрено/g)).toHaveLength(2);
|
||||
expect(html).toContain('data-package="training"');
|
||||
expect(html).not.toContain("<time");
|
||||
});
|
||||
|
||||
it("shows the server deadline of a sent invitation and a fallback without the card", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<InvitationPreview
|
||||
card={null}
|
||||
cardFallback={<p>Карточка недоступна</p>}
|
||||
terms={{ ...terms, location: null, work_formats: ["remote"] }}
|
||||
responsePeriodDays={7}
|
||||
responseDeadlineAt="2026-10-16T10:00:00Z"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Карточка недоступна");
|
||||
expect(html).toContain('<time dateTime="2026-10-16T10:00:00Z">16 октября 2026');
|
||||
expect(html).toContain("10:00 UTC</time>");
|
||||
expect(text(html)).toContain("Не требуется: только удаленная работа");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
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 styles from "./invitation-preview.module.css";
|
||||
|
||||
type InvitationPreviewProps = {
|
||||
/** The company card as the candidate sees it, or null while it is unavailable. */
|
||||
card: CandidateOrganizationCard | null;
|
||||
/** What to show instead of the card, for example a loading or error state. */
|
||||
cardFallback?: ReactNode;
|
||||
terms: InvitationTerms;
|
||||
responsePeriodDays: number;
|
||||
/** The server deadline once the invitation is delivered; null for an unsent draft. */
|
||||
responseDeadlineAt: string | null;
|
||||
title?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The invitation through the eyes of the candidate: the company card and
|
||||
* every term, each condition of the package shown either with its
|
||||
* description or as explicitly not provided. It renders data only and sends
|
||||
* nothing; the same view serves the preview of a draft and a sent invitation.
|
||||
*/
|
||||
export function InvitationPreview({
|
||||
card,
|
||||
cardFallback,
|
||||
terms,
|
||||
responsePeriodDays,
|
||||
responseDeadlineAt,
|
||||
title = "Так приглашение увидит кандидат",
|
||||
}: InvitationPreviewProps) {
|
||||
const location =
|
||||
terms.location ??
|
||||
(terms.work_formats.every((format) => format === "remote")
|
||||
? "Не требуется: только удаленная работа"
|
||||
: "Не указано");
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<div className={styles.heading}>
|
||||
<h3 className={styles.title}>{title}</h3>
|
||||
<p className={styles.hint}>
|
||||
Кандидат видит карточку компании и все условия до решения. Контакты кандидата компания
|
||||
получит только после принятия приглашения.
|
||||
</p>
|
||||
</div>
|
||||
<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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -71,7 +71,7 @@ describe("match list", () => {
|
||||
|
||||
it("links every entry to the invitation with the organization-scoped handle, also unconfirmed ones", () => {
|
||||
const html = render(matchModelFixture());
|
||||
const links = [...html.matchAll(/href="(\/employer\/invitations\?[^"]+)"/g)].map(
|
||||
const links = [...html.matchAll(/href="(\/employer\/invitations\/new\?[^"]+)"/g)].map(
|
||||
(match) => new URL((match[1] ?? "").replaceAll("&", "&"), "http://x"),
|
||||
);
|
||||
|
||||
|
||||
Reference in new issue
Block a user