feat(frontend): list the company invitations in the employer cabinet
This commit is contained in:
1 parent
84454116f2
commit
d8abaae85b
23 files changed
+1349
-222
No files matched your search
@@ -174,6 +174,7 @@ describe("route groups", () => {
|
||||
["/employer/support/cases/new", "Обратиться в поддержку", "Разделы кабинета работодателя"],
|
||||
["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"],
|
||||
["/employer/invitations/new", "Приглашение кандидату", "Разделы кабинета работодателя"],
|
||||
["/employer/invitations", "Приглашения", "Разделы кабинета работодателя"],
|
||||
])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => {
|
||||
const html = await renderHtml(path);
|
||||
|
||||
@@ -296,10 +297,13 @@ describe("product readiness", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("labels the remaining cabinet scaffolds as placeholders", async () => {
|
||||
expect(await renderHtml("/employer/invitations")).toContain(
|
||||
"Экран будет реализован в одной из следующих задач",
|
||||
);
|
||||
it("routes the employer invitation list to its own screen, not a placeholder", async () => {
|
||||
const html = await renderHtml("/employer/invitations");
|
||||
|
||||
expect(html).toMatch(/<h1[^>]*>Приглашения<\/h1>/);
|
||||
expect(html).toContain("Проверяем компанию...");
|
||||
expect(html).not.toContain("Экран будет реализован в одной из следующих задач");
|
||||
expect(html).not.toContain("Заготовка");
|
||||
});
|
||||
|
||||
it("routes the candidate inbox and one invitation to their own screens, not placeholders", async () => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from "../../pages/candidate-invitations";
|
||||
import { CandidateOnboardingPage } from "../../pages/candidate-onboarding";
|
||||
import { CompanyPage } from "../../pages/company";
|
||||
import { EmployerInvitationsPage } from "../../pages/employer-invitations";
|
||||
import { PrivacyPage } from "../../pages/privacy";
|
||||
import { SessionGate } from "../../entities/session";
|
||||
import { MatchesPage } from "../../pages/matches";
|
||||
@@ -17,7 +18,6 @@ import { NotFoundPage } from "../../pages/not-found";
|
||||
import { NeedEditorPage } from "../../pages/need-editor";
|
||||
import { NeedListPage } from "../../pages/needs";
|
||||
import { CandidateNotificationsPage, EmployerNotificationsPage } from "../../pages/notifications";
|
||||
import { PlaceholderPage } from "../../pages/placeholder";
|
||||
import { ProfilePage } from "../../pages/profile";
|
||||
import { QuestionnairePage } from "../../pages/questionnaire";
|
||||
import { StatusPage } from "../../pages/status";
|
||||
@@ -141,10 +141,7 @@ export function createRoutes(stand: StandMode = standMode): RouteObject[] {
|
||||
element: <SupportCaseDetailPage />,
|
||||
},
|
||||
{ path: paths.employer.candidates, element: <MatchesPage /> },
|
||||
{
|
||||
path: paths.employer.invitations,
|
||||
element: <PlaceholderPage screen="employerInvitations" />,
|
||||
},
|
||||
{ path: paths.employer.invitations, element: <EmployerInvitationsPage /> },
|
||||
{ path: paths.employer.invitationNew, element: <InvitationComposePage /> },
|
||||
{ path: paths.employer.notifications, element: <EmployerNotificationsPage /> },
|
||||
{
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { setupServer } from "msw/node";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ApiRequestError, invalidResponseCode } from "../../../shared/api";
|
||||
import { invitationListPageSize, listInvitationsOfOrganization } from "./organization-invitations";
|
||||
|
||||
const organizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccddee01";
|
||||
const base = `http://localhost/api/v1/organizations/${organizationId}/invitations`;
|
||||
|
||||
const server = setupServer();
|
||||
beforeAll(() => server.listen({ onUnhandledFrame: "error" }));
|
||||
beforeEach(() => {
|
||||
// The browser client uses same-origin paths; Node needs an origin.
|
||||
const realFetch = globalThis.fetch;
|
||||
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
|
||||
realFetch(new URL(input, "http://localhost"), init),
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
server.resetHandlers();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
const summary = {
|
||||
id: "0199b4f2-7c1e-7d3a-9f00-aabbccdd3301",
|
||||
candidate_handle: `cv1_${"A".repeat(43)}`,
|
||||
need: null,
|
||||
state: "delivered",
|
||||
expiry_reason: null,
|
||||
version: 2,
|
||||
terms_version: 1,
|
||||
role_title: "Middle Go-разработчик",
|
||||
salary: {
|
||||
salary_from: 100000,
|
||||
salary_to: 140000,
|
||||
currency: "RUB",
|
||||
period: "month",
|
||||
tax_basis: "net",
|
||||
},
|
||||
response_deadline_at: "2099-10-16T10:00:00Z",
|
||||
contact_access: { status: "not_granted", fields: [] },
|
||||
created_at: "2026-10-09T10:00:00Z",
|
||||
updated_at: "2026-10-09T10:05:00Z",
|
||||
};
|
||||
|
||||
describe("organization invitation list transport", () => {
|
||||
it("reads a page with the page size and the cursor and parses it with the contract", async () => {
|
||||
const seen: { query: URLSearchParams | null } = { query: null };
|
||||
server.use(
|
||||
http.get(base, ({ request }) => {
|
||||
seen.query = new URL(request.url).searchParams;
|
||||
return HttpResponse.json({
|
||||
items: [summary],
|
||||
page: { has_more: true, next_cursor: "next-1" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const list = await listInvitationsOfOrganization(organizationId, { cursor: "first-1" });
|
||||
|
||||
expect(seen.query?.get("limit")).toBe(String(invitationListPageSize));
|
||||
expect(seen.query?.get("cursor")).toBe("first-1");
|
||||
expect(list.items[0]?.role_title).toBe("Middle Go-разработчик");
|
||||
expect(list.page).toEqual({ has_more: true, next_cursor: "next-1" });
|
||||
});
|
||||
|
||||
it("sends no cursor for the first page", async () => {
|
||||
const seen: { query: URLSearchParams | null } = { query: null };
|
||||
server.use(
|
||||
http.get(base, ({ request }) => {
|
||||
seen.query = new URL(request.url).searchParams;
|
||||
return HttpResponse.json({ items: [], page: { has_more: false, next_cursor: null } });
|
||||
}),
|
||||
);
|
||||
|
||||
await listInvitationsOfOrganization(organizationId);
|
||||
|
||||
expect(seen.query?.has("cursor")).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses a body that does not match the contract instead of listing it", async () => {
|
||||
server.use(http.get(base, () => HttpResponse.json({ items: [{ id: "not-an-invitation" }] })));
|
||||
|
||||
const failure = await listInvitationsOfOrganization(organizationId).catch(
|
||||
(error: unknown) => error,
|
||||
);
|
||||
|
||||
expect(failure).toBeInstanceOf(ApiRequestError);
|
||||
expect((failure as ApiRequestError).code).toBe(invalidResponseCode);
|
||||
});
|
||||
|
||||
it("surfaces an access refusal with its status", async () => {
|
||||
server.use(
|
||||
http.get(base, () =>
|
||||
HttpResponse.json(
|
||||
{ type: "about:blank", title: "Forbidden", status: 403, code: "forbidden" },
|
||||
{ status: 403, headers: { "Content-Type": "application/problem+json" } },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const failure = await listInvitationsOfOrganization(organizationId).catch(
|
||||
(error: unknown) => error,
|
||||
);
|
||||
|
||||
expect(failure).toBeInstanceOf(ApiRequestError);
|
||||
expect((failure as ApiRequestError).status).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -4,15 +4,19 @@ import {
|
||||
getGetOrganizationInvitationContactsQueryKey,
|
||||
getGetOrganizationInvitationQueryKey,
|
||||
getOrganizationInvitation,
|
||||
getListOrganizationInvitationsQueryKey,
|
||||
getOrganizationInvitationContacts,
|
||||
listOrganizationInvitations,
|
||||
sendOrganizationInvitation,
|
||||
updateOrganizationInvitation,
|
||||
} from "../../../shared/api/endpoints/invitation/invitation";
|
||||
import {
|
||||
ContactDisclosure as contactDisclosureSchema,
|
||||
OrganizationInvitation as organizationInvitationSchema,
|
||||
OrganizationInvitationList as organizationInvitationListSchema,
|
||||
type ContactDisclosure,
|
||||
type OrganizationInvitation,
|
||||
type OrganizationInvitationList,
|
||||
type OrganizationInvitationCreate,
|
||||
type OrganizationInvitationUpdate,
|
||||
} from "../../../shared/api/schemas";
|
||||
@@ -36,6 +40,12 @@ function parseInvitation(value: unknown): OrganizationInvitation {
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function parseInvitationList(value: unknown): OrganizationInvitationList {
|
||||
const parsed = organizationInvitationListSchema.safeParse(value);
|
||||
if (!parsed.success) throw invalidResponse();
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
type CommandOptions = {
|
||||
organizationId: string;
|
||||
csrfToken: string;
|
||||
@@ -93,6 +103,31 @@ export async function sendInvitationDraft(
|
||||
);
|
||||
}
|
||||
|
||||
/** Page size of the organization's invitation list. */
|
||||
export const invitationListPageSize = 20;
|
||||
|
||||
/**
|
||||
* Reads one page of the organization's invitations, drafts included, newest
|
||||
* first. The cursor comes only from the previous page. The summaries name a
|
||||
* candidate by the opaque handle alone and hold no contact value.
|
||||
*/
|
||||
export async function listInvitationsOfOrganization(
|
||||
organizationId: string,
|
||||
options: { cursor?: string | undefined; signal?: AbortSignal | undefined } = {},
|
||||
): Promise<OrganizationInvitationList> {
|
||||
const params = {
|
||||
limit: invitationListPageSize,
|
||||
...(options.cursor === undefined ? {} : { cursor: options.cursor }),
|
||||
};
|
||||
return parseInvitationList(
|
||||
await listOrganizationInvitations(
|
||||
organizationId,
|
||||
params,
|
||||
options.signal ? { signal: options.signal } : {},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Reads one invitation of the organization and checks it against the contract. */
|
||||
export async function readOrganizationInvitation(
|
||||
organizationId: string,
|
||||
@@ -123,6 +158,12 @@ export async function readInvitationContacts(
|
||||
|
||||
/** Invitation reads stay separate for each signed-in account. */
|
||||
export const invitationQueryKeys = {
|
||||
/** Every page of the organization's invitation list for one account. */
|
||||
list: (accountId: string, organizationId: string) =>
|
||||
[
|
||||
...getListOrganizationInvitationsQueryKey(organizationId, { limit: invitationListPageSize }),
|
||||
accountId,
|
||||
] as const,
|
||||
detail: (accountId: string, organizationId: string, invitationId: string) =>
|
||||
[...getGetOrganizationInvitationQueryKey(organizationId, invitationId), accountId] as const,
|
||||
contacts: (accountId: string, organizationId: string, invitationId: string) =>
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
|
||||
export {
|
||||
createInvitationDraft,
|
||||
invitationListPageSize,
|
||||
invitationQueryKeys,
|
||||
listInvitationsOfOrganization,
|
||||
readInvitationContacts,
|
||||
readOrganizationInvitation,
|
||||
sendInvitationDraft,
|
||||
@@ -21,6 +23,14 @@ export {
|
||||
readCandidateInvitation,
|
||||
viewCandidateInvitation,
|
||||
} from "./api/candidate-invitations";
|
||||
export {
|
||||
filterInvitations,
|
||||
invitationFilterOptions,
|
||||
invitationGroup,
|
||||
invitationStateTone,
|
||||
type InvitationFilter,
|
||||
type InvitationGroup,
|
||||
} from "./model/list-groups";
|
||||
export { formatRubles, formatSalaryRange, formatServerMoment } from "./model/format";
|
||||
export {
|
||||
candidateInvitationStateLabels,
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { InvitationState } from "../../../shared/api/schemas";
|
||||
import {
|
||||
filterInvitations,
|
||||
invitationFilterOptions,
|
||||
invitationGroup,
|
||||
invitationStateTone,
|
||||
} from "./list-groups";
|
||||
|
||||
const allStates = InvitationState.options;
|
||||
|
||||
describe("invitation list groups", () => {
|
||||
it("puts every state of the contract into exactly one group", () => {
|
||||
for (const state of allStates) {
|
||||
expect(["draft", "pending", "accepted", "closed"]).toContain(invitationGroup(state));
|
||||
}
|
||||
});
|
||||
|
||||
it("separates waiting, accepted, closed, and draft invitations", () => {
|
||||
expect(invitationGroup("draft")).toBe("draft");
|
||||
for (const state of ["delivered", "viewed", "counter"] as const) {
|
||||
expect(invitationGroup(state)).toBe("pending");
|
||||
}
|
||||
expect(invitationGroup("accepted")).toBe("accepted");
|
||||
expect(invitationGroup("terms_agreed")).toBe("accepted");
|
||||
for (const state of [
|
||||
"declined",
|
||||
"expired",
|
||||
"withdrawn",
|
||||
"cancelled_by_candidate",
|
||||
"no_deal",
|
||||
] as const) {
|
||||
expect(invitationGroup(state)).toBe("closed");
|
||||
}
|
||||
});
|
||||
|
||||
it("offers the four groups of the screen and the drafts", () => {
|
||||
expect(invitationFilterOptions.map((option) => option.label)).toEqual([
|
||||
"Все",
|
||||
"Ожидают ответа",
|
||||
"Приняты",
|
||||
"Закрыты",
|
||||
"Черновики",
|
||||
]);
|
||||
});
|
||||
|
||||
it("filters by group and keeps the server order", () => {
|
||||
const items = [
|
||||
{ id: "1", state: "declined" },
|
||||
{ id: "2", state: "draft" },
|
||||
{ id: "3", state: "viewed" },
|
||||
{ id: "4", state: "accepted" },
|
||||
{ id: "5", state: "delivered" },
|
||||
{ id: "6", state: "expired" },
|
||||
] as const;
|
||||
|
||||
expect(filterInvitations(items, "all").map((item) => item.id)).toEqual([
|
||||
"1",
|
||||
"2",
|
||||
"3",
|
||||
"4",
|
||||
"5",
|
||||
"6",
|
||||
]);
|
||||
expect(filterInvitations(items, "pending").map((item) => item.id)).toEqual(["3", "5"]);
|
||||
expect(filterInvitations(items, "accepted").map((item) => item.id)).toEqual(["4"]);
|
||||
expect(filterInvitations(items, "closed").map((item) => item.id)).toEqual(["1", "6"]);
|
||||
expect(filterInvitations(items, "draft").map((item) => item.id)).toEqual(["2"]);
|
||||
});
|
||||
|
||||
it("repeats the meaning of the state in the tone of its tag", () => {
|
||||
expect(invitationStateTone("draft")).toBe("neutral");
|
||||
expect(invitationStateTone("delivered")).toBe("accent");
|
||||
expect(invitationStateTone("viewed")).toBe("accent");
|
||||
expect(invitationStateTone("accepted")).toBe("success");
|
||||
expect(invitationStateTone("declined")).toBe("danger");
|
||||
expect(invitationStateTone("expired")).toBe("danger");
|
||||
expect(invitationStateTone("withdrawn")).toBe("danger");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { InvitationState } from "../../../shared/api/schemas";
|
||||
import type { TagTone } from "../../../shared/ui";
|
||||
|
||||
/**
|
||||
* Groups of the organization's invitation list. The groups cover every state
|
||||
* of the contract once, so a state that a later release adds fails the
|
||||
* exhaustive map below at compile time instead of vanishing from the list.
|
||||
*/
|
||||
export type InvitationGroup = "draft" | "pending" | "accepted" | "closed";
|
||||
|
||||
export type InvitationFilter = "all" | InvitationGroup;
|
||||
|
||||
const groupOfState: Readonly<Record<InvitationState, InvitationGroup>> = {
|
||||
draft: "draft",
|
||||
delivered: "pending",
|
||||
viewed: "pending",
|
||||
counter: "pending",
|
||||
accepted: "accepted",
|
||||
interview_scheduled: "accepted",
|
||||
interviewed: "accepted",
|
||||
negotiation: "accepted",
|
||||
terms_agreed: "accepted",
|
||||
no_deal: "closed",
|
||||
declined: "closed",
|
||||
expired: "closed",
|
||||
withdrawn: "closed",
|
||||
cancelled_by_candidate: "closed",
|
||||
};
|
||||
|
||||
export function invitationGroup(state: InvitationState): InvitationGroup {
|
||||
return groupOfState[state];
|
||||
}
|
||||
|
||||
/** Filters in the order the list offers them; drafts have their own group. */
|
||||
export const invitationFilterOptions: readonly { value: InvitationFilter; label: string }[] = [
|
||||
{ value: "all", label: "Все" },
|
||||
{ value: "pending", label: "Ожидают ответа" },
|
||||
{ value: "accepted", label: "Приняты" },
|
||||
{ value: "closed", label: "Закрыты" },
|
||||
{ value: "draft", label: "Черновики" },
|
||||
];
|
||||
|
||||
/** Items of one filter, in the server order. */
|
||||
export function filterInvitations<T extends { state: InvitationState }>(
|
||||
items: readonly T[],
|
||||
filter: InvitationFilter,
|
||||
): T[] {
|
||||
return filter === "all"
|
||||
? [...items]
|
||||
: items.filter((item) => groupOfState[item.state] === filter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tone of the state tag. The tag text always names the state; the tone only
|
||||
* repeats it: a draft is plain, an invitation that waits for the candidate is
|
||||
* accented, an acceptance is a success, and every closed outcome is danger.
|
||||
*/
|
||||
export function invitationStateTone(state: InvitationState): TagTone {
|
||||
switch (state) {
|
||||
case "delivered":
|
||||
case "viewed":
|
||||
case "counter":
|
||||
case "negotiation":
|
||||
return "accent";
|
||||
case "accepted":
|
||||
case "interview_scheduled":
|
||||
case "interviewed":
|
||||
case "terms_agreed":
|
||||
return "success";
|
||||
case "declined":
|
||||
case "expired":
|
||||
case "withdrawn":
|
||||
case "cancelled_by_candidate":
|
||||
case "no_deal":
|
||||
return "danger";
|
||||
case "draft":
|
||||
return "neutral";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Public API of the employer invitations page: the list of the organization's
|
||||
// invitations, drafts included, with the state of each.
|
||||
|
||||
export { EmployerInvitationsPage } from "./ui/employer-invitations-page";
|
||||
@@ -0,0 +1,168 @@
|
||||
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 { ApiRequestError, type ApiErrorCode } from "../../../shared/api";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type {
|
||||
MyOrganizationList,
|
||||
OrganizationInvitationList,
|
||||
Session,
|
||||
} from "../../../shared/api/schemas";
|
||||
import { invitationQueryKeys } from "../../../entities/invitation";
|
||||
import { needQueryKeys } from "../../../entities/need";
|
||||
import { EmployerInvitationsPage } from "./employer-invitations-page";
|
||||
|
||||
const organizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccddee01";
|
||||
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;
|
||||
|
||||
const draft: OrganizationInvitationList["items"][number] = {
|
||||
id: "0199b4f2-7c1e-7d3a-9f00-aabbccdd3301",
|
||||
candidate_handle: `cv1_${"C".repeat(43)}`,
|
||||
need: null,
|
||||
state: "draft",
|
||||
expiry_reason: null,
|
||||
version: 1,
|
||||
terms_version: 1,
|
||||
role_title: "Middle Go-разработчик в команду платежей",
|
||||
salary: {
|
||||
salary_from: 100000,
|
||||
salary_to: 140000,
|
||||
currency: "RUB",
|
||||
period: "month",
|
||||
tax_basis: "net",
|
||||
},
|
||||
response_deadline_at: null,
|
||||
contact_access: { status: "not_granted", fields: [] },
|
||||
created_at: "2026-10-09T10:00:00Z",
|
||||
updated_at: "2026-10-09T10:00:00Z",
|
||||
};
|
||||
|
||||
type Seed =
|
||||
| { kind: "none" }
|
||||
| { kind: "items"; page: OrganizationInvitationList }
|
||||
| { kind: "error"; error: ApiRequestError };
|
||||
|
||||
function render(options: { seed: Seed; role?: "owner" | "recruiter"; path?: string }): string {
|
||||
// A seeded error must stay an error: the server render must not restart the query.
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, retryOnMount: false } },
|
||||
});
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
|
||||
const directory: MyOrganizationList = {
|
||||
items: [
|
||||
{
|
||||
organization: { id: organizationId, name: "Северный ветер", verification_level: "e0" },
|
||||
membership: {
|
||||
organization_id: organizationId,
|
||||
role: options.role ?? "owner",
|
||||
state: "active",
|
||||
joined_at: "2026-09-01T00:00:00Z",
|
||||
},
|
||||
},
|
||||
],
|
||||
page: { has_more: false, next_cursor: null },
|
||||
};
|
||||
queryClient.setQueryData(needQueryKeys.directory(session.account.id), {
|
||||
pages: [directory],
|
||||
pageParams: [undefined],
|
||||
});
|
||||
const key = invitationQueryKeys.list(session.account.id, organizationId);
|
||||
if (options.seed.kind === "items") {
|
||||
queryClient.setQueryData(key, { pages: [options.seed.page], pageParams: [undefined] });
|
||||
} else if (options.seed.kind === "error") {
|
||||
queryClient.getQueryCache().build(queryClient, { queryKey: key }).setState({
|
||||
status: "error",
|
||||
error: options.seed.error,
|
||||
errorUpdateCount: 1,
|
||||
fetchStatus: "idle",
|
||||
});
|
||||
}
|
||||
return renderToString(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={[options.path ?? "/employer/invitations"]}>
|
||||
<EmployerInvitationsPage />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
function problem(status: number, code: ApiErrorCode): ApiRequestError {
|
||||
return new ApiRequestError({ status, code, title: "Problem" });
|
||||
}
|
||||
|
||||
describe("employer invitations page", () => {
|
||||
it("lists the invitations of the first owned organization", () => {
|
||||
const html = render({
|
||||
seed: {
|
||||
kind: "items",
|
||||
page: { items: [draft], page: { has_more: false, next_cursor: null } },
|
||||
},
|
||||
});
|
||||
|
||||
expect(html).toMatch(/<h1[^>]*>Приглашения<\/h1>/);
|
||||
expect(html).toContain("Middle Go-разработчик в команду платежей");
|
||||
expect(html).toContain("Черновик");
|
||||
expect(html).toContain("cv1_CCCCCCCC...");
|
||||
// The full handle is only in the link, never in the text.
|
||||
expect(html.replace(/href="[^"]*"/g, "")).not.toContain(draft.candidate_handle);
|
||||
expect(html).not.toContain("Экран будет реализован");
|
||||
});
|
||||
|
||||
it("asks for the owner role when the account owns no organization", () => {
|
||||
const html = render({ seed: { kind: "none" }, role: "recruiter" });
|
||||
|
||||
expect(html).toContain("Нужны права владельца компании");
|
||||
});
|
||||
|
||||
it("shows a loading state with a skeleton before the first page arrives", () => {
|
||||
const html = render({ seed: { kind: "none" } });
|
||||
|
||||
expect(html).toContain("Загружаем приглашения...");
|
||||
expect(html).toContain('aria-hidden="true"');
|
||||
});
|
||||
|
||||
it("explains an empty list and points to the candidate search", () => {
|
||||
const html = render({
|
||||
seed: { kind: "items", page: { items: [], page: { has_more: false, next_cursor: null } } },
|
||||
});
|
||||
|
||||
expect(html).toContain("Приглашений пока нет");
|
||||
expect(html).toContain(`href="/employer/candidates?organization_id=${organizationId}"`);
|
||||
});
|
||||
|
||||
it("offers a retry when the list cannot be loaded", () => {
|
||||
const html = render({ seed: { kind: "error", error: problem(503, "http_error") } });
|
||||
|
||||
expect(html).toContain('role="alert"');
|
||||
expect(html).toContain("Не удалось загрузить приглашения");
|
||||
expect(html).toContain("Повторить");
|
||||
});
|
||||
|
||||
it("shows a forbidden state, without a retry, when access to the list is refused", () => {
|
||||
const html = render({ seed: { kind: "error", error: problem(403, "forbidden") } });
|
||||
|
||||
expect(html).toContain("Нет доступа");
|
||||
expect(html).not.toContain("Повторить");
|
||||
});
|
||||
|
||||
it("does not show another company's list for an organization the account does not own", () => {
|
||||
const html = render({
|
||||
seed: { kind: "none" },
|
||||
path: "/employer/invitations?organization_id=0199b4f2-7c1e-7d3a-9f00-aabbccddee99",
|
||||
});
|
||||
|
||||
expect(html).toContain("Компания не найдена среди ваших");
|
||||
expect(html).not.toContain("Загружаем приглашения...");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,252 @@
|
||||
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
import {
|
||||
Button,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
ForbiddenState,
|
||||
isAccessDenied,
|
||||
LoadingState,
|
||||
Page,
|
||||
Skeleton,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
invitationQueryKeys,
|
||||
listInvitationsOfOrganization,
|
||||
type InvitationFilter,
|
||||
} from "../../../entities/invitation";
|
||||
import {
|
||||
activeNeedOrganizations,
|
||||
isNeedSessionCurrent,
|
||||
useNeedOrganizationDirectory,
|
||||
type NeedOrganization,
|
||||
} from "../../../entities/need";
|
||||
import { InvitationList } from "./invitation-list";
|
||||
import styles from "./employer-invitations.module.css";
|
||||
|
||||
function isAccessLoss(error: unknown): error is ApiRequestError {
|
||||
return (
|
||||
error instanceof ApiRequestError &&
|
||||
(error.status === 401 || error.status === 403 || error.status === 404)
|
||||
);
|
||||
}
|
||||
|
||||
type WorkspaceProps = {
|
||||
session: Session;
|
||||
organization: NeedOrganization;
|
||||
};
|
||||
|
||||
/** The invitation list of one organization; remounted when the organization changes. */
|
||||
function InvitationWorkspace({ session, organization }: WorkspaceProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [filter, setFilter] = useState<InvitationFilter>("all");
|
||||
const accountId = session.account.id;
|
||||
const organizationId = organization.organization.id;
|
||||
|
||||
const invitations = useInfiniteQuery({
|
||||
queryKey: invitationQueryKeys.list(accountId, organizationId),
|
||||
initialPageParam: undefined as string | undefined,
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
if (!isNeedSessionCurrent(queryClient, session)) {
|
||||
throw new Error("The session changed before the invitation-list request.");
|
||||
}
|
||||
const result = await listInvitationsOfOrganization(organizationId, {
|
||||
cursor: pageParam,
|
||||
signal,
|
||||
});
|
||||
if (!isNeedSessionCurrent(queryClient, session)) {
|
||||
throw new Error("The session changed during the invitation-list request.");
|
||||
}
|
||||
return result;
|
||||
},
|
||||
getNextPageParam: (lastPage) =>
|
||||
lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined,
|
||||
enabled: isNeedSessionCurrent(queryClient, session),
|
||||
gcTime: 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
refetchOnWindowFocus: "always",
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const items = invitations.data?.pages.flatMap((page) => page.items) ?? [];
|
||||
|
||||
if (invitations.isPending) {
|
||||
return (
|
||||
<>
|
||||
<LoadingState label="Загружаем приглашения..." />
|
||||
<Skeleton shape="card" lines={3} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (invitations.isError && items.length === 0) {
|
||||
if (isAccessDenied(invitations.error)) {
|
||||
return <ForbiddenState error={invitations.error} />;
|
||||
}
|
||||
if (isAccessLoss(invitations.error)) {
|
||||
return (
|
||||
<ForbiddenState
|
||||
title="Приглашения компании недоступны"
|
||||
description="Доступ владельца к этой компании не подтвержден. Выберите другую компанию или обновите страницу."
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ErrorState
|
||||
error={invitations.error}
|
||||
title="Не удалось загрузить приглашения"
|
||||
isRetrying={invitations.isFetching}
|
||||
onRetry={() => void invitations.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{invitations.isError ? (
|
||||
<ErrorState
|
||||
error={invitations.error}
|
||||
title="Не удалось обновить список приглашений"
|
||||
isRetrying={invitations.isFetching}
|
||||
onRetry={() => void invitations.refetch()}
|
||||
/>
|
||||
) : null}
|
||||
<InvitationList
|
||||
organizationId={organizationId}
|
||||
items={items}
|
||||
filter={filter}
|
||||
onFilterChange={setFilter}
|
||||
hasMore={invitations.hasNextPage}
|
||||
isFetchingMore={invitations.isFetchingNextPage}
|
||||
onLoadMore={() => void invitations.fetchNextPage()}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The invitations of the organization that the owner works in: drafts and
|
||||
* sent invitations with their state. The organization comes from the address
|
||||
* and falls back to the first one the owner holds; only the owner of an
|
||||
* organization reads its invitations in this version. A candidate appears
|
||||
* only by the opaque handle, because the list holds no name or contact.
|
||||
*/
|
||||
export function EmployerInvitationsPage() {
|
||||
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 requestedOrganizationId = searchParams.get("organization_id");
|
||||
|
||||
const pages = directory.data?.pages;
|
||||
const organizations = useMemo(() => activeNeedOrganizations(pages ?? []), [pages]);
|
||||
const selected =
|
||||
organizations.find((item) => item.organization.id === requestedOrganizationId) ??
|
||||
(requestedOrganizationId ? undefined : organizations[0]);
|
||||
const hasMore = directory.hasNextPage;
|
||||
const fetchNext = directory.fetchNextPage;
|
||||
const fetching = directory.isFetchingNextPage;
|
||||
|
||||
// A requested organization may sit on a later page of the directory.
|
||||
useEffect(() => {
|
||||
if (!directory.data || directory.isError || fetching) return;
|
||||
if (hasMore && (!selected || organizations.length === 0)) void fetchNext();
|
||||
}, [directory.data, directory.isError, fetchNext, fetching, hasMore, organizations, selected]);
|
||||
|
||||
const loading =
|
||||
!sessionQuery.isError &&
|
||||
(!sessionReady || directory.isPending || (hasMore && !selected && !directory.isError));
|
||||
|
||||
return (
|
||||
<Page
|
||||
title="Приглашения"
|
||||
eyebrow="Кабинет работодателя"
|
||||
lead="Черновики и отправленные приглашения вашей компании с их состоянием. Кандидат назван только псевдонимом: имя и контакты здесь не показываются, контакты открываются в приглашении после принятия."
|
||||
width="wide"
|
||||
>
|
||||
{sessionQuery.isError ? (
|
||||
isAccessLoss(sessionQuery.error) ? (
|
||||
<ForbiddenState error={sessionQuery.error} title="Текущий вход не подтвержден" />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={sessionQuery.error}
|
||||
isRetrying={sessionQuery.isFetching}
|
||||
onRetry={() => void sessionQuery.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{directory.isError ? (
|
||||
isAccessLoss(directory.error) ? (
|
||||
<ForbiddenState error={directory.error} />
|
||||
) : (
|
||||
<ErrorState
|
||||
error={directory.error}
|
||||
isRetrying={directory.isFetching}
|
||||
onRetry={() => void directory.refetch()}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
{loading ? (
|
||||
<>
|
||||
<LoadingState label="Проверяем компанию..." />
|
||||
<Skeleton shape="card" lines={3} />
|
||||
</>
|
||||
) : null}
|
||||
{session && sessionReady && directory.data && !directory.isError && !loading ? (
|
||||
<div className={styles.content}>
|
||||
{organizations.length === 0 ? (
|
||||
<ForbiddenState
|
||||
title="Нужны права владельца компании"
|
||||
description="Приглашениями в этой версии управляет только владелец компании."
|
||||
/>
|
||||
) : !selected ? (
|
||||
<EmptyState
|
||||
title="Компания не найдена среди ваших"
|
||||
description="Выберите компанию, где вы владелец."
|
||||
action={
|
||||
<Button variant="secondary" onClick={() => setSearchParams({}, { replace: true })}>
|
||||
Выбрать другую компанию
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{organizations.length > 1 ? (
|
||||
<div className={styles.selector}>
|
||||
<label htmlFor="invitation-organization">Компания</label>
|
||||
<select
|
||||
id="invitation-organization"
|
||||
value={selected.organization.id}
|
||||
onChange={(event) =>
|
||||
setSearchParams({ organization_id: event.currentTarget.value })
|
||||
}
|
||||
>
|
||||
{organizations.map((item) => (
|
||||
<option key={item.organization.id} value={item.organization.id}>
|
||||
{item.organization.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
) : null}
|
||||
<InvitationWorkspace
|
||||
key={`${session.account.id}:${selected.organization.id}`}
|
||||
session={session}
|
||||
organization={selected}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/* Phones come first: one column, and every tap target is at least 44px. */
|
||||
|
||||
.content {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.selector {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: min(100%, 20rem);
|
||||
max-width: 28rem;
|
||||
}
|
||||
|
||||
.selector label {
|
||||
font-size: var(--font-size-s);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.selector select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
min-width: 0;
|
||||
margin-block-end: var(--space-5);
|
||||
}
|
||||
|
||||
.list {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.card {
|
||||
align-content: start;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.card-head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
color: var(--color-text-strong);
|
||||
font-size: var(--font-size-l);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.facts {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.fact {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(7rem, max-content) 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;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-3);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.load-more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-block-start: var(--space-4);
|
||||
}
|
||||
|
||||
@media (width < 30rem) {
|
||||
.fact {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (width >= 64rem) {
|
||||
.list {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { InvitationState } from "../../../shared/api/schemas";
|
||||
import { InvitationList, type InvitationSummary } from "./invitation-list";
|
||||
|
||||
const organizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccddee01";
|
||||
const handleOf = (letter: string) => `cv1_${letter.repeat(43)}`;
|
||||
|
||||
function summaryOf(
|
||||
index: number,
|
||||
state: InvitationState,
|
||||
overrides: Partial<InvitationSummary> = {},
|
||||
): InvitationSummary {
|
||||
return {
|
||||
id: `0199b4f2-7c1e-7d3a-9f00-aabbccdd33${String(index).padStart(2, "0")}`,
|
||||
candidate_handle: handleOf(String.fromCharCode(65 + index)),
|
||||
need: null,
|
||||
state,
|
||||
expiry_reason: state === "expired" ? "invitation_timeout" : null,
|
||||
version: 2,
|
||||
terms_version: 1,
|
||||
role_title: `Роль ${index}`,
|
||||
salary: {
|
||||
salary_from: 100000,
|
||||
salary_to: 140000,
|
||||
currency: "RUB",
|
||||
period: "month",
|
||||
tax_basis: "net",
|
||||
},
|
||||
response_deadline_at: state === "draft" ? null : "2099-10-16T10:00:00Z",
|
||||
contact_access: { status: "not_granted", fields: [] },
|
||||
created_at: "2026-10-09T10:00:00Z",
|
||||
updated_at: "2026-10-09T10:05:00Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function render(
|
||||
items: readonly InvitationSummary[],
|
||||
props: Partial<Parameters<typeof InvitationList>[0]> = {},
|
||||
): string {
|
||||
return renderToStaticMarkup(
|
||||
<MemoryRouter>
|
||||
<InvitationList
|
||||
organizationId={organizationId}
|
||||
items={items}
|
||||
filter="all"
|
||||
onFilterChange={() => undefined}
|
||||
hasMore={false}
|
||||
isFetchingMore={false}
|
||||
onLoadMore={() => undefined}
|
||||
{...props}
|
||||
/>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
const everyState: InvitationState[] = [
|
||||
"draft",
|
||||
"delivered",
|
||||
"viewed",
|
||||
"accepted",
|
||||
"declined",
|
||||
"expired",
|
||||
"withdrawn",
|
||||
];
|
||||
|
||||
function toneOf(html: string, state: string): string | null {
|
||||
const match = html.match(new RegExp(`data-state="${state}"><span[^>]*data-tone="([a-z]+)"`));
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
describe("employer invitation list", () => {
|
||||
it("shows each state as a tag whose tone repeats its meaning", () => {
|
||||
const html = render(everyState.map((state, index) => summaryOf(index, state)));
|
||||
|
||||
expect(toneOf(html, "draft")).toBe("neutral");
|
||||
expect(toneOf(html, "delivered")).toBe("accent");
|
||||
expect(toneOf(html, "viewed")).toBe("accent");
|
||||
expect(toneOf(html, "accepted")).toBe("success");
|
||||
expect(toneOf(html, "declined")).toBe("danger");
|
||||
expect(toneOf(html, "expired")).toBe("danger");
|
||||
expect(toneOf(html, "withdrawn")).toBe("danger");
|
||||
for (const label of [
|
||||
"Черновик",
|
||||
"Доставлено",
|
||||
"Просмотрено кандидатом",
|
||||
"Принято",
|
||||
"Отклонено",
|
||||
"Срок ответа истек",
|
||||
"Отозвано компанией",
|
||||
]) {
|
||||
expect(html).toContain(label);
|
||||
}
|
||||
});
|
||||
|
||||
it("lists one item per invitation with a heading, a shortened handle, salary, and dates", () => {
|
||||
const html = render([summaryOf(1, "delivered")]);
|
||||
|
||||
expect(html.match(/<li[\s>]/g)).toHaveLength(1);
|
||||
expect(html).toMatch(/<h2[^>]*>Приглашения компании<\/h2>/);
|
||||
expect(html).toMatch(/<h3[^>]*>Роль 1<\/h3>/);
|
||||
expect(html).toContain("cv1_BBBBBBBB...");
|
||||
// The full handle is only in the link, never in the text.
|
||||
expect(html.replace(/href="[^"]*"/g, "")).not.toContain(handleOf("B"));
|
||||
expect(html).toMatch(/от 100\s000 ₽ до 140\s000 ₽ в месяц, после налога \(net\)/);
|
||||
expect(html).toContain("Создано");
|
||||
expect(html).toContain("Срок ответа до");
|
||||
expect(html).toMatch(/dateTime="2099-10-16T10:00:00Z"/i);
|
||||
expect(html).toContain("UTC");
|
||||
expect(html).toContain("Прямое приглашение");
|
||||
});
|
||||
|
||||
it("names the need and its requirements version when the invitation comes from one", () => {
|
||||
const html = render([
|
||||
summaryOf(1, "delivered", {
|
||||
need: { need_id: "0199b4f2-7c1e-7d3a-9f00-aabbccdd3401", requirements_version: 3 },
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(html).toContain("Потребность, версия требований 3");
|
||||
});
|
||||
|
||||
it("omits the deadline of a draft and does not claim a change date for it", () => {
|
||||
const html = render([summaryOf(1, "draft")]);
|
||||
|
||||
expect(html).not.toContain("Срок ответа до");
|
||||
expect(html).not.toContain("Изменено");
|
||||
});
|
||||
|
||||
it("links a draft to the form and a sent invitation to its screen, with the same handle", () => {
|
||||
const draft = summaryOf(1, "draft");
|
||||
const sent = summaryOf(2, "delivered");
|
||||
const html = render([draft, sent]);
|
||||
|
||||
for (const item of [draft, sent]) {
|
||||
const query = new URLSearchParams({
|
||||
organization_id: organizationId,
|
||||
candidate_handle: item.candidate_handle,
|
||||
invitation_id: item.id,
|
||||
}).toString();
|
||||
expect(html).toContain(`href="/employer/invitations/new?${query.replaceAll("&", "&")}"`);
|
||||
}
|
||||
expect(html).toMatch(/>Продолжить черновик<span[^>]*>: Роль 1<\/span><\/a>/);
|
||||
expect(html).toMatch(/>Открыть приглашение<span[^>]*>: Роль 2<\/span><\/a>/);
|
||||
});
|
||||
|
||||
it("shows the contact kinds only while the grant is readable, and never a value", () => {
|
||||
const html = render([
|
||||
summaryOf(1, "accepted", {
|
||||
contact_access: { status: "available", fields: ["phone", "email"] },
|
||||
}),
|
||||
summaryOf(2, "accepted", { contact_access: { status: "closed", fields: [] } }),
|
||||
]);
|
||||
|
||||
expect(html).toContain("Доступны: Электронная почта, Телефон");
|
||||
expect(html).toContain("Доступ закрыт");
|
||||
expect(html).toContain("Открыть и прочитать контакты");
|
||||
expect(html).not.toContain("@");
|
||||
});
|
||||
|
||||
it("filters the loaded invitations by group", () => {
|
||||
const items = everyState.map((state, index) => summaryOf(index, state));
|
||||
|
||||
const pending = render(items, { filter: "pending" });
|
||||
expect(pending.match(/<li[\s>]/g)).toHaveLength(2);
|
||||
expect(pending).toContain("Доставлено");
|
||||
expect(pending).not.toContain("Принято");
|
||||
expect(pending).toMatch(/type="radio"[^>]*checked=""[^>]*value="pending"/);
|
||||
|
||||
const closed = render(items, { filter: "closed" });
|
||||
expect(closed.match(/<li[\s>]/g)).toHaveLength(3);
|
||||
expect(closed).not.toContain("Доставлено");
|
||||
|
||||
const drafts = render(items, { filter: "draft" });
|
||||
expect(drafts.match(/<li[\s>]/g)).toHaveLength(1);
|
||||
expect(drafts).toContain("Продолжить черновик");
|
||||
});
|
||||
|
||||
it("offers the same five filters in a fixed order", () => {
|
||||
const html = render([summaryOf(1, "delivered")]);
|
||||
const labels = [
|
||||
...html.matchAll(
|
||||
/<span class="[^"]*">(Все|Ожидают ответа|Приняты|Закрыты|Черновики)<\/span>/g,
|
||||
),
|
||||
].map((match) => match[1]);
|
||||
|
||||
expect(labels).toEqual(["Все", "Ожидают ответа", "Приняты", "Закрыты", "Черновики"]);
|
||||
});
|
||||
|
||||
it("says that a group is empty without hiding the other groups", () => {
|
||||
const html = render([summaryOf(1, "delivered")], { filter: "accepted" });
|
||||
|
||||
expect(html).toContain("В этой группе приглашений нет");
|
||||
expect(html).toContain("Показать все");
|
||||
expect(html).not.toContain("Роль 1");
|
||||
});
|
||||
|
||||
it("does not claim that a group is empty while later pages may hold its items", () => {
|
||||
const html = render([summaryOf(1, "delivered")], { filter: "accepted", hasMore: true });
|
||||
|
||||
expect(html).toContain("Среди загруженных приглашений подходящих нет");
|
||||
expect(html).toContain("Показать еще");
|
||||
});
|
||||
|
||||
it("offers the next page only when the server says there is one", () => {
|
||||
expect(render([summaryOf(1, "delivered")])).not.toContain("Показать еще");
|
||||
expect(render([summaryOf(1, "delivered")], { hasMore: true })).toContain("Показать еще");
|
||||
});
|
||||
|
||||
it("sends an organization without invitations to the candidate search", () => {
|
||||
const html = render([]);
|
||||
|
||||
expect(html).toContain("Приглашений пока нет");
|
||||
expect(html).toContain(`href="/employer/candidates?organization_id=${organizationId}"`);
|
||||
expect(html).toContain("Перейти к кандидатам");
|
||||
expect(html).not.toContain('type="radio"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import type { ReactNode } from "react";
|
||||
import type { OrganizationInvitationList } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
Button,
|
||||
ButtonLink,
|
||||
Card,
|
||||
EmptyState,
|
||||
Mono,
|
||||
SegmentedControl,
|
||||
Section,
|
||||
Tag,
|
||||
VisuallyHidden,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
contactKindLabels,
|
||||
filterInvitations,
|
||||
formatSalaryRange,
|
||||
formatServerMoment,
|
||||
invitationFilterOptions,
|
||||
invitationStateLabels,
|
||||
invitationStateTone,
|
||||
orderedContactKinds,
|
||||
type InvitationFilter,
|
||||
} from "../../../entities/invitation";
|
||||
import { shortHandle } from "../../../entities/match";
|
||||
import styles from "./employer-invitations.module.css";
|
||||
|
||||
export type InvitationSummary = OrganizationInvitationList["items"][number];
|
||||
|
||||
type Fact = { label: string; value: ReactNode };
|
||||
|
||||
function moment(value: string): ReactNode {
|
||||
return <time dateTime={value}>{formatServerMoment(value)}</time>;
|
||||
}
|
||||
|
||||
/** The facts of one summary. No contact value or candidate name exists in it. */
|
||||
function factsOf(item: InvitationSummary): Fact[] {
|
||||
const facts: Fact[] = [
|
||||
{ label: "Кандидат", value: <Mono>{shortHandle(item.candidate_handle)}</Mono> },
|
||||
{ label: "Зарплата", value: formatSalaryRange(item.salary) },
|
||||
{
|
||||
label: "Основание",
|
||||
value: item.need
|
||||
? `Потребность, версия требований ${item.need.requirements_version}`
|
||||
: "Прямое приглашение",
|
||||
},
|
||||
{ label: "Создано", value: moment(item.created_at) },
|
||||
];
|
||||
if (item.state !== "draft") facts.push({ label: "Изменено", value: moment(item.updated_at) });
|
||||
if (item.response_deadline_at) {
|
||||
facts.push({ label: "Срок ответа до", value: moment(item.response_deadline_at) });
|
||||
}
|
||||
if (item.contact_access.status === "available") {
|
||||
const kinds = orderedContactKinds(item.contact_access.fields).map(
|
||||
(kind) => contactKindLabels[kind],
|
||||
);
|
||||
facts.push({ label: "Контакты", value: `Доступны: ${kinds.join(", ")}` });
|
||||
} else if (item.contact_access.status === "closed") {
|
||||
facts.push({ label: "Контакты", value: "Доступ закрыт" });
|
||||
}
|
||||
return facts;
|
||||
}
|
||||
|
||||
function actionLabel(item: InvitationSummary): string {
|
||||
if (item.state === "draft") return "Продолжить черновик";
|
||||
if (item.contact_access.status === "available") return "Открыть и прочитать контакты";
|
||||
return "Открыть приглашение";
|
||||
}
|
||||
|
||||
type InvitationCardProps = {
|
||||
item: InvitationSummary;
|
||||
organizationId: string;
|
||||
};
|
||||
|
||||
/** One invitation. A draft continues in the form; a sent one opens its state screen. */
|
||||
function InvitationCard({ item, organizationId }: InvitationCardProps) {
|
||||
return (
|
||||
<Card as="li" className={styles.card}>
|
||||
<div className={styles["card-head"]}>
|
||||
<h3 className={styles["card-title"]}>{item.role_title}</h3>
|
||||
<span data-state={item.state}>
|
||||
<Tag tone={invitationStateTone(item.state)}>{invitationStateLabels[item.state]}</Tag>
|
||||
</span>
|
||||
</div>
|
||||
<dl className={styles.facts}>
|
||||
{factsOf(item).map((fact) => (
|
||||
<div key={fact.label} className={styles.fact}>
|
||||
<dt>{fact.label}</dt>
|
||||
<dd>{fact.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<div className={styles.actions}>
|
||||
<ButtonLink
|
||||
variant={item.state === "draft" ? "primary" : "secondary"}
|
||||
to={paths.employer.invitation({
|
||||
organizationId,
|
||||
invitationId: item.id,
|
||||
candidateHandle: item.candidate_handle,
|
||||
})}
|
||||
>
|
||||
{actionLabel(item)}
|
||||
<VisuallyHidden>{`: ${item.role_title}`}</VisuallyHidden>
|
||||
</ButtonLink>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
type InvitationListProps = {
|
||||
organizationId: string;
|
||||
/** Every loaded invitation of the organization, newest first. */
|
||||
items: readonly InvitationSummary[];
|
||||
filter: InvitationFilter;
|
||||
onFilterChange: (filter: InvitationFilter) => void;
|
||||
hasMore: boolean;
|
||||
isFetchingMore: boolean;
|
||||
onLoadMore: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The invitations of one organization with a client-side filter by state
|
||||
* group. The API has no state filter yet, so the filter only hides loaded
|
||||
* items and never claims that the other pages hold none.
|
||||
*/
|
||||
export function InvitationList({
|
||||
organizationId,
|
||||
items,
|
||||
filter,
|
||||
onFilterChange,
|
||||
hasMore,
|
||||
isFetchingMore,
|
||||
onLoadMore,
|
||||
}: InvitationListProps) {
|
||||
const candidatesLink = `${paths.employer.candidates}?organization_id=${encodeURIComponent(organizationId)}`;
|
||||
|
||||
if (items.length === 0 && !hasMore) {
|
||||
return (
|
||||
<EmptyState
|
||||
title="Приглашений пока нет"
|
||||
description="Найдите кандидата в разделе «Кандидаты» и отправьте первое приглашение: черновики и отправленные приглашения появятся здесь."
|
||||
action={<ButtonLink to={candidatesLink}>Перейти к кандидатам</ButtonLink>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const shown = filterInvitations(items, filter);
|
||||
|
||||
return (
|
||||
<Section title="Приглашения компании">
|
||||
<div className={styles.toolbar}>
|
||||
<SegmentedControl
|
||||
legend="Показать приглашения"
|
||||
name="invitation-filter"
|
||||
options={invitationFilterOptions}
|
||||
value={filter}
|
||||
onChange={onFilterChange}
|
||||
/>
|
||||
</div>
|
||||
{shown.length > 0 ? (
|
||||
<ul className={styles.list}>
|
||||
{shown.map((item) => (
|
||||
<InvitationCard key={item.id} item={item} organizationId={organizationId} />
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<EmptyState
|
||||
title="В этой группе приглашений нет"
|
||||
description={
|
||||
hasMore
|
||||
? "Среди загруженных приглашений подходящих нет. Загрузите следующие или выберите другую группу."
|
||||
: "Выберите другую группу, чтобы увидеть остальные приглашения."
|
||||
}
|
||||
action={
|
||||
filter === "all" ? null : (
|
||||
<Button variant="secondary" onClick={() => onFilterChange("all")}>
|
||||
Показать все
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{hasMore ? (
|
||||
<div className={styles["load-more"]}>
|
||||
<Button variant="secondary" isBusy={isFetchingMore} onClick={onLoadMore}>
|
||||
{isFetchingMore ? "Загружаем..." : "Показать еще"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
@@ -31,12 +31,12 @@ import {
|
||||
Page,
|
||||
StatusView,
|
||||
Tag,
|
||||
type TagTone,
|
||||
} from "../../../shared/ui";
|
||||
import {
|
||||
formatServerMoment,
|
||||
invitationQueryKeys,
|
||||
invitationStateLabels,
|
||||
invitationStateTone,
|
||||
readOrganizationInvitation,
|
||||
salaryFitLabels,
|
||||
} from "../../../entities/invitation";
|
||||
@@ -73,28 +73,6 @@ function specializationOf(value: string | null): SpecializationCode | "" {
|
||||
|
||||
type OrganizationQuery = UseQueryResult<Organization, ApiRequestError>;
|
||||
|
||||
/** Tone of the state tag: pending and neutral states are plain, outcomes carry color. */
|
||||
function stateTone(state: OrganizationInvitation["state"]): TagTone {
|
||||
switch (state) {
|
||||
case "accepted":
|
||||
case "interview_scheduled":
|
||||
case "interviewed":
|
||||
case "terms_agreed":
|
||||
return "success";
|
||||
case "declined":
|
||||
case "expired":
|
||||
case "withdrawn":
|
||||
case "cancelled_by_candidate":
|
||||
case "no_deal":
|
||||
return "danger";
|
||||
case "counter":
|
||||
case "negotiation":
|
||||
return "accent";
|
||||
default:
|
||||
return "neutral";
|
||||
}
|
||||
}
|
||||
|
||||
/** What the preview shows while the company card is not available. */
|
||||
function cardFallbackOf(organization: OrganizationQuery) {
|
||||
if (organization.isPending) return <LoadingState label="Загружаем карточку компании..." />;
|
||||
@@ -145,7 +123,9 @@ function SentInvitation({
|
||||
: "Приглашение уже отправлено"}
|
||||
</h2>
|
||||
<span data-state={invitation.state}>
|
||||
<Tag tone={stateTone(invitation.state)}>{invitationStateLabels[invitation.state]}</Tag>
|
||||
<Tag tone={invitationStateTone(invitation.state)}>
|
||||
{invitationStateLabels[invitation.state]}
|
||||
</Tag>
|
||||
</span>
|
||||
</div>
|
||||
<dl className={styles.summary}>
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
export { PlaceholderPage } from "./ui/placeholder-page";
|
||||
export type { ScreenId } from "./model/screens";
|
||||
@@ -1,124 +0,0 @@
|
||||
/**
|
||||
* Screen map from the product requirements. Each entry is a placeholder
|
||||
* until its business task implements the real screen; the "planned" lines
|
||||
* describe intent, not implemented behavior.
|
||||
*/
|
||||
export type ScreenArea = "public" | "candidate" | "employer";
|
||||
|
||||
export type ScreenPlan = {
|
||||
area: ScreenArea;
|
||||
title: string;
|
||||
planned: readonly string[];
|
||||
};
|
||||
|
||||
export const areaLabels: Readonly<Record<ScreenArea, string>> = {
|
||||
public: "Публичный раздел",
|
||||
candidate: "Кабинет кандидата",
|
||||
employer: "Кабинет работодателя",
|
||||
};
|
||||
|
||||
export const screens = {
|
||||
login: {
|
||||
area: "public",
|
||||
title: "Вход",
|
||||
planned: ["Вход по почте и паролю", "Восстановление доступа", "Переход в кабинет по роли"],
|
||||
},
|
||||
register: {
|
||||
area: "public",
|
||||
title: "Регистрация",
|
||||
planned: [
|
||||
"Выбор сценария: кандидат или работодатель",
|
||||
"Согласие на обработку персональных данных",
|
||||
"Письмо для подтверждения почты",
|
||||
],
|
||||
},
|
||||
verifyEmail: {
|
||||
area: "public",
|
||||
title: "Подтверждение почты",
|
||||
planned: [
|
||||
"Проверка ссылки из письма",
|
||||
"Повторная отправка письма",
|
||||
"Понятное сообщение об устаревшей ссылке",
|
||||
],
|
||||
},
|
||||
support: {
|
||||
area: "public",
|
||||
title: "Поддержка",
|
||||
planned: [
|
||||
"Контакты поддержки",
|
||||
"Ответы на частые вопросы",
|
||||
"Как передать идентификатор запроса при ошибке",
|
||||
],
|
||||
},
|
||||
candidateHome: {
|
||||
area: "candidate",
|
||||
title: "Главная",
|
||||
planned: [
|
||||
"Текущая категория и подтвержденный грейд",
|
||||
"Следующий шаг по профилю",
|
||||
"Новые приглашения",
|
||||
],
|
||||
},
|
||||
candidateOnboarding: {
|
||||
area: "candidate",
|
||||
title: "Первые шаги",
|
||||
planned: [
|
||||
"Согласия и видимость профиля",
|
||||
"Анкета и ожидаемый грейд",
|
||||
"Переход к первому тесту",
|
||||
],
|
||||
},
|
||||
candidateProfile: {
|
||||
area: "candidate",
|
||||
title: "Профиль",
|
||||
planned: [
|
||||
"Специальность и навыки",
|
||||
"Резюме и достижения ФСП",
|
||||
"Контакты, скрытые от компаний до приглашения",
|
||||
],
|
||||
},
|
||||
candidateAssessment: {
|
||||
area: "candidate",
|
||||
title: "Тест",
|
||||
planned: ["Выбор уровня теста", "Прохождение заданий", "Сохранение ответов"],
|
||||
},
|
||||
candidateResults: {
|
||||
area: "candidate",
|
||||
title: "Результаты",
|
||||
planned: [
|
||||
"Подтвержденная категория",
|
||||
"История попыток и грейдов",
|
||||
"Разбор результата по компетенциям",
|
||||
],
|
||||
},
|
||||
candidatePrivacy: {
|
||||
area: "candidate",
|
||||
title: "Приватность",
|
||||
planned: ["Видимость профиля в поиске", "Отзыв согласий", "Журнал доступа к контактам"],
|
||||
},
|
||||
employerCompany: {
|
||||
area: "employer",
|
||||
title: "Компания и команда",
|
||||
planned: ["Профиль компании", "Участники и их роли", "Приглашение коллег"],
|
||||
},
|
||||
employerNeeds: {
|
||||
area: "employer",
|
||||
title: "Потребности",
|
||||
planned: [
|
||||
"Описание потребности",
|
||||
"Подтверждение извлеченных навыков",
|
||||
"Фильтры поиска кандидатов",
|
||||
],
|
||||
},
|
||||
employerInvitations: {
|
||||
area: "employer",
|
||||
title: "Приглашения",
|
||||
planned: [
|
||||
"Отправленные предложения",
|
||||
"Статусы: отправлено, просмотрено, принято, отклонено",
|
||||
"Доступ к контактам после принятия",
|
||||
],
|
||||
},
|
||||
} as const satisfies Record<string, ScreenPlan>;
|
||||
|
||||
export type ScreenId = keyof typeof screens;
|
||||
@@ -1,11 +0,0 @@
|
||||
.plan {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
margin: 0;
|
||||
padding-inline-start: var(--space-5);
|
||||
line-height: var(--line-height-snug);
|
||||
}
|
||||
|
||||
.plan li::marker {
|
||||
color: var(--color-accent);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { Card, Notice, Page, Section, Tag } from "../../../shared/ui";
|
||||
import { areaLabels, screens, type ScreenId } from "../model/screens";
|
||||
import styles from "./placeholder-page.module.css";
|
||||
|
||||
type PlaceholderPageProps = {
|
||||
screen: ScreenId;
|
||||
};
|
||||
|
||||
/**
|
||||
* Honest stand-in for a screen that a later task implements. It names the
|
||||
* screen and lists what is planned, without imitating working features. The
|
||||
* planned items are not a sequence, so they are a plain list.
|
||||
*/
|
||||
export function PlaceholderPage({ screen }: PlaceholderPageProps) {
|
||||
const plan = screens[screen];
|
||||
|
||||
return (
|
||||
<Page
|
||||
title={plan.title}
|
||||
eyebrow={areaLabels[plan.area]}
|
||||
width={plan.area === "employer" ? "wide" : "narrow"}
|
||||
>
|
||||
<Notice tone="neutral" title={<Tag>Заготовка</Tag>}>
|
||||
Экран будет реализован в одной из следующих задач. Сейчас здесь нет данных и действий.
|
||||
</Notice>
|
||||
<Section title="Что здесь появится" headingLevel={2}>
|
||||
<Card as="div">
|
||||
<ul className={styles.plan}>
|
||||
{plan.planned.map((item) => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
</Card>
|
||||
</Section>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -48,6 +48,24 @@ export const paths = {
|
||||
`/employer/candidates?organization_id=${encodeURIComponent(organizationId)}&need_id=${encodeURIComponent(needId)}`,
|
||||
invitations: "/employer/invitations",
|
||||
invitationNew: "/employer/invitations/new",
|
||||
/**
|
||||
* Opens one invitation of the organization in the invitation screen: a
|
||||
* draft continues in the form, a sent one shows its state, deadline, and
|
||||
* the contacts after an acceptance. The handle is the organization-scoped
|
||||
* alias, never a candidate identifier.
|
||||
*/
|
||||
invitation: (input: {
|
||||
organizationId: string;
|
||||
invitationId: string;
|
||||
candidateHandle: string;
|
||||
}) => {
|
||||
const query = new URLSearchParams({
|
||||
organization_id: input.organizationId,
|
||||
candidate_handle: input.candidateHandle,
|
||||
invitation_id: input.invitationId,
|
||||
});
|
||||
return `/employer/invitations/new?${query.toString()}`;
|
||||
},
|
||||
/**
|
||||
* Opens the invitation form for one search result. The handle is the
|
||||
* organization-scoped alias from the search, never a candidate identifier.
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
.label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 2.5rem;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-2) var(--space-4);
|
||||
border-radius: var(--radius-pill);
|
||||
color: var(--color-text-secondary);
|
||||
|
||||
Reference in new issue
Block a user