diff --git a/e2e/app.spec.ts b/e2e/app.spec.ts new file mode 100644 index 0000000..c4f5758 --- /dev/null +++ b/e2e/app.spec.ts @@ -0,0 +1,145 @@ +import { expect, test, type Browser, type Page } from '@playwright/test'; +import { deflateSync } from 'node:zlib'; + +/** A small valid PNG (solid colour), for the photo upload. */ +function png(w = 64, h = 48): Buffer { + const crcTable = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; + }); + const crc = (b: Buffer) => { let c = 0xffffffff; for (const x of b) c = crcTable[(c ^ x) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; }; + const chunk = (type: string, data: Buffer) => { + const len = Buffer.alloc(4); len.writeUInt32BE(data.length); + const td = Buffer.concat([Buffer.from(type), data]); + const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); + return Buffer.concat([len, td, c]); + }; + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2; + const raw = Buffer.alloc((w * 3 + 1) * h); + for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) raw.set([61, 220, 151], y * (w * 3 + 1) + 1 + x * 3); + return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]); +} + +async function device(browser: Browser, locale: string): Promise { + const ctx = await browser.newContext({ locale, viewport: { width: 412, height: 915 }, isMobile: true, hasTouch: true }); + await ctx.grantPermissions(['clipboard-read', 'clipboard-write']); + return ctx.newPage(); +} + +test('two devices share a group end to end', async ({ browser }) => { + // ---- Anna creates a group (English device) -------------------------- + const anna = await device(browser, 'en-US'); + await anna.goto('/'); + await expect(anna.getByText('No groups on this device yet')).toBeVisible(); + await anna.getByRole('link', { name: 'New group' }).click(); + await anna.getByLabel('Group name').fill('Prague trip'); + await anna.getByLabel('Main currency').selectOption('CZK'); + await anna.getByLabel('Your name').fill('Anna'); + await anna.getByPlaceholder('Name').fill('Petr'); + await anna.getByRole('button', { name: 'Add member' }).click(); + await anna.getByPlaceholder('Name').nth(1).fill('Jana'); + await anna.getByRole('button', { name: 'Create group' }).click(); + + // Lands on settings with the "save this link" warning; copy the link. + await expect(anna.getByText('Save this link somewhere safe')).toBeVisible(); + await anna.getByRole('button', { name: 'Copy link' }).click(); + const link = await anna.evaluate(() => navigator.clipboard.readText()); + expect(link).toMatch(/\/g\/[A-Za-z0-9_-]{22}#[A-Za-z0-9_-]{43}$/); + await anna.getByRole('button', { name: 'Back', exact: true }).click(); + + // ---- An equal split in the base currency ---------------------------- + await anna.getByRole('link', { name: 'Add expense' }).click(); + await anna.getByLabel('Amount').fill('300'); + await anna.getByLabel('What was it for?').fill('Dinner'); + await anna.getByRole('button', { name: 'Save', exact: true }).click(); + await expect(anna.getByRole('link', { name: /Dinner/ })).toBeVisible(); + await expect(anna.getByText('you lent CZK 200.00')).toBeVisible(); + + // ---- Petr opens the link on a Czech device -------------------------- + const petr = await device(browser, 'cs-CZ'); + await petr.goto(link); + await expect(petr.getByRole('heading', { name: 'Kdo jste?' })).toBeVisible(); + // The secret is dropped from the address bar once saved. + expect(new URL(petr.url()).hash).toBe(''); + await petr.getByRole('button', { name: 'Petr' }).click(); + await expect(petr.getByRole('link', { name: /Dinner/ })).toBeVisible(); + await expect(petr.getByText(/dlužíte 100,00\sKč/)).toBeVisible(); + + // ---- Petr adds a EUR expense with exact amounts and a photo ---------- + await petr.getByRole('link', { name: 'Přidat výdaj' }).click(); + await petr.getByLabel('Částka').fill('30'); + await petr.getByLabel('Měna').selectOption('EUR'); + // The ECB rate is prefilled by our server. + await expect(petr.getByText(/Kurz ECB ze dne/)).toBeVisible({ timeout: 30_000 }); + const rate = Number((await petr.getByLabel('1 EUR =').inputValue()).replace(',', '.')); + expect(rate).toBeGreaterThan(15); + expect(rate).toBeLessThan(40); + await petr.getByLabel('Za co?').fill('Museum'); + await petr.getByRole('button', { name: 'Částky' }).click(); + await petr.getByLabel('Rozdělení: Anna').fill('10'); + await petr.getByLabel('Rozdělení: Petr').fill('20'); + await petr.getByLabel('Jana', { exact: true }).uncheck(); + await petr.locator('input[type=file]').setInputFiles({ name: 'receipt.png', mimeType: 'image/png', buffer: png() }); + await expect(petr.getByRole('img', { name: 'Fotka' })).toBeVisible(); + await petr.getByRole('button', { name: 'Uložit' }).click(); + await expect(petr.getByRole('link', { name: /Museum/ })).toBeVisible(); + + // ---- Anna sees it live (SSE), with the photo, without reloading ----- + await expect(anna.getByRole('link', { name: /Museum/ })).toBeVisible({ timeout: 15_000 }); + await anna.getByRole('link', { name: /Museum/ }).click(); + await expect(anna.getByText('€30.00').first()).toBeVisible(); + await expect(anna.getByRole('img', { name: 'Photo' })).toBeVisible({ timeout: 15_000 }); + await anna.getByRole('button', { name: 'Close', exact: true }).click(); + + // ---- Balances and settle-up ------------------------------------------ + await anna.getByRole('link', { name: 'Balances' }).click(); + const annaBal = 20000 - Math.round(rate * 1000); // +200 Kč − €10 + const fmt = (minor: number) => (minor / 100).toLocaleString('en-US', { minimumFractionDigits: 2 }); + const shown = `${annaBal > 0 ? '+' : '−'}CZK ${fmt(Math.abs(annaBal))}`; + await expect(anna.getByText(shown).first()).toBeVisible(); + await expect(anna.getByText('Settle up')).toBeVisible(); + const recordButtons = anna.getByRole('button', { name: 'Record payment' }); + const transfers = await recordButtons.count(); + expect(transfers).toBeGreaterThan(0); + expect(transfers).toBeLessThanOrEqual(2); + + // ---- Rewind and undo ------------------------------------------------ + await anna.getByRole('link', { name: 'Activity' }).click(); + await expect(anna.getByText(/Petr added Museum/)).toBeVisible(); + anna.once('dialog', (d) => d.accept()); + // Rewind to just after Dinner was added (the entry below "Museum"). + await anna.getByRole('button', { name: 'Rewind group to here' }).first().click(); + await expect(anna.getByText(/rewound the group/)).toBeVisible(); + await anna.getByRole('link', { name: 'Expenses' }).click(); + await expect(anna.getByRole('link', { name: /Museum/ })).toHaveCount(0); + await anna.getByRole('link', { name: 'Activity' }).click(); + anna.once('dialog', (d) => d.accept()); + await anna.getByRole('button', { name: 'Undo this rewind' }).click(); + await expect(anna.getByText(/rewound the group/)).toHaveCount(2); + await anna.getByRole('link', { name: 'Expenses' }).click(); + await expect(anna.getByRole('link', { name: /Museum/ })).toBeVisible(); + + // ---- Offline edits sync later --------------------------------------- + await anna.context().setOffline(true); + await anna.getByRole('link', { name: 'Add expense' }).click(); + await anna.getByLabel('Amount').fill('90'); + await anna.getByLabel('What was it for?').fill('Taxi'); + await anna.getByRole('button', { name: 'Save', exact: true }).click(); + await expect(anna.getByRole('link', { name: /Taxi/ })).toBeVisible(); + await expect(anna.getByText(/Offline/)).toBeVisible({ timeout: 20_000 }); + await anna.context().setOffline(false); + await expect(petr.getByRole('link', { name: /Taxi/ })).toBeVisible({ timeout: 30_000 }); + + // ---- Home lists the group with my balance after reload -------------- + await anna.goto('/'); + await expect(anna.getByRole('link', { name: /Prague trip/ })).toBeVisible(); + await expect(anna.getByText(/you are owed/)).toBeVisible(); + + // ---- Stats render --------------------------------------------------- + await anna.getByRole('link', { name: /Prague trip/ }).click(); + await anna.getByRole('link', { name: 'Stats' }).click(); + await expect(anna.getByRole('heading', { name: 'By category' })).toBeVisible(); + await expect(anna.getByRole('heading', { name: 'Paid vs. share' })).toBeVisible(); +}); diff --git a/e2e/push.spec.ts b/e2e/push.spec.ts new file mode 100644 index 0000000..0c3c7d2 --- /dev/null +++ b/e2e/push.spec.ts @@ -0,0 +1,49 @@ +import { expect, test } from '@playwright/test'; + +// Delivers a push message straight to the service worker over CDP (no real +// push service involved) and checks that it decrypts the new events and +// shows a readable notification. +// The stripped-down headless shell always denies notifications; full +// Chromium in headless mode supports them. +test.use({ channel: 'chromium' }); + +test('service worker turns a push into a decrypted notification', async ({ browser, baseURL }) => { + const annaCtx = await browser.newContext({ locale: 'en-US' }); + await annaCtx.grantPermissions(['clipboard-read', 'clipboard-write', 'notifications']); + const anna = await annaCtx.newPage(); + await anna.goto('/new'); + await anna.getByLabel('Group name').fill('Flat'); + await anna.getByLabel('Your name').fill('Anna'); + await anna.getByPlaceholder('Name').fill('Petr'); + await anna.getByRole('button', { name: 'Create group' }).click(); + await anna.getByRole('button', { name: 'Copy link' }).click(); + const link = await anna.evaluate(() => navigator.clipboard.readText()); + const groupId = /\/g\/([^#]+)#/.exec(link)![1]; + await anna.evaluate(() => navigator.serviceWorker.ready); + + // Petr adds an expense from another device. + const petr = await (await browser.newContext({ locale: 'en-US' })).newPage(); + await petr.goto(link); + await petr.getByRole('button', { name: 'Petr' }).click(); + await petr.getByRole('link', { name: 'Add expense' }).click(); + await petr.getByLabel('Amount').fill('12.50'); + await petr.getByLabel('What was it for?').fill('Pizza'); + await petr.getByRole('button', { name: 'Save', exact: true }).click(); + await expect(petr.getByRole('link', { name: /Pizza/ })).toBeVisible(); + + // Anna is on the home screen (not looking at the group) when the push arrives. + await anna.goto('/'); + const cdp = await annaCtx.newCDPSession(anna); + const registrationId = await new Promise((resolve) => { + cdp.on('ServiceWorker.workerRegistrationUpdated', ({ registrations }) => { + const r = registrations.find((x: { scopeURL: string; isDeleted: boolean }) => x.scopeURL.startsWith(baseURL!) && !x.isDeleted); + if (r) resolve(r.registrationId); + }); + void cdp.send('ServiceWorker.enable'); + }); + await cdp.send('ServiceWorker.deliverPushMessage', { origin: new URL(baseURL!).origin, registrationId, data: JSON.stringify({ g: groupId }) }); + + await expect + .poll(async () => anna.evaluate(async () => (await (await navigator.serviceWorker.ready).getNotifications()).map((n) => `${n.title} | ${n.body}`)), { timeout: 15_000 }) + .toContainEqual(expect.stringMatching(/Flat \| Petr: Pizza · \S*12\.50/)); +}); diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..b9f85e9 --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,27 @@ +import { defineConfig, devices } from '@playwright/test'; + +// E2E against the production build served by the real server. +// Run `npm run build` first. Uses a throwaway data dir per run. +// Set E2E_BASE_URL to test an already running deployment instead (e.g. the +// compose stack: E2E_BASE_URL=https://localhost:8483). +const external = process.env.E2E_BASE_URL; +const port = 8490; +const dataDir = `${process.env.TMPDIR ?? '/tmp'}/oweme-e2e-${Date.now()}`; + +export default defineConfig({ + testDir: 'e2e', + timeout: 90_000, + fullyParallel: false, + workers: 1, + reporter: [['list']], + use: { baseURL: external ?? `http://127.0.0.1:${port}`, ignoreHTTPSErrors: !!external, trace: 'retain-on-failure' }, + projects: [ + { name: 'mobile-chromium', use: { ...devices['Pixel 7'] } }, + ], + webServer: external ? undefined : { + command: 'node --disable-warning=ExperimentalWarning apps/server/src/main.ts', + url: `http://127.0.0.1:${port}/api/health`, + reuseExistingServer: false, + env: { PORT: String(port), DATA_DIR: dataDir, STATIC_DIR: 'apps/web/dist', GROUP_CREATE_PER_HOUR: '100' }, + }, +});