Files
lincodex/frontend/e2e/need-management.spec.ts
T

592 lines
27 KiB
TypeScript

import { expect, test, type Locator, type Page, type Response } from "@playwright/test";
type InboxMessage = {
id: string;
text?: string;
html?: string;
};
type InboxResponse = {
messages: InboxMessage[];
};
type CurrentSessionResponse = {
account: { id: string };
};
type OrganizationResponse = {
id: string;
name: string;
};
type NeedResponse = {
id: string;
title: string;
source_text?: string | null;
version: number;
requirements_version: number;
requirements: {
specialization: { status: string; value: string | null; source?: { origin: string } | null };
required_skills: {
name: string;
status: string;
source?: { origin: string } | null;
}[];
tasks: { text: string; status: string; source?: { origin: string } | null }[];
grade: {
status: string;
value: string | null;
source?: { origin: string } | null;
};
salary: {
status: string;
value: { tax_basis: string } | null;
source?: { origin: string } | null;
};
};
readiness: { status: string; missing_fields: { field: string; question: string }[] };
recommendations: { status: string; categories: unknown[] };
};
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1";
const password = "correct horse battery staple 2026";
function baseUrl(): string {
const value = process.env.E2E_BASE_URL;
if (!value) throw new Error("The local browser test origin is not configured.");
return value;
}
function needCollectionPath(organizationId: string): string {
return `/api/v1/organizations/${organizationId}/needs`;
}
function needPath(organizationId: string, needId: string): string {
return `${needCollectionPath(organizationId)}/${needId}`;
}
async function readInbox(email: string): Promise<InboxMessage[]> {
const inboxUrl = process.env.E2E_MAILBOX_URL;
const token = process.env.E2E_MAILBOX_TOKEN;
if (!inboxUrl || !token)
throw new Error("The local registration mailbox fixture 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 InboxResponse).messages;
}
async function waitForVerificationMessage(email: string): Promise<InboxMessage> {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
const message = (await readInbox(email)).at(-1);
if (message) return message;
await new Promise((resolve) => setTimeout(resolve, 250));
}
throw new Error("The local registration mailbox did not receive the expected message.");
}
function verificationToken(message: InboxMessage): string {
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 local registration message had no verification link.");
return token;
}
async function registerVerifiedEmployer(page: Page): Promise<{ email: string; userId: string }> {
const email = `company-${crypto.randomUUID().slice(0, 8)}@example.test`;
await page.goto("/register");
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("radio", { name: /Работодатель/ }).check();
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
await page.getByRole("button", { name: "Создать аккаунт" }).click();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
const message = await waitForVerificationMessage(email);
const verificationUrl = new URL("/verify-email", baseUrl());
verificationUrl.hash = `token=${verificationToken(message)}`;
await page.goto(verificationUrl.toString());
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await page.goto("/employer/company");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
const loginResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions" &&
response.status() === 201,
);
await page.getByRole("button", { name: "Войти" }).click();
await expect(page.getByRole("heading", { name: "Компания" })).toBeVisible();
const loginResponse = await loginResponsePromise;
const currentSession = (await loginResponse.json()) as CurrentSessionResponse;
return { email, userId: currentSession.account.id };
}
async function signInEmployer(page: Page, email: string): Promise<void> {
await page.goto("/employer/needs");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
const loginResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions" &&
response.status() === 201,
);
await page.getByRole("button", { name: "Войти" }).click();
await loginResponsePromise;
}
async function createOrganization(page: Page, name: string): Promise<OrganizationResponse> {
const result = await page.evaluate(
async ({ organizationName, key }) => {
const sessionResponse = await fetch("/api/v1/identity/sessions/current", {
cache: "no-store",
});
if (!sessionResponse.ok) return { status: sessionResponse.status, body: null };
const session = (await sessionResponse.json()) as { csrf_token?: string };
if (!session.csrf_token) return { status: 401, body: null };
const response = await fetch("/api/v1/organizations", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": key,
"X-CSRF-Token": session.csrf_token,
},
body: JSON.stringify({ name: organizationName }),
});
return {
status: response.status,
body: (await response.json()) as OrganizationResponse,
};
},
{ organizationName: name, key: crypto.randomUUID() },
);
if (result.status !== 201 || !result.body) {
throw new Error("Could not create the synthetic organization for the need flow.");
}
return result.body;
}
async function revokeMembership(
organizationId: string,
userId: string,
successorUserId: string,
): Promise<void> {
const fixtureURL = process.env.E2E_COMPANY_FIXTURE_URL;
const fixtureToken = process.env.E2E_COMPANY_FIXTURE_TOKEN;
if (!fixtureURL || !fixtureToken)
throw new Error("The isolated company fixture is not configured.");
const response = await fetch(new URL(fixtureURL), {
method: "POST",
headers: {
Authorization: `Bearer ${fixtureToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
organization_id: organizationId,
user_id: userId,
successor_user_id: successorUserId,
}),
});
if (response.status !== 204) {
throw new Error(
`The isolated company fixture could not transfer the synthetic membership (status ${response.status}).`,
);
}
}
async function findSkillRow(section: Locator, name: string): Promise<Locator> {
const rows = section.getByRole("listitem");
for (let index = 0; index < (await rows.count()); index += 1) {
const row = rows.nth(index);
if ((await row.locator("input").inputValue()) === name) return row;
}
throw new Error(`The parsed need did not contain the expected skill ${name}.`);
}
// The need form has five steps and saves only on the last one; "Далее" moves one step on.
async function nextStep(page: Page, times = 1): Promise<void> {
for (let index = 0; index < times; index += 1) {
await page.getByRole("button", { name: "Далее", exact: true }).click();
}
}
function isResponse(response: Response, method: string, path: string, status: number): boolean {
return (
response.request().method() === method &&
new URL(response.url()).pathname === path &&
response.status() === status
);
}
function sanitizedPageError(error: Error, privateValues: string[]): string {
let message = error.message.split("\n", 1)[0] ?? "";
for (const value of privateValues) {
if (value !== "") message = message.replaceAll(value, "[redacted]");
}
message = message
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, "[email]")
.replace(/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi, "[id]");
return `${error.name}: ${message.slice(0, 180)}`;
}
test.use({ trace: "off", screenshot: "off", video: "off" });
test.describe("employer needs", () => {
test.skip(
!mailFixtureEnabled || !companyFixtureEnabled,
"Requires the isolated mail and company fixtures.",
);
test("creates, edits, reloads, handles conflicts, and removes private data after owner access ends", async ({
browser,
page,
}) => {
const owner = await registerVerifiedEmployer(page);
const suffix = crypto.randomUUID().slice(0, 8);
const organization = await createOrganization(page, `Need team ${suffix}`);
const sourceText =
"Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно.";
const pageErrors: string[] = [];
page.on("pageerror", (error) => {
pageErrors.push(sanitizedPageError(error, [owner.email, sourceText, suffix]));
});
await page.goto(`/employer/needs?organization_id=${encodeURIComponent(organization.id)}`);
await expect(
page.getByRole("status").getByText("Потребностей пока нет", { exact: true }),
).toBeVisible();
await page.getByRole("link", { name: "Создать потребность" }).first().click();
await expect(page.getByLabel("Название потребности")).toBeVisible();
await expect(page.getByText("Вакансия для сохранения потребности не требуется.")).toBeVisible();
await expect(page.getByText("Шаг 1 из 5")).toBeVisible();
// A step that needs a title does not let the employer leave it blank.
await nextStep(page);
await expect(page.getByLabel("Название потребности")).toHaveAttribute("aria-invalid", "true");
await expect(page.getByLabel("Название потребности")).toBeFocused();
await page.getByLabel("Название потребности").fill(`Payments backend ${suffix}`);
// An unknown grade stays unknown: no grade radio is preselected.
await expect(page.getByRole("radio", { name: "Не указан", exact: true })).toBeChecked();
expect(pageErrors, `Browser page errors: ${pageErrors.join("; ")}`).toEqual([]);
await page.getByLabel("Описание работы").fill(sourceText);
expect(pageErrors, `Browser page errors: ${pageErrors.join("; ")}`).toEqual([]);
// Focus follows the employer to the heading of each step, and back keeps the draft.
await nextStep(page);
await expect(
page.getByRole("heading", { level: 2, name: "Навыки", exact: true }),
).toBeFocused();
await page.getByRole("button", { name: "Назад", exact: true }).click();
await expect(page.getByRole("heading", { level: 2, name: "Роль и грейд" })).toBeFocused();
await expect(page.getByLabel("Описание работы")).toHaveValue(sourceText);
await nextStep(page, 3);
await expect(page.getByRole("radio", { name: /После налога/ })).not.toBeChecked();
await expect(page.getByRole("radio", { name: /До налога/ })).not.toBeChecked();
await expect(
page.getByText("Укажите обе суммы и выберите базу. Без явной базы диапазон не сохранится."),
).toBeVisible();
await nextStep(page);
const organizationNeedsPath = needCollectionPath(organization.id);
const createResponsePromise = page.waitForResponse((response) =>
isResponse(response, "POST", organizationNeedsPath, 201),
);
await page.getByRole("button", { name: "Создать потребность" }).click();
const createResponse = await createResponsePromise;
const createRequest = createResponse.request();
expect(createRequest.headers()["x-csrf-token"]).toBeTruthy();
expect(createRequest.headers()["idempotency-key"]).toBeTruthy();
const created = (await createResponse.json()) as NeedResponse;
expect(created.version).toBe(1);
expect(created.requirements_version).toBe(1);
expect(created.requirements.grade.status).toBe("unknown");
expect(created.requirements.grade.value).toBeNull();
expect(created.readiness.missing_fields.map((field) => field.field)).toContain("salary");
expect(created.recommendations.status).toBe("not_available");
await nextStep(page);
const requiredSkills = page
.getByRole("heading", { name: "Обязательные навыки" })
.locator("xpath=..");
await expect(requiredSkills.getByRole("listitem")).toHaveCount(3);
const goRow = await findSkillRow(requiredSkills, "Go");
const postgresRow = await findSkillRow(requiredSkills, "PostgreSQL");
const temporalRow = await findSkillRow(requiredSkills, "Temporal");
await goRow.getByRole("button", { name: "Подтвердить", exact: true }).click();
await temporalRow.locator("input").fill("TemporalDB");
await postgresRow.getByRole("button", { name: "Удалить", exact: true }).click();
const needId = created.id;
const itemPath = needPath(organization.id, needId);
await nextStep(page, 3);
const firstSavePromise = page.waitForResponse((response) =>
isResponse(response, "PATCH", itemPath, 200),
);
await page.getByRole("button", { name: "Сохранить изменения" }).click();
const firstSave = (await firstSavePromise).json() as Promise<NeedResponse>;
const saved = await firstSave;
expect(saved.version).toBe(2);
expect(saved.requirements.required_skills.map((skill) => skill.name)).toEqual([
"Go",
"TemporalDB",
]);
expect(saved.recommendations.status).toBe("pending");
expect(saved.recommendations.categories).toEqual([]);
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
const reloadResponsePromise = page.waitForResponse((response) =>
isResponse(response, "GET", itemPath, 200),
);
await page.reload();
const reloaded = (await reloadResponsePromise).json() as Promise<NeedResponse>;
const reloadedNeed = await reloaded;
expect(reloadedNeed.requirements.required_skills.map((skill) => skill.name)).not.toContain(
"PostgreSQL",
);
await expect(page.getByLabel("Описание работы")).toHaveValue(sourceText);
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
const secondContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
const secondPage = await secondContext.newPage();
try {
await signInEmployer(secondPage, owner.email);
await secondPage.goto(
`/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`,
);
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(
`Payments backend ${suffix}`,
);
const firstWindowTitle = `Payments backend first ${suffix}`;
await page.getByLabel("Название потребности").fill(firstWindowTitle);
// An existing need can jump straight to the review step.
await page.getByRole("button", { name: "К проверке и сохранению" }).click();
const firstWindowSave = page.waitForResponse((response) =>
isResponse(response, "PATCH", itemPath, 200),
);
await page.getByRole("button", { name: "Сохранить изменения" }).click();
const firstWindowResponse = await firstWindowSave;
const firstWindowSaved = (await firstWindowResponse.json()) as NeedResponse;
expect(firstWindowSaved.title).toBe(firstWindowTitle);
await expect(page.getByLabel("Название потребности")).toHaveValue(firstWindowTitle);
const secondWindowDraft = `Payments backend second ${suffix}`;
await secondPage.getByLabel("Название потребности").fill(secondWindowDraft);
await secondPage.getByRole("button", { name: "К проверке и сохранению" }).click();
const conflictResponsePromise = secondPage.waitForResponse((response) =>
isResponse(response, "PATCH", itemPath, 412),
);
await secondPage.getByRole("button", { name: "Сохранить изменения" }).click();
expect((await conflictResponsePromise).status()).toBe(412);
await expect(secondPage.getByRole("heading", { name: "Версия изменилась" })).toBeVisible();
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft);
const latestResponsePromise = secondPage.waitForResponse((response) =>
isResponse(response, "GET", itemPath, 200),
);
await secondPage.getByRole("button", { name: "Загрузить и применить мой черновик" }).click();
await latestResponsePromise;
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft);
await expect(
secondPage.getByRole("heading", { name: "Проверьте объединенный черновик" }),
).toBeVisible();
await secondPage.getByRole("button", { name: "Продолжить сохранение" }).click();
const rebasedSavePromise = secondPage.waitForResponse((response) =>
isResponse(response, "PATCH", itemPath, 200),
);
await secondPage.getByRole("button", { name: "Сохранить изменения" }).click();
const rebasedSaveResponse = await rebasedSavePromise;
const rebased = (await rebasedSaveResponse.json()) as NeedResponse;
expect(rebased.title).toBe(secondWindowDraft);
await expect(secondPage.getByLabel("Название потребности")).toHaveValue(secondWindowDraft);
const artifactsDirectory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
await page.setViewportSize({ width: 360, height: 900 });
const hasHorizontalOverflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(hasHorizontalOverflow).toBe(false);
await page.screenshot({
path: `${artifactsDirectory}/need-editor-mobile.png`,
animations: "disabled",
});
await page.setViewportSize({ width: 1280, height: 900 });
await page.screenshot({
path: `${artifactsDirectory}/need-editor-desktop.png`,
animations: "disabled",
});
const successorContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
try {
const successorPage = await successorContext.newPage();
const successor = await registerVerifiedEmployer(successorPage);
await successorPage.goto(
`/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`,
);
await expect(
successorPage.getByText("Потребность недоступна", { exact: true }),
).toBeVisible();
await expect(successorPage.getByLabel("Название потребности")).toHaveCount(0);
const beforeTransferStatus = await successorPage.evaluate(
async ({ orgId, id }) => {
const response = await fetch(`/api/v1/organizations/${orgId}/needs/${id}`, {
cache: "no-store",
});
return response.status;
},
{ orgId: organization.id, id: needId },
);
expect(beforeTransferStatus).toBe(404);
await revokeMembership(organization.id, owner.userId, successor.userId);
async function expectOwnerAccessRemoved(targetPage: Page): Promise<void> {
await test.step("Refresh directory after owner access is revoked", async () => {
const directoryResponsePromise = targetPage.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/me/organizations" &&
response.status() === 200,
{ timeout: 10_000 },
);
await targetPage.bringToFront();
await targetPage.evaluate(() => {
window.dispatchEvent(new Event("visibilitychange"));
});
await directoryResponsePromise;
await expect(
targetPage.getByText("Потребность недоступна", { exact: true }),
).toBeVisible();
await expect(targetPage.getByLabel("Название потребности")).toHaveCount(0);
await expect(targetPage.getByLabel("Описание работы")).toHaveCount(0);
await expect(targetPage.getByText(sourceText, { exact: true })).toHaveCount(0);
});
}
await expectOwnerAccessRemoved(page);
await expectOwnerAccessRemoved(secondPage);
const revokedStatus = await page.evaluate(
async ({ orgId, id }) => {
const response = await fetch(`/api/v1/organizations/${orgId}/needs/${id}`, {
cache: "no-store",
});
return response.status;
},
{ orgId: organization.id, id: needId },
);
expect(revokedStatus).toBe(404);
const successorNeedResponse = successorPage.waitForResponse((response) =>
isResponse(response, "GET", itemPath, 200),
);
await successorPage.goto(
`/employer/needs/${needId}?organization_id=${encodeURIComponent(organization.id)}`,
);
await successorNeedResponse;
await expect(successorPage.getByLabel("Название потребности")).toHaveValue(
secondWindowDraft,
);
} finally {
await successorContext.close();
}
} finally {
await secondContext.close();
}
});
test("creates a manual need without source text and keeps recommendations pending", async ({
page,
}) => {
await registerVerifiedEmployer(page);
const suffix = crypto.randomUUID().slice(0, 8);
const organization = await createOrganization(page, `Manual need ${suffix}`);
const collectionPath = needCollectionPath(organization.id);
await page.goto(`/employer/needs/new?organization_id=${encodeURIComponent(organization.id)}`);
await expect(page.getByLabel("Название потребности")).toBeVisible();
await page.getByLabel("Название потребности").fill(`Manual Go developer ${suffix}`);
await expect(page.getByLabel("Описание работы")).toHaveValue("");
await page.getByLabel("Специализация").selectOption("backend");
await page.getByRole("radio", { name: "Junior", exact: true }).check();
await nextStep(page);
const requiredSkills = page
.getByRole("heading", { name: "Обязательные навыки" })
.locator("xpath=..");
await requiredSkills.getByLabel("Добавить навык").fill("Go");
await requiredSkills.getByRole("button", { name: "Добавить", exact: true }).click();
await nextStep(page);
const tasks = page.getByRole("heading", { name: "Задачи команды" }).locator("xpath=..");
await tasks.getByLabel("Добавить задачу").fill("Развивать сервис уведомлений");
await tasks.getByRole("button", { name: "Добавить", exact: true }).click();
await nextStep(page);
await page.getByLabel("От, рублей в месяц").fill("100000");
await page.getByLabel("До, рублей в месяц").fill("130000");
await page.getByRole("radio", { name: /После налога/ }).check();
await nextStep(page);
const createResponsePromise = page.waitForResponse((response) =>
isResponse(response, "POST", collectionPath, 201),
);
await page.getByRole("button", { name: "Создать потребность" }).click();
const createResponse = await createResponsePromise;
const createBody = createResponse.request().postDataJSON() as Record<string, unknown>;
expect(createBody).not.toHaveProperty("source_text");
expect(createBody).not.toHaveProperty("vacancy_id");
const created = (await createResponse.json()) as NeedResponse;
expect(created.source_text).toBeNull();
expect(created.requirements.specialization).toMatchObject({
status: "confirmed",
value: "backend",
source: { origin: "manual" },
});
expect(created.requirements.grade).toMatchObject({
status: "confirmed",
value: "junior",
source: { origin: "manual" },
});
expect(created.requirements.required_skills).toHaveLength(1);
expect(created.requirements.required_skills[0]).toMatchObject({
name: "Go",
status: "confirmed",
source: { origin: "manual" },
});
expect(created.requirements.tasks).toHaveLength(1);
expect(created.requirements.tasks[0]).toMatchObject({
text: "Развивать сервис уведомлений",
status: "confirmed",
source: { origin: "manual" },
});
expect(created.requirements.salary).toMatchObject({
status: "confirmed",
value: { tax_basis: "net" },
source: { origin: "manual" },
});
expect(created.recommendations).toMatchObject({ status: "pending", categories: [] });
expect(created.readiness.status).toBe("incomplete");
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
const detailPath = needPath(organization.id, created.id);
const reloadResponsePromise = page.waitForResponse((response) =>
isResponse(response, "GET", detailPath, 200),
);
await page.reload();
const reloadResponse = await reloadResponsePromise;
const persisted = (await reloadResponse.json()) as NeedResponse;
expect(persisted.source_text).toBeNull();
expect(persisted.requirements.grade.source?.origin).toBe("manual");
expect(persisted.requirements.required_skills[0]?.source?.origin).toBe("manual");
expect(persisted.requirements.salary.source?.origin).toBe("manual");
expect(persisted.recommendations).toMatchObject({ status: "pending", categories: [] });
await expect(page.getByText("Рекомендации пока не рассчитаны.", { exact: true })).toBeVisible();
});
});