319 lines
15 KiB
TypeScript
319 lines
15 KiB
TypeScript
import { selectOption } from './helpers/select';
|
||
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('Daily sales browser tests require the isolated database');
|
||
const db = createDatabase(process.env.DATABASE_URL);
|
||
const names = new Set<string>();
|
||
const sessions = new Set<string>();
|
||
test.afterEach(async () => {
|
||
await db.merchant.deleteMany({ where: { name: { in: [...names] } } });
|
||
names.clear();
|
||
await db.session.deleteMany({ where: { id: { in: [...sessions] } } });
|
||
sessions.clear();
|
||
});
|
||
test.afterAll(() => db.$disconnect());
|
||
async function login(page: Page, account = 'head') {
|
||
await page.goto('/login');
|
||
await page.getByLabel(/Email address|Электронная почта/).fill(`${account}@merchantflow.test`);
|
||
await page.getByLabel(/^Password$|^Пароль$/).fill('MerchantFlow123!');
|
||
await page
|
||
.getByRole('button', { name: /^Sign in to workspace$|^Войти в рабочее пространство$/ })
|
||
.click();
|
||
await expect(page).toHaveURL(/\/app$/);
|
||
}
|
||
async function save(page: Page) {
|
||
await page
|
||
.getByRole('dialog')
|
||
.getByRole('button', { name: /^(Save changes|Сохранить изменения)$/ })
|
||
.click();
|
||
await expect(page.getByRole('dialog')).not.toBeVisible();
|
||
}
|
||
async function create(page: Page, name: string) {
|
||
names.add(name);
|
||
await page.goto('/app/merchants');
|
||
await page.getByRole('button', { name: /^(Add merchant|Добавить мерчанта)$/ }).click();
|
||
const dialog = page.getByRole('dialog');
|
||
await dialog.getByLabel(/^(Company name|Название компании)$/).fill(name);
|
||
await dialog.getByLabel(/^(Primary contact|Основной контакт)$/).fill(`Contact ${name}`);
|
||
await dialog.getByLabel(/^(Contact email|Email контакта)$/).fill('[email protected]');
|
||
await save(page);
|
||
await expect(page.locator('h1')).toHaveText(name);
|
||
return new URL(page.url()).pathname.split('/').at(-1)!;
|
||
}
|
||
async function noOverflow(page: Page) {
|
||
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
|
||
}
|
||
|
||
for (const language of ['en', 'ru'])
|
||
for (const width of [390, 1440]) {
|
||
test.describe(`daily sales ${language} ${width}`, () => {
|
||
test.use({ viewport: { width, height: 1000 } });
|
||
test('creation, filters, history, pipeline actions and rejection use persistent API data', async ({
|
||
page,
|
||
}, info) => {
|
||
const errors: string[] = [];
|
||
page.on('pageerror', (error) => errors.push(error.message));
|
||
await page.addInitScript(
|
||
(locale) => localStorage.setItem('merchantflow.language', locale),
|
||
language,
|
||
);
|
||
await login(page);
|
||
const name = `Daily workspace ${language} ${width}`;
|
||
const id = await create(page, name);
|
||
await expect(
|
||
page.getByText(/Assign a manager before progressing|Назначьте менеджера для перехода/),
|
||
).toBeVisible();
|
||
await expect(
|
||
page.getByText(/Log a call or email before|Запишите звонок или письмо/),
|
||
).toBeVisible();
|
||
await page.getByRole('button', { name: /^(Assign manager|Назначить менеджера)$/ }).click();
|
||
await selectOption(
|
||
page.getByRole('dialog').getByLabel(/^(Account manager|Аккаунт-менеджер)$/),
|
||
'user-manager1',
|
||
);
|
||
await save(page);
|
||
await page.getByRole('tab', { name: /^(Activity|Активность)$/ }).click();
|
||
await page
|
||
.getByRole('button', { name: /^(Log interaction|Добавить взаимодействие)$/ })
|
||
.click();
|
||
await selectOption(
|
||
page.getByRole('dialog').getByLabel(/^(Interaction type|Тип взаимодействия)$/),
|
||
'CALL',
|
||
);
|
||
await page
|
||
.getByRole('dialog')
|
||
.getByLabel(/^(Details|Подробности)$/)
|
||
.fill('A real discovery call recorded through the API.');
|
||
await save(page);
|
||
await expect(
|
||
page.getByText('A real discovery call recorded through the API.', { exact: true }),
|
||
).toBeVisible();
|
||
await expect(
|
||
page.getByText(
|
||
/Manager changed: Unassigned → Alex Morgan|Менеджер изменён: Не назначен → Alex Morgan/,
|
||
),
|
||
).toBeVisible();
|
||
await page.reload();
|
||
await expect(page.getByRole('tab', { name: /^(Activity|Активность)$/ })).toHaveAttribute(
|
||
'aria-selected',
|
||
'true',
|
||
);
|
||
const activityTab = page.getByRole('tab', { name: /^(Activity|Активность)$/ });
|
||
await activityTab.focus();
|
||
await activityTab.press('End');
|
||
await expect(page.getByRole('tab', { name: /^(Tasks|Задачи)$/ })).toHaveAttribute(
|
||
'aria-selected',
|
||
'true',
|
||
);
|
||
await page.getByRole('tab', { name: /^(Tasks|Задачи)$/ }).press('Home');
|
||
await expect(page.getByRole('tab', { name: /^(Overview|Обзор)$/ })).toHaveAttribute(
|
||
'aria-selected',
|
||
'true',
|
||
);
|
||
await page.getByRole('tab', { name: /^(Overview|Обзор)$/ }).press('ArrowRight');
|
||
await expect(activityTab).toBeFocused();
|
||
await page.getByRole('button', { name: /^(Edit merchant|Изменить мерчанта)$/ }).click();
|
||
const dialog = page.getByRole('dialog');
|
||
await dialog.getByLabel(/^(Website|Сайт)$/).fill('https://daily.example.test');
|
||
await dialog.getByLabel(/^(Country code|Код страны)$/).fill('GB');
|
||
await selectOption(dialog.getByLabel(/^(Industry|Отрасль)$/), 'OTHER');
|
||
await dialog
|
||
.getByLabel(/^(Estimated monthly processing \(USD\)|Месячный объём обработки \(USD\))$/)
|
||
.fill('0');
|
||
await save(page);
|
||
await page.goto('/app/merchants');
|
||
await page
|
||
.getByRole('textbox', { name: /Search merchants|Название мерчанта/ })
|
||
.fill(`Contact ${name}`);
|
||
await selectOption(
|
||
page.getByRole('combobox', { name: /^(All countries|Все страны)$/ }),
|
||
'GB',
|
||
);
|
||
await selectOption(
|
||
page.getByRole('combobox', { name: /^(All industries|Все отрасли)$/ }),
|
||
'OTHER',
|
||
);
|
||
await selectOption(
|
||
page.getByRole('combobox', { name: /^(All managers|Все менеджеры)$/ }),
|
||
'user-manager1',
|
||
);
|
||
await expect(page).toHaveURL(/country=GB.*industry=OTHER.*ownerId=user-manager1/);
|
||
await expect(page.getByRole('link', { name: new RegExp(name) }).first()).toBeVisible();
|
||
await noOverflow(page);
|
||
await page.screenshot({ path: info.outputPath('daily-directory.png'), fullPage: true });
|
||
const directory = page.url();
|
||
await page
|
||
.getByRole('link', { name: new RegExp(name) })
|
||
.first()
|
||
.click();
|
||
await page.getByRole('tab', { name: /^(Activity|Активность)$/ }).click();
|
||
await page.getByRole('link', { name: /Back to merchants|К списку мерчантов/ }).click();
|
||
await expect(page).toHaveURL(directory);
|
||
await page.reload();
|
||
await expect(
|
||
page.getByRole('textbox', { name: /Search merchants|Название мерчанта/ }),
|
||
).toHaveValue(`Contact ${name}`);
|
||
await page.goto(`${directory}&page=9999`);
|
||
await expect(page).not.toHaveURL(/page=/);
|
||
await page.goto('/app/pipeline?stage=NEW_LEAD');
|
||
const card = page
|
||
.locator('article')
|
||
.filter({ has: page.getByRole('link', { name: new RegExp(name) }) });
|
||
await card.getByRole('button', { name: /Move to Contacted|Перевести: Контакт/ }).click();
|
||
await expect
|
||
.poll(async () => (await (await page.request.get(`/api/merchants/${id}`)).json()).status)
|
||
.toBe('CONTACTED');
|
||
if (width === 390) await selectOption(page.getByRole('combobox'), 'CONTACTED');
|
||
const contactedCard = page
|
||
.getByRole('region', {
|
||
name: language === 'en' ? 'Contacted' : 'Контакт установлен',
|
||
exact: true,
|
||
})
|
||
.locator('article')
|
||
.filter({ has: page.getByRole('link', { name: new RegExp(name) }) });
|
||
await expect(contactedCard).toBeVisible();
|
||
await contactedCard.getByRole('link', { name: new RegExp(name) }).click();
|
||
await expect(page).toHaveURL(new RegExp(`/app/merchants/${id}$`));
|
||
await expect(page.locator('h1')).toHaveText(name);
|
||
await page
|
||
.getByRole('button', { name: /Move to Qualified|Перевести: Квалифицирован/ })
|
||
.click();
|
||
await expect
|
||
.poll(async () => (await (await page.request.get(`/api/merchants/${id}`)).json()).status)
|
||
.toBe('QUALIFIED');
|
||
await page.getByRole('button', { name: /^(Reject merchant|Отклонить мерчанта)$/ }).click();
|
||
await page
|
||
.getByRole('dialog')
|
||
.getByRole('button', { name: /Save changes|Сохранить изменения/ })
|
||
.click();
|
||
await expect(
|
||
page.getByRole('dialog').getByLabel(/Rejection reason|Причина отклонения/),
|
||
).toHaveAttribute('aria-invalid', 'true');
|
||
await page
|
||
.getByRole('dialog')
|
||
.getByLabel(/Rejection reason|Причина отклонения/)
|
||
.fill('Commercial terms were declined.');
|
||
await save(page);
|
||
await expect(page.getByText(/This is a final stage|Это финальный этап/)).toBeVisible();
|
||
await page.getByRole('tab', { name: /^(Activity|Активность)$/ }).click();
|
||
await expect(
|
||
page.getByText('Commercial terms were declined.', { exact: true }),
|
||
).toBeVisible();
|
||
await page.screenshot({ path: info.outputPath('daily-history.png'), fullPage: true });
|
||
await page.goto('/app/pipeline?stage=REJECTED');
|
||
await expect(card).toBeVisible();
|
||
if (width === 390)
|
||
expect(await page.locator('section[aria-label]:visible').count()).toBe(1);
|
||
await noOverflow(page);
|
||
await page.screenshot({ path: info.outputPath('daily-pipeline.png'), fullPage: true });
|
||
expect(errors).toEqual([]);
|
||
});
|
||
});
|
||
}
|
||
|
||
test('manager creation assigns self and stale edits keep unsaved form values', async ({ page }) => {
|
||
await login(page, 'alex');
|
||
const id = await create(page, 'Daily workspace manager');
|
||
const merchant = await (await page.request.get(`/api/merchants/${id}`)).json();
|
||
expect(merchant.owner.id).toBe('user-manager1');
|
||
await expect(page.getByRole('button', { name: 'Assign manager', exact: true })).toHaveCount(0);
|
||
await page.getByRole('button', { name: 'Edit merchant', exact: true }).click();
|
||
await page.getByRole('dialog').getByLabel('Contact title', { exact: true }).fill('Unsaved title');
|
||
const concurrent = await page.request.post(`/api/merchants/${id}/activities`, {
|
||
headers: { origin: 'http://127.0.0.1:5174' },
|
||
data: { version: merchant.version, kind: 'NOTE', text: 'Concurrent update' },
|
||
});
|
||
expect(concurrent.ok()).toBe(true);
|
||
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('Contact title', { exact: true })).toHaveValue(
|
||
'Unsaved title',
|
||
);
|
||
await save(page);
|
||
await expect(page.getByText('Unsaved title', { exact: true })).toBeVisible();
|
||
await page.goto('/app/merchants?ownerId=user-manager2');
|
||
await expect(page).not.toHaveURL(/ownerId/);
|
||
await expect(page.getByRole('combobox', { name: 'All managers' })).toHaveCount(0);
|
||
await page.getByRole('button', { name: 'Sign out', exact: true }).click();
|
||
await login(page, 'sam');
|
||
expect((await page.request.get(`/api/merchants/${id}`)).status()).toBe(404);
|
||
await page.getByRole('button', { name: 'Sign out', exact: true }).click();
|
||
await login(page, 'compliance');
|
||
await page.goto('/app/merchants');
|
||
await expect(page.getByRole('button', { name: 'Add merchant', exact: true })).toHaveCount(0);
|
||
});
|
||
|
||
for (const width of [390, 1440]) {
|
||
test(`custom dropdown keyboard navigation and merchant page sizes at ${width}px`, async ({
|
||
page,
|
||
}) => {
|
||
await page.setViewportSize({ width, height: 1000 });
|
||
// Login has dedicated coverage; these checks must not exhaust its rate limit.
|
||
const user = await db.user.findUniqueOrThrow({ where: { email: '[email protected]' } });
|
||
const token = randomBytes(32).toString('hex');
|
||
const id = createHash('sha256').update(token).digest('hex');
|
||
sessions.add(id);
|
||
await db.session.create({
|
||
data: { id, userId: user.id, expiresAt: new Date(Date.now() + 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/merchants');
|
||
const size = page.getByRole('combobox', { name: 'Show per page' });
|
||
await expect(size).toHaveText('10');
|
||
await expect(page.locator('select:visible')).toHaveCount(0);
|
||
await page.getByRole('button', { name: 'Next', exact: true }).click();
|
||
await expect(page).toHaveURL(/page=2/);
|
||
for (const count of [20, 30, 10]) {
|
||
const response = page.waitForResponse((response) => {
|
||
const url = new URL(response.url());
|
||
return (
|
||
url.pathname === '/api/merchants' && url.searchParams.get('pageSize') === String(count)
|
||
);
|
||
});
|
||
await selectOption(size, String(count));
|
||
const result = await (await response).json();
|
||
expect(result.page).toBe(1);
|
||
expect(result.pageSize).toBe(count);
|
||
expect(result.items).toHaveLength(Math.min(count, result.total));
|
||
await expect(
|
||
page.getByText(`1–${Math.min(count, result.total)} of ${result.total} merchants`, {
|
||
exact: true,
|
||
}),
|
||
).toBeVisible();
|
||
expect(new URL(page.url()).searchParams.has('page')).toBe(false);
|
||
await noOverflow(page);
|
||
}
|
||
await selectOption(size, '20');
|
||
await page.reload();
|
||
await expect(size).toHaveText('20');
|
||
const stage = page.getByRole('combobox', { name: 'Filter by stage' });
|
||
await stage.focus();
|
||
await stage.press('ArrowDown');
|
||
await expect(page.getByRole('listbox')).toBeVisible();
|
||
await expect(page.getByRole('option', { name: 'All stages', exact: true })).toBeFocused();
|
||
await page.keyboard.press('End');
|
||
await expect(page.getByRole('option', { name: 'Rejected', exact: true })).toBeFocused();
|
||
await page.keyboard.press('Enter');
|
||
await expect(stage).toHaveText('Rejected');
|
||
await expect(stage).toBeFocused();
|
||
await expect(page).toHaveURL(/status=REJECTED/);
|
||
await stage.press('ArrowDown');
|
||
await page.keyboard.press('Escape');
|
||
await expect(page.getByRole('listbox')).not.toBeVisible();
|
||
await expect(stage).toBeFocused();
|
||
await expect(stage).toHaveText('Rejected');
|
||
});
|
||
}
|