Files
lincodex/frontend/e2e/notifications.spec.ts
T

321 lines
15 KiB
TypeScript

import { expect, test, type BrowserContext, type Page } from "@playwright/test";
type InboxMessage = { id?: string; text?: string; html?: string };
type ApiResult = { status: number; body: unknown };
type NotificationBody = {
id: string;
read_at: string | null;
content: { title: string; summary: string } | null;
};
type NotificationPageBody = { items: NotificationBody[] };
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1";
const password = "correct horse battery staple 2026";
const deliveryTimeoutMs = 60_000;
test.use({ trace: "off", screenshot: "off", video: "off" });
// Each test registers several accounts and waits for the event to travel
// through the relay and the bus, which a loaded stand makes slow.
test.setTimeout(120_000);
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 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 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<string> {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
const message = (await readInbox(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.");
}
type Account = { email: string; userId: string };
// Registers, confirms, and signs in a synthetic account. Employer addresses
// follow the pattern that the company fixture accepts.
async function createAccount(page: Page, scenario: "candidate" | "employer"): Promise<Account> {
const suffix = crypto.randomUUID().replaceAll("-", "").slice(0, 8);
const email =
scenario === "employer" ? `company-${suffix}@example.test` : `inbox-${suffix}@example.test`;
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);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
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 loginResponse = 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();
const session = (await (await loginResponse).json()) as { account: { id: string } };
return { email, userId: session.account.id };
}
// 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<ApiResult> {
return page.evaluate(
async ({ method, path, body }) => {
const headers: Record<string, string> = {};
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 },
);
}
async function createOrganization(page: Page, name: string): Promise<string> {
const suffix = crypto.randomUUID().slice(0, 8);
const created = await api(page, "POST", "/api/v1/organizations", {
name,
contacts: {
website: `https://notice-${suffix}.example.test`,
email: `careers@notice-${suffix}.example.test`,
phone: "+12025550123",
telegram: "@noticeinbox",
},
});
expect(created.status).toBe(201);
return (created.body as { id: string }).id;
}
async function fixture(path: string, body: unknown): Promise<{ status: number; body: unknown }> {
const origin = process.env.E2E_COMPANY_FIXTURE_URL;
const token = process.env.E2E_COMPANY_FIXTURE_TOKEN;
if (!origin || !token) throw new Error("The local company fixture is not configured.");
const response = await fetch(new URL(path, origin), {
method: "POST",
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
body: JSON.stringify(body),
});
return { status: response.status, body: await response.json().catch(() => null) };
}
async function publishNotice(recipientUserId: string, organizationId: string): Promise<string> {
const published = await fixture("/notifications/synthetic", {
recipient_user_id: recipientUserId,
organization_id: organizationId,
});
expect(published.status).toBe(201);
return (published.body as { event_id: string }).event_id;
}
// The event travels through the real outbox, relay, event bus, and consumer,
// so the item appears after a delay; the page is read again until it does.
async function waitForItems(page: Page, path: string, count: number): Promise<void> {
await page.goto(path);
await expect(async () => {
await page.reload();
await expect(page.getByRole("list", { name: "Уведомления" }).getByRole("listitem")).toHaveCount(
count,
{ timeout: 2_000 },
);
}).toPass({ timeout: deliveryTimeoutMs, intervals: [500, 1_000, 2_000] });
}
async function newPage(context: BrowserContext): Promise<Page> {
return context.newPage();
}
test.describe("internal notifications", () => {
test.skip(
!mailFixtureEnabled || !companyFixtureEnabled,
"Requires the isolated mail and company fixtures.",
);
test("a candidate reads, marks, and loses the content of one delivered-twice event", async ({
browser,
page,
}) => {
const context = (): Promise<BrowserContext> =>
browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
const senderContext = await context();
const otherContext = await context();
try {
const sender = await newPage(senderContext);
await createAccount(sender, "employer");
const organizationName = `Север ${crypto.randomUUID().slice(0, 6)}`;
const organizationId = await createOrganization(sender, organizationName);
const candidate = await createAccount(page, "candidate");
await page.goto("/candidate/notifications");
await expect(page.getByRole("heading", { name: "Уведомления", level: 1 })).toBeVisible();
await expect(page.getByText("Уведомлений пока нет")).toBeVisible();
const eventId = await publishNotice(candidate.userId, organizationId);
await waitForItems(page, "/candidate/notifications", 1);
// The real consumer already stored the event. A second delivery by the
// same consumer and a third by a renamed one still leave one item.
const replay = await fixture("/notifications/synthetic/replay", { event_id: eventId });
expect(replay.status).toBe(200);
expect(replay.body).toEqual({ primary_applied: false, renamed_applied: true });
await page.reload();
const items = page.getByRole("list", { name: "Уведомления" }).getByRole("listitem");
await expect(items).toHaveCount(1);
await expect(items.first()).toContainText(organizationName);
await expect(items.first()).toContainText("Не прочитано");
// The mark is reachable and operable from the keyboard.
const mark = items.first().getByRole("button", { name: /Отметить прочитанным/ });
await mark.focus();
await expect(mark).toBeFocused();
await page.keyboard.press("Enter");
await expect(items.first()).toContainText("Прочитано");
await expect(items.first()).not.toContainText("Не прочитано");
await expect(items.first().getByRole("button")).toHaveCount(0);
await expect(items.first().getByRole("heading", { level: 2 })).toBeFocused();
await expect(
page.getByRole("status").filter({ hasText: "отмечено прочитанным" }),
).toBeAttached();
// The read state is stored on the server.
await page.reload();
await expect(items).toHaveCount(1);
await expect(items.first()).toContainText("Прочитано");
await expect(items.first().getByRole("button")).toHaveCount(0);
// Another candidate neither lists nor marks the same ID.
const other = await newPage(otherContext);
await createAccount(other, "candidate");
const otherList = await api(other, "GET", "/api/v1/me/notifications");
expect(otherList.status).toBe(200);
expect((otherList.body as NotificationPageBody).items).toHaveLength(0);
const otherMark = await api(other, "POST", `/api/v1/me/notifications/${eventId}/read`);
expect(otherMark.status).toBe(404);
await other.goto("/candidate/notifications");
await expect(other.getByText("Уведомлений пока нет")).toBeVisible();
// An employer account gets no candidate inbox.
const employerRead = await api(sender, "GET", "/api/v1/me/notifications");
expect(employerRead.status).toBe(403);
// After the candidate hides the organization the item stays, but its
// text is gone from the next read and from the page.
const hidden = await fixture("/notifications/synthetic/hide-organization", {
recipient_user_id: candidate.userId,
organization_id: organizationId,
});
expect(hidden.status).toBe(204);
await page.reload();
await expect(items).toHaveCount(1);
await expect(items.first()).toContainText("Содержимое больше недоступно");
await expect(items.first()).toContainText("Прочитано");
await expect(page.getByText(organizationName)).toHaveCount(0);
const hiddenRead = await api(page, "GET", "/api/v1/me/notifications");
expect((hiddenRead.body as NotificationPageBody).items[0]?.content).toBeNull();
} finally {
await senderContext.close();
await otherContext.close();
}
});
test("an employer reads the organization inbox until the membership is revoked", async ({
browser,
page,
}) => {
const successorContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
try {
const owner = await createAccount(page, "employer");
const organizationName = `Юг ${crypto.randomUUID().slice(0, 6)}`;
const organizationId = await createOrganization(page, organizationName);
const successorPage = await newPage(successorContext);
const successor = await createAccount(successorPage, "employer");
const eventId = await publishNotice(owner.userId, organizationId);
await waitForItems(page, "/employer/notifications", 1);
await expect(page.getByRole("heading", { name: "Уведомления", level: 1 })).toBeVisible();
const items = page.getByRole("list", { name: "Уведомления" }).getByRole("listitem");
await expect(items.first()).toContainText(organizationName);
await items
.first()
.getByRole("button", { name: /Отметить прочитанным/ })
.click();
await expect(items.first()).toContainText("Прочитано");
await page.reload();
await expect(items.first()).toContainText("Прочитано");
await expect(items.first().getByRole("button")).toHaveCount(0);
// A non-member gets the same answer as for an unknown organization.
const listPath = `/api/v1/organizations/${organizationId}/notifications`;
expect((await api(successorPage, "GET", listPath)).status).toBe(404);
expect((await api(successorPage, "POST", `${listPath}/${eventId}/read`)).status).toBe(404);
const revoked = await fixture("/company/memberships/revoke", {
organization_id: organizationId,
user_id: owner.userId,
successor_user_id: successor.userId,
});
expect(revoked.status).toBe(204);
// The same ID after the revocation: refusal, and no content in the page.
expect((await api(page, "GET", listPath)).status).toBe(404);
expect((await api(page, "POST", `${listPath}/${eventId}/read`)).status).toBe(404);
await page.goto(`/employer/notifications?organization_id=${organizationId}`);
await expect(page.getByText("Компаний пока нет")).toBeVisible();
await expect(page.getByText(organizationName)).toHaveCount(0);
// The new owner sees the organization inbox, not the item of the former
// owner, and cannot mark it.
const successorList = await api(successorPage, "GET", listPath);
expect(successorList.status).toBe(200);
expect((successorList.body as NotificationPageBody).items).toHaveLength(0);
expect((await api(successorPage, "POST", `${listPath}/${eventId}/read`)).status).toBe(404);
} finally {
await successorContext.close();
}
});
});