Files
test-assignment/tests/tasks-dashboards.spec.ts

361 lines
15 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { createHash, randomBytes } from 'node:crypto';
import { test, expect, type Page } from '@playwright/test';
import { createDatabase } from '../packages/database/dist/index.js';
if (!process.env.DATABASE_URL?.endsWith('/merchantflow_test'))
throw new Error('Isolated database required');
const db = createDatabase(process.env.DATABASE_URL);
const ids: string[] = [];
const sessions: string[] = [];
test.afterEach(async () => {
await db.merchant.deleteMany({ where: { id: { in: ids } } });
ids.length = 0;
await db.session.deleteMany({ where: { id: { in: sessions } } });
sessions.length = 0;
});
test.afterAll(() => db.$disconnect());
// These journeys exercise SessionGuard using real isolated-database sessions.
// Login and throttling already have dedicated coverage; repeated setup must not exhaust them.
async function login(page: Page, account = 'head') {
const user = await db.user.findUniqueOrThrow({
where: { email: `${account}@merchantflow.test` },
});
const token = randomBytes(32).toString('hex');
const id = createHash('sha256').update(token).digest('hex');
sessions.push(id);
await db.session.create({
data: { id, userId: user.id, expiresAt: new Date(Date.now() + 8 * 3600000) },
});
await page.context().addCookies([
{
name: 'mf_session',
value: token,
domain: '127.0.0.1',
path: '/api',
httpOnly: true,
sameSite: 'Lax',
},
]);
await page.goto('/app');
await expect(page).toHaveURL(/\/app$/);
await expect(page.locator('h1')).toBeVisible();
}
async function save(page: Page) {
await page
.getByRole('dialog')
.getByRole('button', { name: /^(Save changes|Сохранить изменения)$/ })
.click();
await expect(page.getByRole('dialog')).not.toBeVisible();
}
async function localInput(page: Page, ms: number) {
return page.evaluate((time) => {
const date = new Date(time);
return new Date(time - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
}, ms);
}
async function inbox(page: Page) {
await page.getByRole('button', { name: /^(Reminders|Напоминания)( \(\d+\))?$/ }).click();
await expect(page.getByRole('dialog')).toBeVisible();
await expect(page.getByRole('dialog')).toHaveCSS('opacity', '1');
return page.getByRole('dialog');
}
for (const language of ['en', 'ru'])
for (const width of [390, 1440])
test.describe(`tasks and dashboards ${language} ${width}`, () => {
test.use({ viewport: { width, height: 1000 }, timezoneId: 'America/New_York' });
test('tasks work from both entry points and reminder dismissal survives reload', async ({
page,
}, info) => {
await page.addInitScript(
(lang) => localStorage.setItem('merchantflow.language', lang),
language,
);
const id = `browser-tasks-${language}-${width}`;
ids.push(id);
await db.merchant.create({
data: {
id,
name: `Task merchant ${language} ${width}`,
contactName: 'Contact',
contactEmail: '[email protected]',
},
});
await login(page);
await page.goto('/app/tasks');
await page.getByRole('button', { name: /^(Add task|Добавить задачу)$/ }).click();
await page
.getByRole('dialog')
.getByLabel(/Search merchants|Поиск мерчантов/)
.fill(`Task merchant ${language} ${width}`);
await page
.getByRole('dialog')
.getByRole('button', { name: `Task merchant ${language} ${width}`, exact: true })
.click();
const title = `Follow up ${language} ${width}`,
edited = title + ' edited';
await page
.getByRole('dialog')
.getByLabel(/^(Task title|Название задачи)$/)
.fill(title);
const due = await localInput(page, Date.now() + 2 * 86400000),
reminder = await localInput(page, Date.now() - 3600000);
await page
.getByRole('dialog')
.getByLabel(/^(Due date and time|Дата и время выполнения)$/)
.fill(due);
await page
.getByRole('dialog')
.getByLabel(/^(Reminder date and time|Дата и время напоминания)$/)
.fill(reminder);
await page.screenshot({ path: info.outputPath('task-editor.png'), fullPage: true });
await save(page);
const task = await db.task.findFirstOrThrow({ where: { merchantId: id } });
const utc = await page.evaluate((value) => new Date(value).toISOString(), due);
expect(task.dueAt.toISOString()).toBe(utc);
await page.getByRole('button', { name: /^(Upcoming|Предстоящие)$/ }).click();
const row = page.locator(`#task-${task.id}`);
await expect(row).toBeVisible();
await row.getByRole('button', { name: /^(Edit task|Изменить задачу)$/ }).click();
await page
.getByRole('dialog')
.getByLabel(/^(Task title|Название задачи)$/)
.fill(edited);
await save(page);
await expect(row).toContainText(edited);
let dialog = await inbox(page);
await expect(dialog.getByText(edited, { exact: true })).toBeVisible();
await page.keyboard.press('Escape');
await page.goto(`/app/merchants/${id}?tab=tasks`);
await row.getByRole('button', { name: /^(Complete task|Выполнить задачу)$/ }).click();
await expect(
row.getByRole('button', { name: /Reopen task|Открыть задачу снова/ }),
).toBeVisible();
dialog = await inbox(page);
await expect(dialog.getByText(edited, { exact: true })).toHaveCount(0);
await page.keyboard.press('Escape');
await row.getByRole('button', { name: /Reopen task|Открыть задачу снова/ }).click();
await expect(
row.getByRole('button', { name: /^(Complete task|Выполнить задачу)$/ }),
).toBeVisible();
dialog = await inbox(page);
await expect(dialog.getByText(edited, { exact: true })).toBeVisible();
await dialog
.locator('div.border-b')
.filter({ has: page.getByText(edited, { exact: true }) })
.getByRole('button', { name: /Dismiss reminder|Скрыть напоминание/ })
.click();
await expect(dialog.getByText(edited, { exact: true })).toHaveCount(0);
await page.reload();
dialog = await inbox(page);
await expect(dialog.getByText(edited, { exact: true })).toHaveCount(0);
await page.keyboard.press('Escape');
await row.getByRole('button', { name: /^(Edit task|Изменить задачу)$/ }).click();
await page
.getByRole('dialog')
.getByLabel(/^(Due date and time|Дата и время выполнения)$/)
.fill(await localInput(page, Date.now() - 1800000));
await page
.getByRole('dialog')
.getByLabel(/^(Reminder date and time|Дата и время напоминания)$/)
.fill(await localInput(page, Date.now() - 7200000));
await save(page);
dialog = await inbox(page);
await expect(dialog.getByText(edited, { exact: true })).toBeVisible();
await page.screenshot({ path: info.outputPath('reminder-inbox.png'), fullPage: true });
await page.keyboard.press('Escape');
await page.getByRole('button', { name: /^(Add task|Добавить задачу)$/ }).click();
await page
.getByRole('dialog')
.getByLabel(/^(Task title|Название задачи)$/)
.fill('Created from merchant');
await save(page);
await page.goto(`/app/tasks?merchantId=${id}&filter=TODAY`);
await expect(row).toBeVisible();
await page.getByRole('button', { name: /^(Overdue|Просроченные)$/ }).click();
await expect(row).toBeVisible();
await row.getByRole('button', { name: /^(Complete task|Выполнить задачу)$/ }).click();
await expect(row).toHaveCount(0);
await page.getByRole('button', { name: /^(Completed|Выполненные)$/ }).click();
await expect(row).toBeVisible();
await row.getByRole('button', { name: /Reopen task|Открыть задачу снова/ }).click();
await expect(row).toHaveCount(0);
await page.goBack();
await expect(page).toHaveURL(/filter=OVERDUE/);
await expect(row).toBeVisible();
await page.reload();
await expect(row).toBeVisible();
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(
true,
);
await page.screenshot({ path: info.outputPath('tasks.png'), fullPage: true });
});
test('role dashboards have scoped metrics and working filtered links', async ({
page,
}, info) => {
await page.addInitScript(
(lang) => localStorage.setItem('merchantflow.language', lang),
language,
);
for (const account of ['head', 'alex', 'compliance']) {
await login(page, account);
await expect(page.locator('h1')).toHaveText(
account === 'head'
? /Portfolio overview|Обзор портфеля/
: account === 'alex'
? /My merchant workspace|Мои мерчанты/
: /Review workspace|Проверки комплаенса/,
);
await expect(
page.getByRole('heading', { name: /Activation rate|Доля активации/ }),
).toBeVisible();
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
).toBe(true);
await page.screenshot({
path: info.outputPath(`${account}-dashboard.png`),
fullPage: true,
animations: 'disabled',
});
if (account === 'compliance') {
await page
.getByRole('link')
.filter({
has: page.getByRole('heading', { name: /Decisions · 30 days|Решения · 30 дней/ }),
})
.click();
await expect(page).toHaveURL(/view=DECISIONS/);
await expect(page.locator('h1')).toHaveText(/Decision history|История решений/);
} else {
await page
.getByRole('link')
.filter({
has: page.getByRole('heading', {
name: /Active onboarding|Активный онбординг/,
exact: true,
}),
})
.click();
await expect(page).toHaveURL(/cohort=ACTIVE_ONBOARDING/);
}
await page.reload();
await expect(page.getByRole('alert')).toHaveCount(0);
if (width < 1024)
await page.getByRole('button', { name: /Open navigation|Открыть навигацию/ }).click();
await page.getByRole('button', { name: /Sign out|Выйти/, exact: true }).click();
await expect(page).toHaveURL(/login/);
}
});
});
test('reminders arrive through polling and focus, survive failures, and respect revision changes', async ({
page,
}) => {
const id = 'browser-tasks-refresh';
ids.push(id);
await db.merchant.create({
data: {
id,
name: 'Refresh task merchant',
contactName: 'Test',
contactEmail: '[email protected]',
},
});
await login(page);
const now = Date.now();
const task = await db.task.create({
data: {
merchantId: id,
assigneeId: 'user-head',
title: 'Focus reminder',
dueAt: new Date(now + 3600000),
remindAt: new Date(now + 1800000),
},
});
let dialog = await inbox(page);
await expect(dialog.getByText(task.title, { exact: true })).toHaveCount(0);
await page.keyboard.press('Escape');
await page.clock.install();
await db.task.update({
where: { id: task.id },
data: { remindAt: new Date(now - 1000), reminderRevision: { increment: 1 } },
});
await page.clock.fastForward(31000);
await expect(page.getByRole('button', { name: /^Reminders \([1-9]\d*\)$/ })).toBeVisible();
dialog = await inbox(page);
await expect(dialog.getByText(task.title, { exact: true })).toBeVisible();
await page.keyboard.press('Escape');
await db.task.update({ where: { id: task.id }, data: { status: 'DONE' } });
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
dialog = await inbox(page);
await expect(dialog.getByText(task.title, { exact: true })).toHaveCount(0);
await page.route('**/api/reminders', (route) =>
route.fulfill({ status: 503, json: { code: 'DATABASE_UNAVAILABLE' } }),
);
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.clock.fastForward(3000);
await expect(
dialog.getByText('The workspace database is unavailable. Please try again.'),
).toBeVisible();
await expect(dialog.getByText('You’re all caught up', { exact: true })).toHaveCount(0);
await page.unroute('**/api/reminders');
await dialog.getByRole('button', { name: 'Try again' }).click();
await expect(
dialog.getByText('The workspace database is unavailable. Please try again.'),
).toHaveCount(0);
});
test('title-only edits preserve precise reminder instants, and conflicts retain unsaved values', async ({
page,
}) => {
const id = 'browser-tasks-conflict';
ids.push(id);
await db.merchant.create({
data: {
id,
name: 'Task conflict merchant',
contactName: 'Test',
contactEmail: '[email protected]',
},
});
const remindAt = new Date(Date.now() - 3600123),
dueAt = new Date(Date.now() + 8640456);
const task = await db.task.create({
data: {
merchantId: id,
assigneeId: 'user-head',
title: 'Keep exact reminder',
dueAt,
remindAt,
reminderDismissedAt: new Date(),
},
});
await login(page);
await page.goto(`/app/merchants/${id}?tab=tasks`);
const row = page.locator(`#task-${task.id}`);
await row.getByRole('button', { name: 'Edit task', exact: true }).click();
await page
.getByRole('dialog')
.getByLabel('Task title', { exact: true })
.fill('Keep unsaved title');
await db.merchant.update({ where: { id }, data: { version: { increment: 1 } } });
await page.getByRole('dialog').getByRole('button', { name: 'Save changes', exact: true }).click();
await expect(page.getByRole('dialog').getByRole('alert')).toBeVisible();
await expect(page.getByRole('dialog').getByLabel('Task title', { exact: true })).toHaveValue(
'Keep unsaved title',
);
expect((await db.task.findUniqueOrThrow({ where: { id: task.id } })).title).toBe(
'Keep exact reminder',
);
await page.getByRole('dialog').getByRole('button', { name: 'Load current version' }).click();
await expect(
page.getByText('Current version loaded. Review your changes before saving.'),
).toBeVisible();
await save(page);
const updated = await db.task.findUniqueOrThrow({ where: { id: task.id } });
expect(updated.remindAt!.toISOString()).toBe(remindAt.toISOString());
expect(updated.dueAt.toISOString()).toBe(dueAt.toISOString());
expect(updated.reminderDismissedAt).not.toBeNull();
expect(updated.reminderRevision).toBe(0);
const dialog = await inbox(page);
await expect(dialog.getByText('Keep unsaved title', { exact: true })).toHaveCount(0);
});