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(); test.afterEach(async () => { await db.merchant.deleteMany({ where: { name: { in: [...names] } } }); names.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('daily@sales.test'); 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 page .getByRole('dialog') .getByLabel(/^(Account manager|Аккаунт-менеджер)$/) .selectOption('user-manager1'); await save(page); await page.getByRole('tab', { name: /^(Activity|Активность)$/ }).click(); await page .getByRole('button', { name: /^(Log interaction|Добавить взаимодействие)$/ }) .click(); await page .getByRole('dialog') .getByLabel(/^(Interaction type|Тип взаимодействия)$/) .selectOption('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 dialog.getByLabel(/^(Industry|Отрасль)$/).selectOption('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 page .getByRole('combobox', { name: /^(All countries|Все страны)$/ }) .selectOption('GB'); await page .getByRole('combobox', { name: /^(All industries|Все отрасли)$/ }) .selectOption('OTHER'); await page .getByRole('combobox', { name: /^(All managers|Все менеджеры)$/ }) .selectOption('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 page.getByRole('combobox').selectOption('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); });