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
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user