diff --git a/backend/Dockerfile.e2e b/backend/Dockerfile.e2e index fdffc99..299afc6 100644 --- a/backend/Dockerfile.e2e +++ b/backend/Dockerfile.e2e @@ -16,6 +16,7 @@ RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldfla RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/consent-fixture ./cmd/consent-fixture RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/company-fixture ./cmd/company-fixture RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/questionnaire-fixture ./cmd/questionnaire-fixture +RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/assessment-category-attest ./cmd/assessment-category-attest FROM ${RUNTIME_IMAGE} @@ -27,6 +28,7 @@ COPY --from=build /out/app /app COPY --from=build /out/consent-fixture /consent-fixture COPY --from=build /out/company-fixture /company-fixture COPY --from=build /out/questionnaire-fixture /questionnaire-fixture +COPY --from=build /out/assessment-category-attest /assessment-category-attest EXPOSE 8080 9090 USER nonroot:nonroot ENTRYPOINT ["/app"] diff --git a/deploy/docker/docker-compose.e2e-mail.yml b/deploy/docker/docker-compose.e2e-mail.yml index 319eb8a..027c896 100644 --- a/deploy/docker/docker-compose.e2e-mail.yml +++ b/deploy/docker/docker-compose.e2e-mail.yml @@ -18,6 +18,10 @@ services: # The browser suite delivers the synthetic inbox event through the real # pipeline; the production default is off. NOTIFICATION_SYNTHETIC_ENABLED: "true" + # The fixture bank is synthetic, so a passed full test may receive the + # uncalibrated demonstration category after the runner attests the + # opening. Ordinary and release E2E keep the default false. + ASSESSMENT_DEMO_CATEGORIES_ENABLED: "true" depends_on: mail-fixture: condition: service_healthy @@ -31,6 +35,7 @@ services: E2E_MAIL_FIXTURE: "1" E2E_COMPANY_FIXTURE: "1" E2E_QUESTIONNAIRE_FIXTURE: "1" + E2E_DEMO_CATEGORIES: "1" E2E_CONSENT_FIXTURE: "1" E2E_COMPANY_FIXTURE_URL: http://company-fixture:8081/company/memberships/revoke E2E_COMPANY_FIXTURE_TOKEN: ${E2E_COMPANY_FIXTURE_TOKEN:?Set the per-run company fixture token} diff --git a/deploy/scripts/e2e.sh b/deploy/scripts/e2e.sh index 0ac78a6..6f5bf73 100644 --- a/deploy/scripts/e2e.sh +++ b/deploy/scripts/e2e.sh @@ -266,6 +266,12 @@ try { compose exec -T backend /consent-fixture # Publish an explicitly reviewed synthetic bank for the questionnaire flow. compose exec -T -e E2E_QUESTIONNAIRE_FIXTURE=1 backend /questionnaire-fixture + # Attest that opening as a synthetic demonstration source, so a passed full + # test of this stand receives the uncalibrated category. The backend of + # this overlay alone enables the runtime gate. + compose exec -T backend /assessment-category-attest attest \ + --specialization backend --grade junior --task-language go \ + --actor operator:e2e-category-attestor fi playwright_command=(node node_modules/@playwright/test/cli.js test) diff --git a/deploy/scripts/test_e2e_mail.py b/deploy/scripts/test_e2e_mail.py index ab8b258..1a87f10 100644 --- a/deploy/scripts/test_e2e_mail.py +++ b/deploy/scripts/test_e2e_mail.py @@ -117,6 +117,8 @@ class ComposeMailFixtureTest(unittest.TestCase): self.assertNotIn(name, rendered["services"]["playwright"].get("environment", {})) self.assertNotIn("E2E_QUESTIONNAIRE_FIXTURE", backend["environment"]) self.assertNotIn("E2E_QUESTIONNAIRE_FIXTURE", rendered["services"]["playwright"].get("environment", {})) + self.assertEqual(backend["environment"]["ASSESSMENT_DEMO_CATEGORIES_ENABLED"], "false") + self.assertNotIn("E2E_DEMO_CATEGORIES", rendered["services"]["playwright"].get("environment", {})) def test_fixture_uses_an_e2e_build_and_fixed_synthetic_credentials(self): services = self.fixture["services"] @@ -138,6 +140,8 @@ class ComposeMailFixtureTest(unittest.TestCase): self.assertEqual(services["playwright"]["environment"]["E2E_QUESTIONNAIRE_FIXTURE"], "1") self.assertNotIn("E2E_QUESTIONNAIRE_FIXTURE", backend["environment"]) self.assertNotIn("questionnaire-fixture", (ROOT / "backend" / "Dockerfile").read_text()) + self.assertEqual(backend["environment"]["ASSESSMENT_DEMO_CATEGORIES_ENABLED"], "true") + self.assertEqual(services["playwright"]["environment"]["E2E_DEMO_CATEGORIES"], "1") self.assertNotIn("E2E_MAIL_FIXTURE", services["frontend"].get("environment", {})) def test_fixture_has_no_host_port_storage_network_or_outbound_route(self): diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 2a38913..d3e5f7f 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -82,7 +82,7 @@ The full inventory and the seed rules are in [Isolated demo stand](#isolated-dem 2. On the same page start the Backend Junior full test with Go: 25 items, a 72-hour deadline, two work sessions, no practice. After it completes, the result is compared with the pass mark of the demo policy; a passed test receives an uncalibrated synthetic category, a failed one the result `not_confirmed`. The result and the history open at `/candidate/results`. 3. Prepared candidate: sign in as `prepared-1@demo.lincodex.test` and open the results, the skill evidence, and the privacy settings with the published card. 4. Employer: sign in as `employer-alpha@demo.lincodex.test`, select "Alpha", create a need, and open the search (`/employer/candidates`). The main group holds the six prepared cards with the flags `ml_unavailable` and `cohort_below_30`; a card and its evidence open from the results. In "Beta" the same account is a recruiter, and search answers 403: in the minimal release only the owner can search. -5. Invitations: the company creates an invitation with the "Invite" button of a search result, sends it, and keeps the address of the invitation page: it holds `invitation_id`. The prepared candidate accepts the invitation at `/candidate/invitations`, choosing the contacts and the consent C4, and the company reads the disclosed contacts on the same invitation page. The company's invitation list is still a placeholder, so keep the page address. +5. Invitations: the company creates an invitation with the "Invite" button of the first card of the main group, fills in the tasks and the team description (the need does not fill them), sends it, and keeps the address of the invitation page: it holds `invitation_id`. Equal cards keep a fixed order, and the first one belongs to `prepared-1@demo.lincodex.test`. This candidate accepts the invitation at `/candidate/invitations`, choosing the contacts and the consent C4, and the company reads the disclosed contacts on the same invitation page. The company's invitation list is still a placeholder, so keep the page address. The eight-minute step-by-step guide with links to the screens and the logins is on the stand at `/demo`; the start page has the button "Open the jury guide". The guide exists only in the demonstration stand build. @@ -90,7 +90,7 @@ The eight-minute step-by-step guide with links to the screens and the logins is - FSP: there is no integration in any mode. This build has no off or mock switch, no fixture provider, and no call to an external API. The profile is filled in manually, linking an FSP ID is optional and not available yet, and the path to a category goes through the questionnaire and the test. The project has no official access to FSP data and does not promise it; an FSP link through a fixture provider is planned (see [ARCHITECTURE.md](ARCHITECTURE.md#identity-fsp-and-privacy)). - ML: the core and demo stands do not start ML and do not call it. Search uses the neutral semantic similarity 0.5 and marks it with the `ml_unavailable` flag. `make -C deploy ml-up` starts a separate service without a model: `/healthz` answers 200 and `/readyz` 503. The core needs no GPU or external inference key and reads none. -- Data: the demo stand holds synthetic data only. Addresses on the reserved domain `@demo.lincodex.test` never receive mail, names are marked as synthetic, categories have the source `synthetic_demo` and are uncalibrated, and the item families are synthetic and had no subject review. Do not register real people on this stand. Only the demo overlay enables synthetic categories (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`); `.env.example` sets `false`. +- Data: the demo stand holds synthetic data only. Addresses on the reserved domain `@demo.lincodex.test` never receive mail, names are marked as synthetic, categories have the source `synthetic_demo` and are uncalibrated, and the item families are synthetic and had no subject review. Do not register real people on this stand. Synthetic categories are enabled (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) only by the demo overlay and by the overlay of the isolated registration browser suite (see [TESTING.md](TESTING.md#minimal-path-from-registration-to-disclosed-contacts)); `.env.example` sets `false`. ### 6. Checks diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 1d25b06..3462098 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -457,6 +457,23 @@ The isolated mail overlay sets `IDENTITY_CLIENT_HOURLY_LIMIT=200` because all br `assessment.spec.ts` uses the same isolated fixture. It saves both languages and explicitly selects Python, then completes the full attempt with keyboard navigation at 360px and waits for finalization and the server result. It separately exercises express training with the resumption of an unfinished run after a reload (409 to a new start, then 201 for the stored key), offline answer submission, replay after a malformed success response, reload, and resuming saved progress. Explicit screenshots cover 360px and 1280px. These synthetic checks validate the application flow, not assessment calibration. +## Minimal path from registration to disclosed contacts + +In the registration mode the overlay `docker-compose.e2e-mail.yml` sets `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` on the test backend and gives Playwright `E2E_DEMO_CATEGORIES=1`. After `questionnaire-fixture`, the runner attests the opened Backend Junior category with the operator command `/assessment-category-attest` from the test backend image, so a passed full test of this stand receives the uncalibrated `synthetic_demo` category, as on the demo stand. The ordinary and release suites keep the default `false`, and `make -C deploy check-e2e-mail` checks both settings. + +`frontend/e2e/acceptance-path.spec.ts` walks the minimal path on the real backend without an FSP ID. Five candidates register with the link from the received message, fill the profile and the questionnaire, grant C3, solve every item of the full test from its statement, and publish an identical card after an explicit C2, because a card is shown only in a group of five. The spec then checks: + +- the result `confirmed` with the category decision `assigned`, `demo_basic_pass_mark`, `synthetic_demo`; a reload in the middle of the attempt returns the same attempt without a second answer, and the result history keeps one entry after a reload and a step back and forward in the browser history; +- a need, the search by its requirements version with the five confirmed entries and the explanation from the server, a filter by the declared grade senior that removes all five cards and keeps only cards of other specs with that grade, and the unchanged result of the first requirements version after the need is edited; +- three invitations bound to the first requirements version, delivered once each; no search result, invitation list, or organization notification holds an email, a phone, or a name; +- an acceptance in the browser with the email only, after which a reload and a history step add no record, there is one C4 record for the organization, and the organization reads only the email; +- two concurrent acceptances of one invitation with different keys: both answer 200 with the same body, one C4 record and one grant; +- a decline without access and the refusal 409 `state_conflict` of a new invitation for the same pair; +- a second company that gets 404 or a field error, never data, for the need, the search by that need, the cards, the invitations, and the contacts of the first one; +- C2 revocation that closes the contact read and the cards of the earlier result at once (the four remaining cards fall below the group of five and are suppressed too), and a new C2 and publication that reopen the cards but not the grant of the accepted invitation. + +The spec does not check the planned transitions without an operation (withdrawal, cancellation by the candidate, the counter offer, the interview, the closed final), the 20-invitation limit per need and the expiry (backend integration tests cover them), category recommendations for a need, which stay `pending`, or a PDF. Traces and screenshots are off; the data are synthetic. + ## Candidate visibility tests Unit tests (`make -C backend test`) check the visibility rules without a database: diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 4a6b727..b8beee4 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -82,7 +82,7 @@ Docker Engine с Compose plugin, GNU make, python3 (цели `deploy` запус 2. Там же начните полный тест Backend Junior с Go: 25 заданий, срок 72 часа, две рабочие сессии, без практики. После завершения результат сравнивается с порогом демонстрационной политики; пройденный тест получает неоткалиброванную синтетическую категорию, непройденный - результат `not_confirmed`. Результат и история открываются в `/candidate/results`. 3. Подготовленный кандидат: войдите как `prepared-1@demo.lincodex.test` и откройте результаты, доказательства навыка и настройки приватности с опубликованной карточкой. 4. Работодатель: войдите как `employer-alpha@demo.lincodex.test`, выберите "Альфу", создайте потребность и откройте подбор (`/employer/candidates`). Основная группа содержит шесть подготовленных карточек с отметками `ml_unavailable` и `cohort_below_30`; карточка и ее доказательства открываются из выдачи. В "Бете" тот же аккаунт - рекрутер, и поиск отвечает 403: в минимальном выпуске искать может только владелец. -5. Приглашения: компания создает приглашение кнопкой "Пригласить" в результате поиска, отправляет его и сохраняет адрес страницы: в нем `invitation_id`. Подготовленный кандидат принимает приглашение в `/candidate/invitations`, выбрав контакты и согласие C4, а компания читает переданные контакты на той же странице приглашения. Список приглашений компании пока заготовка, поэтому адрес страницы нужен. +5. Приглашения: компания создает приглашение кнопкой "Пригласить" у первой карточки основной группы, вписывает задачи и описание команды (потребность их не заполняет), отправляет его и сохраняет адрес страницы: в нем `invitation_id`. Одинаковые карточки идут в постоянном порядке, и первая принадлежит `prepared-1@demo.lincodex.test`. Этот кандидат принимает приглашение в `/candidate/invitations`, выбрав контакты и согласие C4, а компания читает переданные контакты на той же странице приглашения. Список приглашений компании пока заготовка, поэтому адрес страницы нужен. Пошаговый гид на восемь минут со ссылками на экраны и логинами открыт на стенде по адресу `/demo`; на главной есть кнопка "Открыть гид для жюри". Гид есть только в сборке демонстрационного стенда. @@ -90,7 +90,7 @@ Docker Engine с Compose plugin, GNU make, python3 (цели `deploy` запус - ФСП: интеграции нет ни в каком режиме. В этой сборке нет переключателя off или mock, fixture-провайдера и обращений к внешнему API. Профиль заполняется вручную, привязка ФСП ID необязательна и пока недоступна, а путь до категории проходит через анкету и тест. Проект не имеет официального доступа к данным ФСП и не обещает его; связь с ФСП через fixture-провайдер запланирована (см. [ARCHITECTURE.md](ARCHITECTURE.md#идентификация-фсп-и-приватность)). - ML: основной и демонстрационный стенды не запускают ML и не обращаются к нему. Поиск подставляет нейтральную смысловую близость 0.5 и отмечает это флагом `ml_unavailable`. `make -C deploy ml-up` запускает отдельный сервис без модели: `/healthz` отвечает 200, `/readyz` - 503. GPU и ключи внешнего inference ядру не нужны и не читаются. -- Данные: демонстрационный стенд содержит только синтетические данные. Адреса на зарезервированном домене `@demo.lincodex.test` никогда не получают почту, названия помечены как синтетические, категории имеют источник `synthetic_demo` и не откалиброваны, а семейства заданий синтетические и не прошли предметную проверку. Не регистрируйте на этом стенде реальных людей. Синтетические категории включает только демонстрационный overlay (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`); в `.env.example` значение `false`. +- Данные: демонстрационный стенд содержит только синтетические данные. Адреса на зарезервированном домене `@demo.lincodex.test` никогда не получают почту, названия помечены как синтетические, категории имеют источник `synthetic_demo` и не откалиброваны, а семейства заданий синтетические и не прошли предметную проверку. Не регистрируйте на этом стенде реальных людей. Синтетические категории (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) включают только демонстрационный overlay и overlay изолированного браузерного набора регистрации (см. [TESTING.md](TESTING.md#минимальный-путь-от-регистрации-до-раскрытых-контактов)); в `.env.example` значение `false`. ### 6. Проверки diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index dc4b3d1..fdf4221 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -457,6 +457,23 @@ Unit-тесты (`make -C backend test`) проверяют правила жу `assessment.spec.ts` использует тот же изолированный fixture. Он сохраняет оба языка и явно выбирает Python, затем проходит полную попытку клавиатурой на 360 px и ожидает завершения и результата от сервера. Отдельно проверяются express-режим с продолжением незавершенного запуска после перезагрузки (409 на новое начало, затем 201 по сохраненному ключу), отправка ответа без сети, повтор после некорректного успешного ответа, обновление страницы и продолжение сохраненной попытки. Явные снимки покрывают 360 и 1280 px. Синтетические проверки подтверждают работу приложения, но не калибровку оценки. +## Минимальный путь от регистрации до раскрытых контактов + +В режиме регистрации overlay `docker-compose.e2e-mail.yml` выставляет тестовому backend `ASSESSMENT_DEMO_CATEGORIES_ENABLED=true` и передает Playwright `E2E_DEMO_CATEGORIES=1`. После `questionnaire-fixture` runner аттестует открытую категорию Backend Junior операторской командой `/assessment-category-attest` из тестового backend-образа, поэтому пройденный полный тест на этом стенде получает некалиброванную категорию `synthetic_demo`, как на демонстрационном стенде. Обычный и релизный наборы сохраняют значение по умолчанию `false`, а `make -C deploy check-e2e-mail` проверяет обе настройки. + +`frontend/e2e/acceptance-path.spec.ts` проходит минимальный путь на настоящем backend без ФСП ID. Пять кандидатов регистрируются по ссылке из полученного письма, заполняют профиль и анкету, дают C3, решают каждое задание полного теста по его условию и после явного C2 публикуют одинаковую карточку, потому что карточка показывается только в группе из пяти. Затем spec проверяет: + +- результат `confirmed` с решением о категории `assigned`, `demo_basic_pass_mark`, `synthetic_demo`; перезагрузка посреди попытки возвращает ту же попытку без второго ответа, а история результатов хранит одну запись после перезагрузки и шага назад и вперед по истории браузера; +- потребность, поиск по ее версии требований с пятью подтвержденными записями и объяснением от сервера, фильтр по заявленному грейду senior, который убирает все пять карточек и оставляет только чужие карточки с этим грейдом, и неизменный результат первой версии требований после правки потребности; +- три приглашения, привязанные к первой версии требований и доставленные по одному разу; ни результат поиска, ни список приглашений, ни уведомления организации не содержат email, телефон или имя; +- принятие в браузере только с email, после которого перезагрузка и шаг по истории не добавляют записей, для организации есть одна запись C4, а организация читает только email; +- два одновременных принятия одного приглашения с разными ключами: оба отвечают 200 с одинаковым телом, одна запись C4 и один grant; +- отказ без доступа и отказ 409 `state_conflict` в новом приглашении для той же пары; +- вторую компанию, которая получает 404 или ошибку поля, но не данные, для потребности, поиска по этой потребности, карточек, приглашений и контактов первой; +- отзыв C2, который сразу закрывает чтение контактов и карточки прежнего результата (оставшиеся четыре карточки оказываются меньше группы из пяти и тоже скрываются), и новые C2 и публикацию, которые открывают карточки, но не grant принятого приглашения. + +Spec не проверяет запланированные переходы без операции (отзыв приглашения компанией, отмену участия кандидатом, встречное предложение, интервью, закрытый финал), лимит 20 приглашений на потребность и истечение срока (их покрывают интеграционные тесты backend), рекомендации категорий для потребности, которые остаются `pending`, и PDF. Трассировка и снимки выключены, данные синтетические. + ## Тесты видимости кандидата Модульные тесты (`make -C backend test`) проверяют правила видимости без базы: diff --git a/frontend/e2e/acceptance-path.spec.ts b/frontend/e2e/acceptance-path.spec.ts new file mode 100644 index 0000000..06ee485 --- /dev/null +++ b/frontend/e2e/acceptance-path.spec.ts @@ -0,0 +1,1014 @@ +import { expect, test, type Browser, type BrowserContext, type Page } from "@playwright/test"; + +// The minimal path end to end on the real core, without an FSP ID: email +// confirmation from the local mail fixture, profile, questionnaire, the full +// Backend Junior test, the synthetic demonstration category, publication, +// a need, the search and its explanation, an invitation, the acceptance with +// C4, and the contact read by the company. The same run checks that reloads, +// history navigation, and two concurrent acceptances add no second record, +// that another company uses none of these objects, and that C2 revocation +// closes the reads while a new publication does not reopen the grant. +// +// A card is shown only in a group of at least five identical cards, so five +// candidates go through the same steps in the browser and each one solves the +// full test. The isolated registration stand opens the reviewed fixture bank +// (rate-limit items whose answer follows from the statement), enables +// synthetic demonstration categories, and attests the opening; no other stand +// assigns a category this way. + +const enabled = + process.env.E2E_MAIL_FIXTURE === "1" && + process.env.E2E_QUESTIONNAIRE_FIXTURE === "1" && + process.env.E2E_DEMO_CATEGORIES === "1"; +const password = "correct horse battery staple 2026"; +// The same pause as the assessment spec: one client address shares the API +// budget of the stand, and a person reads each item before answering. +const answerPauseMs = 250; +const publishedFields = ["categories", "self_assessment", "stack", "work_formats"]; + +test.use({ trace: "off", screenshot: "off", video: "off", actionTimeout: 15_000 }); + +type ApiResult = { status: number; body: unknown }; +type InboxMessage = { text?: string; html?: string }; +type Candidate = { + context: BrowserContext; + page: Page; + email: string; + phone: string; + fullName: string; +}; +type MatchEntry = { + candidate_handle: string; + specialization: string; + confirmation_status: string; + declared_grade: string | null; + category: { specialization: string; grade: string; basis: string } | null; + components: Record; +}; +type MatchResult = { + source: { kind: string; need_id?: string; requirements_version?: number }; + groups: { main: MatchEntry[]; near: MatchEntry[]; unconfirmed: MatchEntry[] }; + truncated: boolean; +}; +type CandidateInvitation = { + id: string; + state: string; + version: number; + terms_version: number; + organization: { id: string }; + contact_grant: { id: string; fields: string[]; status: string } | null; + contact_consent: { text: { text_version: string }; available_fields: string[] } | null; +}; +type ConsentRecord = { + id: string; + purpose: string; + state: string; + organization?: { id: string } | null; +}; + +function baseUrl(): string { + const value = process.env.E2E_BASE_URL; + if (!value) throw new Error("The local end-to-end base URL is not configured."); + return value; +} + +async function readMailbox(email: string): Promise { + const inboxUrl = process.env.E2E_MAILBOX_URL; + const token = process.env.E2E_MAILBOX_TOKEN; + if (!inboxUrl || !token) throw new Error("The local registration mailbox is not configured."); + const url = new URL(inboxUrl); + url.searchParams.set("to", email); + const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }); + if (!response.ok) throw new Error("Could not read the local registration mailbox."); + return ((await response.json()) as { messages: InboxMessage[] }).messages; +} + +async function verificationToken(email: string): Promise { + const deadline = Date.now() + 20_000; + while (Date.now() < deadline) { + const message = (await readMailbox(email)).at(-1); + if (message) { + const content = `${message.text ?? ""}\n${message.html ?? ""}`; + const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1]; + if (!token) throw new Error("The registration message had no verification link."); + return token; + } + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error("The local mailbox did not receive the verification message."); +} + +// Registers through the form, confirms with the link from the received +// message, and signs in. The message is never printed. +async function createAccount( + page: Page, + scenario: "candidate" | "employer", + email: string, +): Promise { + await page.goto("/register"); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + await page + .getByRole("radio", { name: scenario === "employer" ? /Работодатель/ : /Кандидат/ }) + .check(); + await page.getByRole("checkbox", { name: /принимаю его/ }).check(); + await page.getByRole("button", { name: "Создать аккаунт" }).click(); + await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); + + const verificationUrl = new URL("/verify-email", baseUrl()); + verificationUrl.hash = `token=${await verificationToken(email)}`; + await page.goto(verificationUrl.toString()); + await page.getByLabel("Пароль, выбранный при регистрации").fill(password); + const confirmed = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/identity/email-verifications", + ); + await page.getByRole("button", { name: "Подтвердить почту" }).click(); + expect((await confirmed).status()).toBe(200); + await expect(page.getByText(/Почта подтверждена/)).toBeVisible(); + + await page.goto(scenario === "employer" ? "/employer/company" : "/candidate"); + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + const signedIn = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/identity/sessions", + ); + await page.getByRole("button", { name: "Войти" }).click(); + expect((await signedIn).status()).toBe(201); +} + +// Calls the API from the page, so the cookie and the origin are the browser's. +async function api(page: Page, method: string, path: string, body?: unknown): Promise { + return page.evaluate( + async ({ method, path, body }) => { + const headers: Record = {}; + if (method !== "GET") { + const session = await fetch("/api/v1/identity/sessions/current", { + credentials: "include", + }); + headers["X-CSRF-Token"] = ((await session.json()) as { csrf_token: string }).csrf_token; + headers["Idempotency-Key"] = crypto.randomUUID(); + } + if (body !== undefined) headers["Content-Type"] = "application/json"; + const response = await fetch(path, { + method, + headers, + credentials: "include", + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + return { status: response.status, body: await response.json().catch(() => null) }; + }, + { method, path, body }, + ); +} + +// Sends the same command twice at once, each under its own Idempotency-Key, +// from the page of the signed-in account. +async function concurrently(page: Page, path: string, body: unknown): Promise { + return page.evaluate( + async ({ path, body }) => { + const session = await fetch("/api/v1/identity/sessions/current", { credentials: "include" }); + const csrf = ((await session.json()) as { csrf_token: string }).csrf_token; + const send = () => + fetch(path, { + method: "POST", + credentials: "include", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": csrf, + "Idempotency-Key": crypto.randomUUID(), + }, + body: JSON.stringify(body), + }).then(async (response) => ({ + status: response.status, + body: (await response.json().catch(() => null)) as unknown, + })); + return Promise.all([send(), send()]); + }, + { path, body }, + ); +} + +function apiResponse(method: string, path: string | RegExp) { + return (response: { url(): string; request(): { method(): string } }) => { + const pathname = new URL(response.url()).pathname; + return ( + response.request().method() === method && + (typeof path === "string" ? pathname === path : path.test(pathname)) + ); + }; +} + +// The answer of a rate-limit fixture item follows from its statement: count +// the requests that find `limit` accepted ones in (t - window, t]. +function rejectedRequests(statement: string): number { + const limit = Number(/fewer than (\d+) previously accepted/.exec(statement)?.[1]); + const window = Number(/\(t - (\d+), t\]/.exec(statement)?.[1]); + const times = /arrival times: ([\d ]+)\./.exec(statement)?.[1]?.trim().split(/\s+/).map(Number); + if (!Number.isInteger(limit) || !Number.isInteger(window) || !times?.length) { + throw new Error("The item statement is not a rate-limit fixture item."); + } + const accepted: number[] = []; + let rejected = 0; + for (const moment of times) { + const inWindow = accepted.filter((time) => time > moment - window).length; + if (inWindow < limit) accepted.push(moment); + else rejected += 1; + } + return rejected; +} + +async function saveProfile(candidate: Candidate): Promise { + const { page } = candidate; + await page.goto("/candidate/profile"); + await page.getByLabel("Имя и фамилия").fill(candidate.fullName); + await page.getByLabel("Контактный email").fill(candidate.email); + await page.getByLabel("Телефон").fill(candidate.phone); + for (const heading of ["Роли", "Опыт", "Навыки", "Условия", "Проверка"]) { + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) })).toBeFocused(); + } + const saved = page.waitForResponse(apiResponse("PUT", "/api/v1/me/profile")); + await page.getByRole("button", { name: "Сохранить профиль" }).click(); + expect((await saved).status()).toBe(200); +} + +async function saveQuestionnaire(page: Page): Promise { + await page.goto("/candidate/questionnaire"); + await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible(); + await page.getByLabel("Специализация", { exact: true }).selectOption("backend"); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Уровень и опыт$/ })).toBeFocused(); + await page.getByLabel("Моя оценка уровня").selectOption("junior"); + await page.getByRole("checkbox", { name: "Go", exact: true }).check(); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused(); + await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check(); + await page.getByRole("button", { name: "Далее", exact: true }).click(); + await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused(); + const saved = page.waitForResponse(apiResponse("PUT", "/api/v1/me/questionnaire")); + await page.getByRole("button", { name: "Сохранить анкету" }).click(); + expect((await saved).status()).toBe(200); +} + +async function grantC3(page: Page): Promise { + await page.goto("/candidate/privacy"); + await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click(); + await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check(); + const granted = page.waitForResponse(apiResponse("PUT", "/api/v1/me/consents/c3")); + await page.getByRole("button", { name: "Дать согласие C3" }).click(); + expect((await granted).status()).toBe(200); +} + +// Takes the full Backend Junior test in the browser and answers every item +// from its statement. With `reloadAfter` the page is reloaded after that many +// answers: the same attempt and item come back and nothing is answered twice. +async function passFullTest(page: Page, reloadAfter?: number): Promise { + await page.goto("/candidate/assessment"); + await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible(); + // The questionnaire names Go only, so the page offers no language choice. + const created = page.waitForResponse(apiResponse("POST", "/api/v1/me/assessment-attempts")); + await page.getByRole("button", { name: "Начать полную проверку" }).click(); + await page.getByRole("button", { name: "Подтверждаю ознакомление и начинаю" }).click(); + const createdResponse = await created; + expect(createdResponse.status()).toBe(201); + expect(createdResponse.request().postDataJSON()).toMatchObject({ + kind: "root", + specialization: "backend", + target_grade: "junior", + task_language: "go", + }); + const attemptId = ((await createdResponse.json()) as { id: string }).id; + const attemptPath = `/api/v1/me/assessment-attempts/${attemptId}`; + + const started = page.waitForResponse(apiResponse("POST", `${attemptPath}/sessions`)); + await page.getByRole("button", { name: "Начать или продолжить" }).click(); + const snapshot = (await (await started).json()) as { + progress: { answered_items: number; max_items: number }; + }; + const total = snapshot.progress.max_items; + expect(total).toBeGreaterThan(0); + + for (let sequence = 1; sequence <= total; sequence += 1) { + await expect(page.getByRole("heading", { name: `Задание ${sequence}` })).toBeVisible({ + timeout: 20_000, + }); + const statement = await page + .getByText(/^A gateway applies a sliding-window limiter/) + .innerText(); + await page + .getByRole("textbox", { name: /^Числовой ответ/ }) + .fill(String(rejectedRequests(statement))); + const answered = page.waitForResponse(apiResponse("POST", `${attemptPath}/answers`)); + await page.getByRole("button", { name: "Отправить ответ" }).click(); + expect((await answered).status()).toBe(200); + await page.waitForTimeout(answerPauseMs); + + if (sequence === reloadAfter) { + const reread = page.waitForResponse(apiResponse("GET", attemptPath)); + await page.reload(); + const reloaded = (await (await reread).json()) as { + id: string; + progress: { answered_items: number }; + }; + expect(reloaded.id).toBe(attemptId); + expect(reloaded.progress.answered_items).toBe(sequence); + const resumed = page.waitForResponse(apiResponse("POST", `${attemptPath}/sessions`)); + await page.getByRole("button", { name: "Начать или продолжить" }).click(); + expect((await resumed).status()).toBe(200); + } + } + + const finalized = page.waitForResponse(apiResponse("POST", `${attemptPath}/finalize`)); + await page.getByRole("button", { name: "Завершить проверку" }).click(); + expect((await finalized).status()).toBe(200); + await expect(page.getByRole("heading", { name: "Результат с сервера" })).toBeVisible(); + return attemptId; +} + +async function publishCard(page: Page): Promise { + const text = await api(page, "GET", "/api/v1/me/consent-texts/c2"); + expect(text.status).toBe(200); + const granted = await api(page, "PUT", "/api/v1/me/consents/c2", { + text_version: (text.body as { text_version: string }).text_version, + accepted: true, + }); + expect(granted.status).toBe(200); + const privacy = await api(page, "GET", "/api/v1/me/privacy"); + expect(privacy.status).toBe(200); + const published = await api(page, "PUT", "/api/v1/me/privacy/publication", { + expected_version: (privacy.body as { publication: { version: number } }).publication.version, + state: "published", + fields: publishedFields, + }); + expect(published.status).toBe(200); +} + +// A candidate who confirmed the email, filled the profile and the +// questionnaire without an FSP ID, passed the full test, and published. +async function preparedCandidate(browser: Browser, index: number): Promise { + const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); + const page = await context.newPage(); + const suffix = crypto.randomUUID().replaceAll("-", "").slice(0, 8); + const candidate: Candidate = { + context, + page, + email: `path-${index}-${suffix}@example.test`, + phone: `+7901${String(1_000_000 + Math.floor(Math.random() * 8_999_999))}`, + fullName: `Кандидат пути ${suffix}`, + }; + await createAccount(page, "candidate", candidate.email); + await saveProfile(candidate); + await saveQuestionnaire(page); + await grantC3(page); + await passFullTest(page); + await publishCard(page); + return candidate; +} + +async function myInvitation(candidate: Candidate, id: string): Promise { + const read = await api(candidate.page, "GET", `/api/v1/me/invitations/${id}`); + expect(read.status).toBe(200); + return read.body as CandidateInvitation; +} + +async function c4Records(candidate: Candidate, organizationId: string): Promise { + const list = await api(candidate.page, "GET", "/api/v1/me/consents"); + expect(list.status).toBe(200); + return (list.body as { items: ConsentRecord[] }).items.filter( + (record) => record.purpose === "c4" && record.organization?.id === organizationId, + ); +} + +const terms = { + role_title: "Backend-разработчик сервиса платежей", + specialization: "backend", + grade: "junior", + offer_type: "full_time", + tasks: ["Развивать сервис платежей на Go"], + team: "Команда платежей: пять разработчиков и тимлид.", + tech_stack: ["Go", "PostgreSQL"], + work_formats: ["remote"], + location: null, + communication_method: { channel: "video_call", details: null }, + salary: { + salary_from: 120000, + salary_to: 150000, + currency: "RUB", + period: "month", + tax_basis: "net", + }, + package: { + bonus: { status: "not_provided" }, + equipment: { status: "provided", description: "Ноутбук" }, + training: { status: "not_provided" }, + health_insurance: { status: "not_provided" }, + }, +}; + +test.describe("minimal path from registration to disclosed contacts on the real core", () => { + test.skip(!enabled, "Requires the registration stand with the fixture bank and categories."); + + test("confirms, tests, publishes, matches, invites, accepts once, and closes the reads", async ({ + browser, + page, + }) => { + test.setTimeout(1_200_000); + const candidates: Candidate[] = []; + const contexts: BrowserContext[] = []; + try { + // --- Candidate: confirmed email, profile, questionnaire, test, category. + const mainContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); + contexts.push(mainContext); + const mainPage = await mainContext.newPage(); + const mainSuffix = crypto.randomUUID().replaceAll("-", "").slice(0, 8); + const main: Candidate = { + context: mainContext, + page: mainPage, + email: `path-main-${mainSuffix}@example.test`, + phone: `+7902${String(1_000_000 + Math.floor(Math.random() * 8_999_999))}`, + fullName: `Основной кандидат ${mainSuffix}`, + }; + + await test.step("a confirmed email opens the profile, the questionnaire, and the test", async () => { + await createAccount(mainPage, "candidate", main.email); + await saveProfile(main); + // A reload and a step back in the history keep one stored profile. + await mainPage.reload(); + await expect(mainPage.getByLabel("Имя и фамилия")).toHaveValue(main.fullName); + const profile = await api(mainPage, "GET", "/api/v1/me/profile"); + expect(profile.status).toBe(200); + expect(profile.body).toMatchObject({ + full_name: { value: main.fullName }, + contacts: { email: { value: main.email }, phone: { value: main.phone } }, + }); + await saveQuestionnaire(mainPage); + await mainPage.goBack(); + await mainPage.goForward(); + const questionnaire = await api(mainPage, "GET", "/api/v1/me/questionnaire"); + expect(questionnaire.status).toBe(200); + await grantC3(mainPage); + }); + + let mainAttemptId = ""; + await test.step("the full test passes and assigns the synthetic category once", async () => { + mainAttemptId = await passFullTest(mainPage, 5); + const result = await api( + mainPage, + "GET", + `/api/v1/me/assessment-attempts/${mainAttemptId}/result`, + ); + expect(result.status).toBe(200); + expect(result.body).toMatchObject({ + attempt_id: mainAttemptId, + kind: "root", + mode: "demo_basic", + outcome: "confirmed", + confirmed_grade: "junior", + category_decision: { + status: "assigned", + current_confirmed_grade: "junior", + method: "demo_basic_pass_mark", + source: "synthetic_demo", + }, + }); + // The history holds one result after a reload and a history step. + await mainPage.goto("/candidate/results"); + await mainPage.reload(); + await mainPage.goBack(); + await mainPage.goForward(); + const history = await api(mainPage, "GET", "/api/v1/me/assessment-results"); + expect(history.status).toBe(200); + const items = (history.body as { items: { attempt_id: string }[] }).items; + expect(items.map((item) => item.attempt_id)).toEqual([mainAttemptId]); + }); + + await test.step("the card is published after an explicit C2 and shows the category", async () => { + await publishCard(mainPage); + const preview = await api(mainPage, "GET", "/api/v1/me/privacy/preview"); + expect(preview.status).toBe(200); + const previewText = JSON.stringify(preview.body); + expect(previewText).toContain("synthetic_demo"); + for (const secret of [main.email, main.phone, main.fullName]) { + expect(previewText).not.toContain(secret); + } + }); + candidates.push(main); + + // Four more candidates make a group of five identical cards. + for (let index = 1; index < 5; index += 1) { + const other = await preparedCandidate(browser, index); + contexts.push(other.context); + candidates.push(other); + } + + // --- Employer A: need, search, explanation, filter, snapshot. + const employerEmail = `path-company-${crypto.randomUUID().slice(0, 8)}@example.test`; + await createAccount(page, "employer", employerEmail); + const organization = await api(page, "POST", "/api/v1/organizations", { + name: `Путь ${crypto.randomUUID().slice(0, 6)}`, + }); + expect(organization.status).toBe(201); + const organizationId = (organization.body as { id: string }).id; + + const need = await api(page, "POST", `/api/v1/organizations/${organizationId}/needs`, { + title: "Backend-разработчик платежей", + specialization: { value: "backend", status: "confirmed" }, + grade: { value: "junior", status: "confirmed" }, + required_skills: [{ name: "Go", status: "confirmed" }], + }); + expect(need.status).toBe(201); + const needBody = need.body as { + id: string; + version: number; + requirements_version: number; + recommendations: { status: string; categories: unknown[] }; + }; + const needId = needBody.id; + const firstRequirements = needBody.requirements_version; + + let firstSearch: MatchResult | null = null; + const handles: string[] = []; + await test.step("the need search lists the five confirmed cards with an explanation", async () => { + await page.goto(`/employer/candidates?organization_id=${organizationId}&need_id=${needId}`); + await expect(page.getByRole("radio", { name: "По потребности" })).toBeChecked(); + await expect(page.getByText(`Версия требований: ${firstRequirements}`)).toBeVisible(); + const searched = page.waitForResponse( + apiResponse("POST", `/api/v1/organizations/${organizationId}/matches`), + ); + await page.getByRole("button", { name: "Найти кандидатов" }).click(); + const response = await searched; + expect(response.status()).toBe(200); + firstSearch = (await response.json()) as MatchResult; + expect(firstSearch.source).toEqual({ + kind: "need", + need_id: needId, + requirements_version: firstRequirements, + }); + const confirmed = [...firstSearch.groups.main, ...firstSearch.groups.near]; + expect(confirmed).toHaveLength(5); + for (const entry of confirmed) { + expect(entry).toMatchObject({ + specialization: "backend", + confirmation_status: "confirmed", + category: { specialization: "backend", grade: "junior", basis: "synthetic_demo" }, + }); + handles.push(entry.candidate_handle); + } + expect(new Set(handles).size).toBe(5); + + // The explanation on the screen repeats the components of the server. + const group = firstSearch.groups.main.length > 0 ? "Подтвержденные" : "Близкие варианты"; + const card = page.getByRole("region", { name: group, exact: true }).getByRole("article"); + await expect(card).toHaveCount(5); + const toggle = card.first().getByRole("button", { name: /объяснение/ }); + await toggle.click(); + await expect(toggle).toHaveAttribute("aria-expanded", "true"); + const explanation = card.first().getByRole("region", { name: "Объяснение позиции" }); + await expect(explanation.locator('[data-component="coverage"]')).toBeVisible(); + await expect(explanation.locator('[data-component="semantics"]')).toContainText( + "смысловой анализ недоступен", + ); + + // Nothing identifying or any contact reaches the employer before an answer. + const resultText = `${JSON.stringify(firstSearch)}\n${await page.locator("main").innerText()}`; + for (const candidate of candidates) { + for (const secret of [candidate.email, candidate.phone, candidate.fullName]) { + expect(resultText).not.toContain(secret); + } + } + }); + + await test.step("a filter narrows the result and an edited need keeps the old snapshot", async () => { + const filtered = await api( + page, + "POST", + `/api/v1/organizations/${organizationId}/matches`, + { + need_id: needId, + requirements_version: firstRequirements, + filters: { declared_grade: "senior" }, + }, + ); + expect(filtered.status).toBe(200); + // Other specs of the same stand publish unconfirmed cards with other + // declared grades, so the check is that the five junior cards of this + // run and every other junior card are filtered out. + const narrowed = filtered.body as MatchResult; + const remaining = [ + ...narrowed.groups.main, + ...narrowed.groups.near, + ...narrowed.groups.unconfirmed, + ]; + expect(narrowed.groups.main.length + narrowed.groups.near.length).toBe(0); + for (const entry of remaining) { + expect(handles).not.toContain(entry.candidate_handle); + expect(entry.declared_grade).toBe("senior"); + } + + const edited = await api( + page, + "PATCH", + `/api/v1/organizations/${organizationId}/needs/${needId}`, + { + expected_version: needBody.version, + required_skills: [ + { name: "Go", status: "confirmed" }, + { name: "Kafka", status: "confirmed" }, + ], + }, + ); + expect(edited.status).toBe(200); + expect( + (edited.body as { requirements_version: number }).requirements_version, + ).toBeGreaterThan(firstRequirements); + const again = await api(page, "POST", `/api/v1/organizations/${organizationId}/matches`, { + need_id: needId, + requirements_version: firstRequirements, + }); + expect(again.status).toBe(200); + expect(again.body).toEqual(firstSearch); + }); + + // Which candidate stands behind which handle is learned from the inboxes. + const invitationOf = new Map(); + await test.step("each invitation is delivered once and holds no contact", async () => { + for (const handle of handles.slice(0, 3)) { + const draft = await api( + page, + "POST", + `/api/v1/organizations/${organizationId}/invitations`, + { + candidate_handle: handle, + // The invitation keeps the first requirements snapshot of the need. + need: { need_id: needId, requirements_version: firstRequirements }, + response_period_days: 7, + terms, + }, + ); + expect(draft.status, JSON.stringify(draft.body)).toBe(201); + const draftBody = draft.body as { id: string; version: number }; + const sent = await api( + page, + "POST", + `/api/v1/organizations/${organizationId}/invitations/${draftBody.id}/send`, + { expected_version: draftBody.version }, + ); + expect(sent.status, JSON.stringify(sent.body)).toBe(200); + } + for (const candidate of candidates) { + const inbox = await api(candidate.page, "GET", "/api/v1/me/invitations"); + expect(inbox.status).toBe(200); + const items = (inbox.body as { items: CandidateInvitation[] }).items.filter( + (item) => item.organization.id === organizationId, + ); + expect(items.length).toBeLessThanOrEqual(1); + if (items[0]) invitationOf.set(candidate, items[0].id); + } + expect(invitationOf.size).toBe(3); + const list = await api(page, "GET", `/api/v1/organizations/${organizationId}/invitations`); + expect(list.status).toBe(200); + const listText = JSON.stringify(list.body); + expect((list.body as { items: unknown[] }).items).toHaveLength(3); + for (const candidate of candidates) { + for (const secret of [candidate.email, candidate.phone, candidate.fullName]) { + expect(listText).not.toContain(secret); + } + } + }); + + const [accepting, racing, declining] = [...invitationOf.entries()]; + if (!accepting || !racing || !declining) throw new Error("Three invitations are needed."); + + await test.step("the candidate accepts in the browser and a reload or history step adds nothing", async () => { + const [candidate, invitationId] = accepting; + const candidatePage = candidate.page; + await candidatePage.goto("/candidate/invitations"); + await candidatePage.goto(`/candidate/invitations/${invitationId}`); + await expect( + candidatePage.getByRole("heading", { level: 1, name: "Приглашение" }), + ).toBeVisible(); + await candidatePage + .getByRole("checkbox", { name: "Электронная почта", exact: true }) + .check(); + await candidatePage + .getByRole("checkbox", { name: /Я прочитал\(а\) текст согласия/ }) + .check(); + const accepted = candidatePage.waitForResponse( + apiResponse("POST", `/api/v1/me/invitations/${invitationId}/accept`), + ); + await candidatePage.getByRole("button", { name: "Принять и передать контакты" }).click(); + expect((await accepted).status()).toBe(200); + await expect(candidatePage.locator('[data-state="accepted"]')).toHaveText("Принято"); + + await candidatePage.reload(); + await expect(candidatePage.locator('[data-state="accepted"]')).toHaveText("Принято"); + await candidatePage.goBack(); + await candidatePage.goForward(); + await expect(candidatePage.locator('[data-state="accepted"]')).toHaveText("Принято"); + await expect( + candidatePage.getByRole("button", { name: "Принять и передать контакты" }), + ).toHaveCount(0); + + const read = await myInvitation(candidate, invitationId); + expect(read).toMatchObject({ + state: "accepted", + contact_grant: { fields: ["email"], status: "active" }, + }); + expect(await c4Records(candidate, organizationId)).toHaveLength(1); + + const contacts = await api( + page, + "GET", + `/api/v1/organizations/${organizationId}/invitations/${invitationId}/contacts`, + ); + expect(contacts.status).toBe(200); + expect(contacts.body).toMatchObject({ + email: candidate.email, + phone: null, + full_name: null, + }); + }); + + await test.step("two concurrent acceptances make one transition, one C4, and one grant", async () => { + const [candidate, invitationId] = racing; + const before = await myInvitation(candidate, invitationId); + // C4 has no settings text: the offer of the invitation carries it. + const offer = before.contact_consent; + if (!offer) throw new Error("The delivered invitation offers no C4 consent."); + expect([...offer.available_fields].sort()).toEqual(["email", "full_name", "phone"]); + const answers = await concurrently( + candidate.page, + `/api/v1/me/invitations/${invitationId}/accept`, + { + expected_version: before.version, + terms_version: before.terms_version, + consent_c4: { + text_version: offer.text.text_version, + accepted: true, + fields: ["email", "phone"], + }, + }, + ); + expect(answers.map((answer) => answer.status)).toEqual([200, 200]); + expect(answers[0]?.body).toEqual(answers[1]?.body); + const after = await myInvitation(candidate, invitationId); + expect(after.state).toBe("accepted"); + expect([...(after.contact_grant?.fields ?? [])].sort()).toEqual(["email", "phone"]); + expect(after.contact_grant?.id).toBe( + (answers[0]?.body as CandidateInvitation).contact_grant?.id, + ); + expect(await c4Records(candidate, organizationId)).toHaveLength(1); + const contacts = await api( + page, + "GET", + `/api/v1/organizations/${organizationId}/invitations/${invitationId}/contacts`, + ); + expect(contacts.status).toBe(200); + expect(contacts.body).toMatchObject({ email: candidate.email, phone: candidate.phone }); + }); + + await test.step("a decline gives no access and pauses a new invitation", async () => { + const [candidate, invitationId] = declining; + const declined = await api( + candidate.page, + "POST", + `/api/v1/me/invitations/${invitationId}/decline`, + { + expected_version: (await myInvitation(candidate, invitationId)).version, + reason: "other", + }, + ); + expect(declined.status).toBe(200); + const contacts = await api( + page, + "GET", + `/api/v1/organizations/${organizationId}/invitations/${invitationId}/contacts`, + ); + expect(contacts.status).toBe(404); + expect((await myInvitation(candidate, invitationId)).contact_grant).toBeNull(); + + // A new invitation for the same pair is refused at the send for 30 days. + const sentRead = await api( + page, + "GET", + `/api/v1/organizations/${organizationId}/invitations/${invitationId}`, + ); + expect(sentRead.status).toBe(200); + const handle = (sentRead.body as { candidate_handle: string }).candidate_handle; + const draft = await api( + page, + "POST", + `/api/v1/organizations/${organizationId}/invitations`, + { + candidate_handle: handle, + response_period_days: 7, + terms, + }, + ); + expect(draft.status, JSON.stringify(draft.body)).toBe(201); + const draftBody = draft.body as { id: string; version: number }; + const resent = await api( + page, + "POST", + `/api/v1/organizations/${organizationId}/invitations/${draftBody.id}/send`, + { expected_version: draftBody.version }, + ); + expect(resent.status, JSON.stringify(resent.body)).toBe(409); + expect(resent.body).toMatchObject({ code: "state_conflict" }); + const inbox = await api(candidate.page, "GET", "/api/v1/me/invitations"); + expect( + (inbox.body as { items: CandidateInvitation[] }).items.filter( + (item) => item.organization.id === organizationId, + ), + ).toHaveLength(1); + }); + + await test.step("the organization inbox names no contact before or after the answers", async () => { + const notifications = await api( + page, + "GET", + `/api/v1/organizations/${organizationId}/notifications`, + ); + expect(notifications.status).toBe(200); + const text = JSON.stringify(notifications.body); + for (const candidate of candidates) { + for (const secret of [candidate.email, candidate.phone, candidate.fullName]) { + expect(text).not.toContain(secret); + } + } + }); + + // --- Company B uses none of the objects of company A. + await test.step("another company reads no need, card, invitation, or contact of the first", async () => { + const otherContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" }); + contexts.push(otherContext); + const other = await otherContext.newPage(); + await createAccount( + other, + "employer", + `path-other-${crypto.randomUUID().slice(0, 8)}@example.test`, + ); + const otherOrganization = await api(other, "POST", "/api/v1/organizations", { + name: `Чужая ${crypto.randomUUID().slice(0, 6)}`, + }); + expect(otherOrganization.status).toBe(201); + const otherId = (otherOrganization.body as { id: string }).id; + const [, acceptedId] = accepting; + // A foreign handle in a draft is a field error; every read is not found + // or forbidden. No answer carries a value of a candidate. + const denied: [string, ApiResult, number[]][] = [ + [ + "need of A in its own path", + await api(other, "GET", `/api/v1/organizations/${organizationId}/needs/${needId}`), + [403, 404], + ], + [ + "need of A under B", + await api(other, "GET", `/api/v1/organizations/${otherId}/needs/${needId}`), + [404], + ], + [ + "search by the need of A", + await api(other, "POST", `/api/v1/organizations/${otherId}/matches`, { + need_id: needId, + requirements_version: firstRequirements, + }), + [404], + ], + [ + "card by a handle of A", + await api( + other, + "GET", + `/api/v1/organizations/${otherId}/candidate-cards/${handles[0]}`, + ), + [404], + ], + [ + "invitation of A", + await api( + other, + "GET", + `/api/v1/organizations/${organizationId}/invitations/${acceptedId}`, + ), + [403, 404], + ], + [ + "contacts of A in its own path", + await api( + other, + "GET", + `/api/v1/organizations/${organizationId}/invitations/${acceptedId}/contacts`, + ), + [403, 404], + ], + [ + "contacts of A under B", + await api( + other, + "GET", + `/api/v1/organizations/${otherId}/invitations/${acceptedId}/contacts`, + ), + [404], + ], + [ + "draft for a handle of A", + await api(other, "POST", `/api/v1/organizations/${otherId}/invitations`, { + candidate_handle: handles[0], + response_period_days: 7, + terms, + }), + [400, 404], + ], + ]; + for (const [name, answer, allowed] of denied) { + expect(allowed, `${name}: ${answer.status} ${JSON.stringify(answer.body)}`).toContain( + answer.status, + ); + for (const candidate of candidates) { + for (const secret of [candidate.email, candidate.phone, candidate.fullName]) { + expect(JSON.stringify(answer.body)).not.toContain(secret); + } + } + } + const draftRefusal = denied.at(-1)?.[1]; + if (draftRefusal?.status === 400) { + expect(JSON.stringify(draftRefusal.body)).toContain("/candidate_handle"); + } + const otherList = await api(other, "GET", `/api/v1/organizations/${otherId}/invitations`); + expect(otherList.status).toBe(200); + expect((otherList.body as { items: unknown[] }).items).toHaveLength(0); + }); + + // --- Revocation of C2 closes the reads; a new publication does not reopen them. + await test.step("C2 revocation closes contacts, the card, and the old search; republishing keeps them closed", async () => { + const [candidate, invitationId] = racing; + const contactsPath = `/api/v1/organizations/${organizationId}/invitations/${invitationId}/contacts`; + const revoked = await api(candidate.page, "DELETE", "/api/v1/me/consents/c2"); + expect(revoked.status).toBe(204); + const closedRead = await api(page, "GET", contactsPath); + expect(closedRead.status, JSON.stringify(closedRead.body)).not.toBe(200); + expect(JSON.stringify(closedRead.body)).not.toContain(candidate.email); + const grant = (await myInvitation(candidate, invitationId)).contact_grant; + expect(grant?.status).not.toBe("active"); + + // The handles of the earlier result no longer open the cards: the + // revoked card is closed, and the four left fall below the group of + // five, so they are suppressed as well. A new search lists none. + const searchByNeed = async (): Promise => { + const result = await api( + page, + "POST", + `/api/v1/organizations/${organizationId}/matches`, + { + need_id: needId, + requirements_version: firstRequirements, + }, + ); + expect(result.status).toBe(200); + return result.body as MatchResult; + }; + const cardStatuses = async (): Promise => { + const statuses: number[] = []; + for (const handle of handles) { + const card = await api( + page, + "GET", + `/api/v1/organizations/${organizationId}/candidate-cards/${handle}`, + ); + statuses.push(card.status); + } + return statuses; + }; + expect(await cardStatuses()).toEqual([404, 404, 404, 404, 404]); + const closed = await searchByNeed(); + expect(closed.groups.main.length + closed.groups.near.length).toBe(0); + + // A new C2 and a new publication make the group of five again, but the + // grant of the accepted invitation stays closed until a new C4. + await publishCard(candidate.page); + expect(await cardStatuses()).toEqual([200, 200, 200, 200, 200]); + const reopened = await searchByNeed(); + expect(reopened.groups.main.length + reopened.groups.near.length).toBe(5); + const reread = await api(page, "GET", contactsPath); + expect(reread.status).not.toBe(200); + expect(JSON.stringify(reread.body)).not.toContain(candidate.email); + const after = await myInvitation(candidate, invitationId); + expect(after.state).toBe("accepted"); + expect(after.contact_grant?.status).not.toBe("active"); + // The other accepted invitation keeps its own grant. + const [acceptedCandidate, acceptedId] = accepting; + expect((await myInvitation(acceptedCandidate, acceptedId)).contact_grant?.status).toBe( + "active", + ); + }); + } finally { + await Promise.all(contexts.map((context) => context.close())); + } + }); +}); diff --git a/frontend/src/pages/jury-guide/model/guide.ts b/frontend/src/pages/jury-guide/model/guide.ts index 7d57f93..8e3b30c 100644 --- a/frontend/src/pages/jury-guide/model/guide.ts +++ b/frontend/src/pages/jury-guide/model/guide.ts @@ -75,7 +75,7 @@ export const guideRoles: readonly GuideRole[] = [ link: { label: "Открыть подбор", to: paths.employer.candidates }, }, { - text: "Нажмите «Пригласить» у одного из подготовленных кандидатов. Большая часть условий уже заполнена из потребности; выберите тип предложения и канал связи, отметьте хотя бы один формат работы и для каждого условия пакета укажите «Предусмотрено» с описанием. Затем нажмите «Отправить приглашение» и сохраните адрес страницы: в нем invitation_id, по нему открывается приглашение после ответа кандидата.", + text: "Нажмите «Пригласить» у первой карточки основной группы: одинаковые карточки идут в постоянном порядке, и первая принадлежит prepared-1, который ответит на приглашение. Название роли, специализация, грейд, технологии и вилка уже заполнены из потребности. Впишите «Задачи» (по одной в строке) и «Команда» (размер и роли, без имен), выберите тип предложения и канал связи, отметьте хотя бы один формат работы и для каждого условия пакета укажите «Предусмотрено» с описанием. Затем нажмите «Отправить приглашение» и сохраните адрес страницы: в нем invitation_id, по нему открывается приглашение после ответа кандидата.", link: null, }, ], diff --git a/frontend/src/pages/jury-guide/ui/jury-guide-page.test.tsx b/frontend/src/pages/jury-guide/ui/jury-guide-page.test.tsx index bc6c769..213df64 100644 --- a/frontend/src/pages/jury-guide/ui/jury-guide-page.test.tsx +++ b/frontend/src/pages/jury-guide/ui/jury-guide-page.test.tsx @@ -84,6 +84,20 @@ describe("jury guide page", () => { } }); + it("sends the invitation to the candidate who answers it and names the fields a need leaves empty", () => { + const steps = guideRoles.flatMap((role) => role.steps.map((step) => step.text)); + const invite = steps.find((text) => text.includes("«Пригласить»")) ?? ""; + + // The need of the route has no tasks, and a need never carries a team, so + // the invitation form refuses to leave its first step until both are set. + expect(invite).toContain("«Задачи»"); + expect(invite).toContain("«Команда»"); + // Equal cards keep a fixed order, and the first one belongs to prepared-1, + // the account that answers the invitation in the next block. + expect(invite).toContain("первой карточки"); + expect(invite).toContain("prepared-1"); + }); + it("states the limits: mail may be off and real people must not register", () => { const html = render();