diff --git a/frontend/README.en.md b/frontend/README.en.md index fbe4770..b5c14c3 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -2,10 +2,10 @@ [Русский](README.md) | English -A React and TypeScript SPA built with Vite and organized using FSD. Registration, email confirmation, sign-in, consent settings, the candidate profile and questionnaire, candidate assessment, company profiles, employer needs, and support cases use the API. A manual assessment request creates a support case and displays its current state; the screen does not present it as an assessment result. The result history and result page use the API. Candidate search, the employer's read of an anonymous card, and sending an invitation from a search result use the API. The candidate reads incoming invitations, accepts them with a choice of contacts, and declines them; the company's invitation list remains a placeholder. +A React and TypeScript SPA built with Vite and organized using FSD. Registration, email confirmation, sign-in, consent settings, the candidate profile and questionnaire, candidate assessment, company profiles, employer needs, and support cases use the API. A manual assessment request creates a support case and displays its current state; the screen does not present it as an assessment result. The result history and result page use the API. Candidate search, the employer's read of an anonymous card, and sending an invitation from a search result use the API. The candidate reads incoming invitations, accepts them with a choice of contacts, and declines them. The owner of a company sees the list of its invitations with their states. - `src/app/` starts the application: the route tree (`router/`), the query client (`providers/`), global styles, and the route error page. -- `src/pages/` holds public pages, sign-in and registration, candidate profile and questionnaire, assessment results, company and employer needs pages, candidate search, the invitation to a candidate, the candidate's incoming invitations, support cases, technical status, and remaining placeholders. +- `src/pages/` holds public pages, sign-in and registration, candidate profile and questionnaire, assessment results, company and employer needs pages, candidate search, the invitation to a candidate, the company's invitation list, the candidate's incoming invitations, support cases, and technical status. - `src/widgets/` holds shells: `public-shell`, `candidate-shell`, `employer-shell`, the result history widget `assessment-history`, the search result widget `match-list`, the invitation preview `invitation-preview`, and the technical `system-status` widget. - `src/entities/` holds entity models, including `need` (see [Need entity](#need-entity)), `company`, and `invitation`; `src/features/` holds user actions and forms. - `src/shared/ui/` holds design tokens, fonts, the wordmark, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks. @@ -17,11 +17,11 @@ From the repository root, `make -C frontend dev` starts development and `make -C ## Routes -| Group | Paths | Shell | -| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | -| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | -| Candidate | `/candidate` with `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `invitations/:invitationId`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, and `support/cases/:caseId` | `CandidateShell` | -| Employer | `/employer` redirects to `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/candidates`, `/employer/invitations/new`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` | +| Group | Paths | Shell | +| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | +| Public | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | +| Candidate | `/candidate` with `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `invitations/:invitationId`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, and `support/cases/:caseId` | `CandidateShell` | +| Employer | `/employer` redirects to `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/candidates`, `/employer/invitations`, `/employer/invitations/new`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` | Each group has its own not-found page. Paths are defined once in `shared/config/paths.ts`. The router uses React Router data APIs (`createBrowserRouter`): a route-level error boundary, loader redirects, and later `lazy` code splitting for cabinets. Loaders do not fetch data; server data belongs to TanStack Query. Cabinet boundaries read the current session and direct guests to sign-in. `/support` sends a signed-in user to the support area for their account or to sign-in. Need pages pass `organization_id` in the query string, but the client checks the current owner directory and the server authorizes every request. @@ -161,6 +161,18 @@ Checks. Unit tests cover parsing and labels (`entities/match`), the request buil Checks. Unit tests cover the range rules (`entities/invitation`), draft validation and pointer mapping, the send command over MSW (keys, a retry after a lost create and a lost send response, 400 with fields, a draft update, 412), and the preview and page markup (owner access, an empty address). The Playwright suite `e2e/invitation-compose.spec.ts` runs on the real backend in `make -C deploy test-e2e-registration`: five synthetic candidates publish the same card, the owner finds them with a search, opens the invitation from the result, fills [100000; 140000] net and a package step by step, and checks the preview against every term; without the communication method the form does not leave the terms step, a field error shows, no request is sent, and the candidates' inboxes stay empty. Then the send is slowed down and its first response lost, a second click during the request starts nothing, and the retry uses the same key; the result is one invitation in one inbox (`GET /me/invitations`) with the deadline the screen shows, also after a reload. A 403 for a recruiter is not checked in the browser, since the stand cannot grant that role; the screen for a non-owner role is covered by a unit test. +## Company invitations + +`/employer/invitations` (`pages/employer-invitations`) shows the company's invitations from `GET /organizations/{org_id}/invitations`: drafts and sent ones, newest first, in cursor pages ("Показать еще"). The company comes from `organization_id` in the address, otherwise the first company where the account is the owner; with several companies a picker sits above the list. Owner rights are checked against the current organization directory, and other roles are refused. + +- Row. The heading is the role title; the state tag names the state in words and its tone repeats the meaning (draft is neutral, waiting for an answer is accented, accepted is a success, declined, expired, and withdrawn are danger). Below: the candidate only as the shortened alias (`entities/match/model/views.ts`), the salary range, the basis (a need with its requirements version or a direct invitation), the creation and last change dates, the response deadline, and the contact access (the contact kinds while `available`, "Доступ закрыт" while `closed`). The list response holds no name or contact value, and the screen shows none. +- Dates. The list summary has no delivery moment, so the screen shows creation and the last change, both in UTC through `formatServerMoment`. +- Filter. A `SegmentedControl` with "Все", "Ожидают ответа", "Приняты", "Закрыты", and "Черновики" works on the client over the loaded pages, because the API has no state filter yet (`entities/invitation/model/list-groups.ts`: every state of the contract belongs to exactly one group). When no loaded item is in a group but more pages remain, the screen does not claim the group is empty and offers to load the next pages. +- Links. A draft and a sent invitation open the same route `/employer/invitations/new` with `organization_id`, `candidate_handle`, and `invitation_id`: for a draft it opens the form with the saved terms, for a sent one the state, the deadline, the terms, and, after an acceptance, the contacts. The company has no separate invitation page. +- States. Loading (message and skeleton), an empty list with a link to "Кандидаты", an error with retry, a 401/403 or 404 refusal without retry, and a refresh error above an already loaded list. + +Checks. Unit tests: state groups and tones, the list adapter on MSW (page size, cursor, contract check, a 403 refusal), the list markup (every state with its tone, the filter, empty states, draft and sent links, no contact values), and the page (loading, empty, error with retry, refusal, another company). The Playwright spec `e2e/acceptance-path.spec.ts` opens the owner's screen after three invitations are sent and checks three delivered invitations without candidate contacts. + ## Candidate incoming invitations `/candidate/invitations` (`pages/candidate-invitations`) shows the incoming invitations: a cursor-paged list from `GET /me/invitations`, newest first, which records no view. `/candidate/invitations/:invitationId` opens one invitation. The contract is in the [API](../api/README.en.md#invitations-and-contact-grants). diff --git a/frontend/README.md b/frontend/README.md index 6952d5a..713d9d6 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -2,10 +2,10 @@ Русский | [English](README.en.md) -SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, профиль и анкета кандидата, проверка кандидата, профиль компании, потребности работодателя и обращения в поддержку работают с API. Запрос ручной оценки создает обращение и показывает его текущее состояние; экран не подменяет его результатом автоматической оценки. История и страница результатов проверок работают с API. Подбор кандидатов, чтение анонимной карточки работодателем и отправка приглашения из выдачи работают с API. Кандидат читает входящие приглашения, принимает их с выбором контактов и отклоняет; список приглашений компании остается заготовкой. +SPA на React и TypeScript со сборкой Vite и структурой FSD. Регистрация, подтверждение почты, вход, настройки согласий, профиль и анкета кандидата, проверка кандидата, профиль компании, потребности работодателя и обращения в поддержку работают с API. Запрос ручной оценки создает обращение и показывает его текущее состояние; экран не подменяет его результатом автоматической оценки. История и страница результатов проверок работают с API. Подбор кандидатов, чтение анонимной карточки работодателем и отправка приглашения из выдачи работают с API. Кандидат читает входящие приглашения, принимает их с выбором контактов и отклоняет. Владелец компании видит список ее приглашений с состояниями. - `src/app/` - запуск приложения: дерево маршрутов (`router/`), клиент запросов (`providers/`), глобальные стили и страница ошибки маршрута. -- `src/pages/` - публичные страницы, вход и регистрация, профиль и анкета кандидата, результаты проверок, компания и потребности работодателя, подбор кандидатов, приглашение кандидату, входящие приглашения кандидата, обращения в поддержку, технический статус и оставшиеся заготовки экранов. +- `src/pages/` - публичные страницы, вход и регистрация, профиль и анкета кандидата, результаты проверок, компания и потребности работодателя, подбор кандидатов, приглашение кандидату, список приглашений компании, входящие приглашения кандидата, обращения в поддержку и технический статус. - `src/widgets/` - оболочки: `public-shell`, `candidate-shell`, `employer-shell`, виджет истории результатов `assessment-history`, виджет выдачи подбора `match-list`, предпросмотр приглашения `invitation-preview` и технический виджет `system-status`. - `src/entities/` - модели сущностей, в том числе `need` (см. [сущность потребности](#сущность-потребности)), `company` и `invitation`; `src/features/` - действия пользователя и формы. - `src/shared/ui/` - токены дизайна, шрифты, словесный знак и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками. @@ -17,11 +17,11 @@ SPA на React и TypeScript со сборкой Vite и структурой FS ## Маршруты -| Группа | Пути | Оболочка | -| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | -| Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | -| Кандидат | `/candidate` с `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `invitations/:invitationId`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, `support/cases/:caseId` | `CandidateShell` | -| Работодатель | `/employer` перенаправляет на `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/candidates`, `/employer/invitations/new`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` | +| Группа | Пути | Оболочка | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- | +| Публичная | `/`, `/login`, `/register`, `/verify-email`, `/support`, `/status` | `PublicShell` | +| Кандидат | `/candidate` с `onboarding`, `profile`, `questionnaire`, `assessment`, `results`, `results/:attemptId`, `invitations`, `invitations/:invitationId`, `privacy`, `support/cases`, `support/cases/new`, `support/cases/manual-assessment`, `support/cases/:caseId` | `CandidateShell` | +| Работодатель | `/employer` перенаправляет на `/employer/company`; `/employer/company`, `/employer/needs`, `/employer/needs/new`, `/employer/needs/:needId`, `/employer/candidates`, `/employer/invitations`, `/employer/invitations/new`, `/employer/support/cases`, `/employer/support/cases/new`, `/employer/support/cases/:caseId` | `EmployerShell` | У каждой группы своя страница "не найдено". Пути заданы один раз в `shared/config/paths.ts`. Роутер использует data API React Router (`createBrowserRouter`): граница ошибок на уровне маршрута, перенаправления через loader и в будущем разделение кода кабинетов через `lazy`. Loader не загружает данные: серверные данные принадлежат TanStack Query. Границы кабинетов читают текущую сессию и направляют гостя на вход. `/support` ведет пользователя к обращениям его кабинета или к входу. Страницы потребностей передают `organization_id` в query string, но право владельца каждый раз подтверждают по актуальному списку компаний и на сервере. @@ -161,6 +161,18 @@ SPA на React и TypeScript со сборкой Vite и структурой FS Проверки. Модульные тесты: правила вилки (`entities/invitation`), проверка черновика и перевод указателей ошибок, команда отправки на MSW (ключи, повтор после потерянного ответа создания и отправки, 400 с полями, обновление черновика, 412), разметка предпросмотра и страницы (доступ владельца, пустой адрес). Playwright `e2e/invitation-compose.spec.ts` работает на реальном бэкенде в `make -C deploy test-e2e-registration`: пять синтетических кандидатов публикуют одинаковую карточку, владелец находит их поиском, открывает приглашение из выдачи, заполняет [100000; 140000] net и пакет по шагам и сверяет предпросмотр со всеми условиями; без способа связи форма не уходит с шага условий, видна ошибка поля, запросов нет, inbox кандидатов пуст. Затем отправка замедляется, первый ответ теряется, второе нажатие во время запроса ничего не запускает, повтор идет с тем же ключом; в итоге одно приглашение в одном inbox (`GET /me/invitations`) с тем же сроком, что на экране и после перезагрузки. Отказ 403 для рекрутера в браузере не проверен: на стенде нет способа выдать такую роль; поведение экрана для неглавной роли покрыто модульным тестом. +## Приглашения компании + +`/employer/invitations` (`pages/employer-invitations`) показывает приглашения компании из `GET /organizations/{org_id}/invitations`: черновики и отправленные, новые сверху, страницами по курсору ("Показать еще"). Компания берется из `organization_id` адреса, иначе первая компания, где аккаунт владелец; при нескольких компаниях выбор виден над списком. Право владельца подтверждается по актуальному списку компаний, остальные роли получают отказ. + +- Строка. Заголовок - название роли; тег состояния называет состояние словами, а тон повторяет смысл (черновик - нейтральный, ждет ответа - акцентный, принято - успех, отклонено, истекло и отозвано - опасность). Ниже: кандидат только сокращенным псевдонимом (`entities/match/model/views.ts`), вилка зарплаты, основание (потребность с версией требований или прямое приглашение), даты создания и изменения, срок ответа и доступ к контактам (виды контактов при `available`, "Доступ закрыт" при `closed`). Ни имени, ни значения контакта в ответе списка нет и на экране нет. +- Даты. В сводке списка нет момента доставки, поэтому показаны создание и последнее изменение, оба в UTC через `formatServerMoment`. +- Фильтр. `SegmentedControl` "Все", "Ожидают ответа", "Приняты", "Закрыты" и "Черновики" работает на клиенте по загруженным страницам, потому что фильтра по состоянию в API пока нет (`entities/invitation/model/list-groups.ts`: каждое состояние контракта входит ровно в одну группу). Если в группе нет загруженных записей, а страницы остались, экран не утверждает, что группа пуста, а предлагает загрузить следующие. +- Ссылки. Черновик и отправленное приглашение ведут на один маршрут `/employer/invitations/new` с `organization_id`, `candidate_handle` и `invitation_id`: для черновика он открывает форму с сохраненными условиями, для отправленного - состояние, срок, условия и, после принятия, контакты. Отдельной страницы приглашения у компании нет. +- Состояния. Загрузка (сообщение и скелетон), пустой список со ссылкой на "Кандидаты", ошибка с повтором, отказ 401/403 и 404 без повтора, ошибка обновления над уже загруженным списком. + +Проверки. Модульные тесты: группы и тоны состояний, адаптер списка на MSW (размер страницы, курсор, проверка ответа схемой, отказ 403), разметка списка (каждое состояние с тоном, фильтр, пустые состояния, ссылки черновика и отправленного, отсутствие значений контактов) и страницы (загрузка, пусто, ошибка с повтором, отказ, чужая компания). Playwright `e2e/acceptance-path.spec.ts` после отправки трех приглашений открывает экран владельца и сверяет три доставленных приглашения без контактов кандидатов. + ## Входящие приглашения кандидата `/candidate/invitations` (`pages/candidate-invitations`) показывает входящие приглашения: список по курсору из `GET /me/invitations`, новые сверху, без записи просмотра. `/candidate/invitations/:invitationId` открывает одно приглашение. Контракт описан в [API](../api/README.md#приглашения-и-контактные-разрешения). diff --git a/frontend/e2e/acceptance-path.spec.ts b/frontend/e2e/acceptance-path.spec.ts index 06ee485..45159a1 100644 --- a/frontend/e2e/acceptance-path.spec.ts +++ b/frontend/e2e/acceptance-path.spec.ts @@ -679,6 +679,18 @@ test.describe("minimal path from registration to disclosed contacts on the real expect(listText).not.toContain(secret); } } + // The owner's screen lists the same three invitations, delivered, and + // shows a candidate only by the shortened handle. + await page.goto(`/employer/invitations?organization_id=${organizationId}`); + await expect(page.getByRole("heading", { level: 1, name: "Приглашения" })).toBeVisible(); + const cards = page.getByRole("listitem").filter({ hasText: "Доставлено" }); + await expect(cards).toHaveCount(3); + const screenText = await page.getByRole("main").innerText(); + for (const candidate of candidates) { + for (const secret of [candidate.email, candidate.phone, candidate.fullName]) { + expect(screenText).not.toContain(secret); + } + } }); const [accepting, racing, declining] = [...invitationOf.entries()]; diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx index a6381d5..d11e28e 100644 --- a/frontend/src/app/router/routes.test.tsx +++ b/frontend/src/app/router/routes.test.tsx @@ -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>/); + 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 () => { diff --git a/frontend/src/app/router/routes.tsx b/frontend/src/app/router/routes.tsx index 537b01d..0e03a9a 100644 --- a/frontend/src/app/router/routes.tsx +++ b/frontend/src/app/router/routes.tsx @@ -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: , }, { path: paths.employer.candidates, element: }, - { - path: paths.employer.invitations, - element: , - }, + { path: paths.employer.invitations, element: }, { path: paths.employer.invitationNew, element: }, { path: paths.employer.notifications, element: }, { diff --git a/frontend/src/entities/invitation/api/organization-invitations.test.ts b/frontend/src/entities/invitation/api/organization-invitations.test.ts new file mode 100644 index 0000000..8abd250 --- /dev/null +++ b/frontend/src/entities/invitation/api/organization-invitations.test.ts @@ -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); + }); +}); diff --git a/frontend/src/entities/invitation/api/organization-invitations.ts b/frontend/src/entities/invitation/api/organization-invitations.ts index 9fdd270..236a324 100644 --- a/frontend/src/entities/invitation/api/organization-invitations.ts +++ b/frontend/src/entities/invitation/api/organization-invitations.ts @@ -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 { + 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) => diff --git a/frontend/src/entities/invitation/index.ts b/frontend/src/entities/invitation/index.ts index ab0fdd1..83cc6ed 100644 --- a/frontend/src/entities/invitation/index.ts +++ b/frontend/src/entities/invitation/index.ts @@ -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, diff --git a/frontend/src/entities/invitation/model/list-groups.test.ts b/frontend/src/entities/invitation/model/list-groups.test.ts new file mode 100644 index 0000000..f73c27d --- /dev/null +++ b/frontend/src/entities/invitation/model/list-groups.test.ts @@ -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"); + }); +}); diff --git a/frontend/src/entities/invitation/model/list-groups.ts b/frontend/src/entities/invitation/model/list-groups.ts new file mode 100644 index 0000000..220191b --- /dev/null +++ b/frontend/src/entities/invitation/model/list-groups.ts @@ -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> = { + 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( + 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"; + } +} diff --git a/frontend/src/pages/employer-invitations/index.ts b/frontend/src/pages/employer-invitations/index.ts new file mode 100644 index 0000000..3d01d10 --- /dev/null +++ b/frontend/src/pages/employer-invitations/index.ts @@ -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"; diff --git a/frontend/src/pages/employer-invitations/ui/employer-invitations-page.test.tsx b/frontend/src/pages/employer-invitations/ui/employer-invitations-page.test.tsx new file mode 100644 index 0000000..d83d621 --- /dev/null +++ b/frontend/src/pages/employer-invitations/ui/employer-invitations-page.test.tsx @@ -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( + + + + + , + ); +} + +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>/); + 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("Загружаем приглашения..."); + }); +}); diff --git a/frontend/src/pages/employer-invitations/ui/employer-invitations-page.tsx b/frontend/src/pages/employer-invitations/ui/employer-invitations-page.tsx new file mode 100644 index 0000000..b1c22ad --- /dev/null +++ b/frontend/src/pages/employer-invitations/ui/employer-invitations-page.tsx @@ -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("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 ( + <> + + + + ); + } + + if (invitations.isError && items.length === 0) { + if (isAccessDenied(invitations.error)) { + return ; + } + if (isAccessLoss(invitations.error)) { + return ( + + ); + } + return ( + void invitations.refetch()} + /> + ); + } + + return ( + <> + {invitations.isError ? ( + void invitations.refetch()} + /> + ) : null} + 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 ( + + {sessionQuery.isError ? ( + isAccessLoss(sessionQuery.error) ? ( + + ) : ( + void sessionQuery.refetch()} + /> + ) + ) : null} + {directory.isError ? ( + isAccessLoss(directory.error) ? ( + + ) : ( + void directory.refetch()} + /> + ) + ) : null} + {loading ? ( + <> + + + + ) : null} + {session && sessionReady && directory.data && !directory.isError && !loading ? ( +
+ {organizations.length === 0 ? ( + + ) : !selected ? ( + setSearchParams({}, { replace: true })}> + Выбрать другую компанию + + } + /> + ) : ( + <> + {organizations.length > 1 ? ( +
+ + +
+ ) : null} + + + )} +
+ ) : null} +
+ ); +} diff --git a/frontend/src/pages/employer-invitations/ui/employer-invitations.module.css b/frontend/src/pages/employer-invitations/ui/employer-invitations.module.css new file mode 100644 index 0000000..dde43a1 --- /dev/null +++ b/frontend/src/pages/employer-invitations/ui/employer-invitations.module.css @@ -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)); + } +} diff --git a/frontend/src/pages/employer-invitations/ui/invitation-list.test.tsx b/frontend/src/pages/employer-invitations/ui/invitation-list.test.tsx new file mode 100644 index 0000000..eca700e --- /dev/null +++ b/frontend/src/pages/employer-invitations/ui/invitation-list.test.tsx @@ -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 { + 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[0]> = {}, +): string { + return renderToStaticMarkup( + + undefined} + hasMore={false} + isFetchingMore={false} + onLoadMore={() => undefined} + {...props} + /> + , + ); +} + +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}">]*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(/]/g)).toHaveLength(1); + expect(html).toMatch(/]*>Приглашения компании<\/h2>/); + expect(html).toMatch(/]*>Роль 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(/>Продолжить черновик]*>: Роль 1<\/span><\/a>/); + expect(html).toMatch(/>Открыть приглашение]*>: Роль 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(/]/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(/]/g)).toHaveLength(3); + expect(closed).not.toContain("Доставлено"); + + const drafts = render(items, { filter: "draft" }); + expect(drafts.match(/]/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>/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"'); + }); +}); diff --git a/frontend/src/pages/employer-invitations/ui/invitation-list.tsx b/frontend/src/pages/employer-invitations/ui/invitation-list.tsx new file mode 100644 index 0000000..c5bd758 --- /dev/null +++ b/frontend/src/pages/employer-invitations/ui/invitation-list.tsx @@ -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 ; +} + +/** The facts of one summary. No contact value or candidate name exists in it. */ +function factsOf(item: InvitationSummary): Fact[] { + const facts: Fact[] = [ + { label: "Кандидат", value: {shortHandle(item.candidate_handle)} }, + { 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 ( + +
+

{item.role_title}

+ + {invitationStateLabels[item.state]} + +
+
+ {factsOf(item).map((fact) => ( +
+
{fact.label}
+
{fact.value}
+
+ ))} +
+
+ + {actionLabel(item)} + {`: ${item.role_title}`} + +
+
+ ); +} + +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 ( + Перейти к кандидатам} + /> + ); + } + + const shown = filterInvitations(items, filter); + + return ( +
+
+ +
+ {shown.length > 0 ? ( +
    + {shown.map((item) => ( + + ))} +
+ ) : ( + onFilterChange("all")}> + Показать все + + ) + } + /> + )} + {hasMore ? ( +
+ +
+ ) : null} +
+ ); +} diff --git a/frontend/src/pages/invitation-compose/ui/invitation-compose-page.tsx b/frontend/src/pages/invitation-compose/ui/invitation-compose-page.tsx index 61f75b5..13ef479 100644 --- a/frontend/src/pages/invitation-compose/ui/invitation-compose-page.tsx +++ b/frontend/src/pages/invitation-compose/ui/invitation-compose-page.tsx @@ -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; -/** 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 ; @@ -145,7 +123,9 @@ function SentInvitation({ : "Приглашение уже отправлено"} - {invitationStateLabels[invitation.state]} + + {invitationStateLabels[invitation.state]} +
diff --git a/frontend/src/pages/placeholder/index.ts b/frontend/src/pages/placeholder/index.ts deleted file mode 100644 index 2ce492e..0000000 --- a/frontend/src/pages/placeholder/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { PlaceholderPage } from "./ui/placeholder-page"; -export type { ScreenId } from "./model/screens"; diff --git a/frontend/src/pages/placeholder/model/screens.ts b/frontend/src/pages/placeholder/model/screens.ts deleted file mode 100644 index 832666f..0000000 --- a/frontend/src/pages/placeholder/model/screens.ts +++ /dev/null @@ -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> = { - 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; - -export type ScreenId = keyof typeof screens; diff --git a/frontend/src/pages/placeholder/ui/placeholder-page.module.css b/frontend/src/pages/placeholder/ui/placeholder-page.module.css deleted file mode 100644 index 1c8a0b4..0000000 --- a/frontend/src/pages/placeholder/ui/placeholder-page.module.css +++ /dev/null @@ -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); -} diff --git a/frontend/src/pages/placeholder/ui/placeholder-page.tsx b/frontend/src/pages/placeholder/ui/placeholder-page.tsx deleted file mode 100644 index deac8f1..0000000 --- a/frontend/src/pages/placeholder/ui/placeholder-page.tsx +++ /dev/null @@ -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 ( - - Заготовка}> - Экран будет реализован в одной из следующих задач. Сейчас здесь нет данных и действий. - -
- -
    - {plan.planned.map((item) => ( -
  • {item}
  • - ))} -
-
-
-
- ); -} diff --git a/frontend/src/shared/config/paths.ts b/frontend/src/shared/config/paths.ts index 95838a2..32b9fc1 100644 --- a/frontend/src/shared/config/paths.ts +++ b/frontend/src/shared/config/paths.ts @@ -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. diff --git a/frontend/src/shared/ui/segmented-control/segmented-control.module.css b/frontend/src/shared/ui/segmented-control/segmented-control.module.css index c9e4299..cf46f0b 100644 --- a/frontend/src/shared/ui/segmented-control/segmented-control.module.css +++ b/frontend/src/shared/ui/segmented-control/segmented-control.module.css @@ -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);