Files
xenia-pos-local/tests/e2e/browser.mjs
T
bonaminandClaude Opus 5.5 9f5498332a feat(waiter): the waiter app on the shared foundations (api client, access, i18n), lint clean, starts offline
Plan step 4.1. No visible change to layout or flows.
- api/client.js on @xenia/api createApiClient (CS-8 baseURL, 401 → sign out, no answer →
  backend-offline, err.xenia, the manager-approval retry); the PIN login handles its own 401
  (before, a wrong PIN reloaded the page).
- <AccessProvider> at the root with an i18n instance: modules, permission keys, venue,
  language from bootstrap; who is signed in comes with it (no more /api/auth/me polling).
  packages/access: AccessProvider gains `cache` (the last bootstrap per session; used when
  the server can't be reached, `offline` in the context, keeps retrying) and `failed` (the
  app's own screen when there's nothing cached). The waiter caches per venue, shows its
  offline page (server search) on a first start without a server, retries every 5 s;
  ServerRediscovery and BundleSync run outside the bootstrap.
- Role names → keys: the shift gate and the user menu use core.dashboard.access.
- One shared, offline-cached read of the venue settings (api/venueSettings.js) instead of
  seven GET /api/settings/ calls; apiError() shows backend error codes in the user's
  language (17 places).
- Lint: 78 errors → 0 (unused code, empty catches, two duplicate style keys, a component
  created during render, refs read during render → state, hooks after an early return);
  set-state-in-effect is a warning like the manager/terminal; lint in run-all.
- Tests: tests/bootstrapCache.test.mjs; e2e browser: an offline restart stays signed in.
  Android rediscovery waits for what the screen shows instead of fixed sleeps: 10/10 three
  runs in a row (KI-009). Terminal 3.4 waits for both displays before the sale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:37:47 +02:00

134 lines
8.4 KiB
JavaScript
Raw 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.
// Browser suite (Playwright + Edge): the waiter app's three web delivery modes
// (plan step 2) and the install-app dialog / drawer entry (F-051).
// Starts its own backend (:8055), nginx containers serving the production build
// (:15173 with an APK, :15174 without) and a Vite dev server (:5180).
// node browser.mjs
import { execFileSync } from 'node:child_process'
import { cpSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { chromium } from 'playwright'
import { BROWSER_CHANNEL, OUT, WAITER, lanIp, reporter, sleep } from './lib/env.mjs'
import { login, serveWaiterBuild, startBackend, startViteNative } from './lib/proc.mjs'
const LAN = lanIp()
const ANDROID_UA = 'Mozilla/5.0 (Linux; Android 14; SM-A145R) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Mobile Safari/537.36'
const IPHONE_UA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1'
const DESKTOP_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36'
console.log(' building the waiter app…')
execFileSync('npm', ['run', 'build'], { cwd: WAITER, stdio: 'ignore', shell: process.platform === 'win32' })
// Two copies of the build: one whose server offers the APK, one that doesn't
const withApk = path.join(OUT, 'dist-with-apk'), noApk = path.join(OUT, 'dist-no-apk')
for (const d of [withApk, noApk]) { rmSync(d, { recursive: true, force: true }); cpSync(path.join(WAITER, 'dist'), d, { recursive: true }) }
mkdirSync(path.join(withApk, 'downloads'), { recursive: true })
writeFileSync(path.join(withApk, 'downloads', 'xenia-waiter.apk'), Buffer.from('PK\x03\x04 test apk'))
rmSync(path.join(noApk, 'downloads'), { recursive: true, force: true })
const backend = await startBackend({ port: 8055, siteId: 'test-site-1' })
const web = await serveWaiterBuild({ name: 'xenia-e2e-waiter', port: 15173, dist: withApk })
const webNoApk = await serveWaiterBuild({ name: 'xenia-e2e-waiter-noapk', port: 15174, dist: noApk })
const vite = await startViteNative({ port: 5180, backendUrl: backend.url })
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
let failures = 0
try {
const token = await login(backend.url)
// ── Web delivery modes ────────────────────────────────────────────────────
const r1 = reporter('browser: web delivery modes')
const modes = [
{ name: 'same-origin (prod build, https-like localhost)', origin: 'http://localhost:15173', tokenKey: 'token', db: 'pos_snapshot', wsHost: 'localhost:15173', secure: true },
{ name: 'plain HTTP by LAN IP (prod build)', origin: `http://${LAN}:15173`, tokenKey: 'token', db: 'pos_snapshot', wsHost: `${LAN}:15173`, secure: false },
{ name: 'venue mode (dev build, VITE_SERVER_URL)', origin: 'http://localhost:5180', tokenKey: 'xenia:dev:token', db: 'pos_snapshot__dev', wsHost: '127.0.0.1:8055', secure: true },
]
for (const m of modes) {
const page = await (await browser.newContext()).newPage()
const frames = [], wsUrls = [], apiHosts = new Set()
page.on('request', r => { if (['xhr', 'fetch'].includes(r.resourceType())) apiHosts.add(new URL(r.url()).host) })
page.on('websocket', ws => { wsUrls.push(ws.url()); ws.on('framereceived', f => frames.push(String(f.payload))) })
await page.goto(`${m.origin}/login`)
await page.evaluate(([k, t]) => localStorage.setItem(k, t), [m.tokenKey, token])
await page.goto(`${m.origin}/tables`)
await sleep(6000)
const dbs = await page.evaluate(async () => (await indexedDB.databases()).map(d => d.name))
r1.check(`${m.name}: lands on /tables`, page.url().includes('/tables'), page.url())
r1.check(`${m.name}: live WebSocket via ${m.wsHost}`, frames.some(f => f.includes('"ready"')) && wsUrls.some(u => new URL(u).host === m.wsHost))
r1.check(`${m.name}: no token in the live connection's address (4.0)`, wsUrls.some(u => u.includes('/api/ws/')) && wsUrls.filter(u => u.includes('/api/')).every(u => !/token=/.test(u)), wsUrls.filter(u => u.includes('/api/')).join(' '))
r1.check(`${m.name}: IndexedDB "${m.db}"`, dbs.includes(m.db), dbs.join(','))
r1.check(`${m.name}: secure context = ${m.secure}`, (await page.evaluate(() => window.isSecureContext)) === m.secure)
if (m.name.startsWith('venue')) r1.check(`${m.name}: API calls go to the venue server`, [...apiHosts].every(h => h === '127.0.0.1:8055'), [...apiHosts].join(','))
if (m.name.startsWith('same-origin')) {
// 4.1: the bootstrap (who is signed in, permissions, venue) is cached per venue, so a
// phone that reopens the app without the server still starts signed in
const cached = await page.evaluate(() => !!localStorage.getItem('bootstrap'))
await page.context().setOffline(true)
await page.reload().catch(() => {})
await sleep(4000)
const signedIn = await page.evaluate(() => location.pathname).catch(() => '')
r1.check(`${m.name}: the bootstrap is cached and an offline restart stays signed in`, cached && signedIn.startsWith('/tables'), `${cached} ${signedIn}`)
await page.context().setOffline(false)
}
await page.context().close()
}
failures += r1.done()
// ── Install-app dialog + drawer entry ─────────────────────────────────────
const r2 = reporter('browser: install-app dialog')
const phone = ua => browser.newContext({ userAgent: ua, viewport: { width: 393, height: 852 }, deviceScaleFactor: 2.75, isMobile: true, hasTouch: true })
const dialog = page => page.getByRole('dialog', { name: 'Εφαρμογή Xenia' })
const hamburger = page => page.locator('button').filter({ has: page.locator('svg') }).first()
let ctx = await phone(ANDROID_UA)
let page = await ctx.newPage()
await page.goto(`http://${LAN}:15173/?pair=test-site-1`)
await sleep(3500)
r2.check('first visit on Android: dialog opens by itself', await dialog(page).isVisible())
const box = await dialog(page).boundingBox()
r2.check('dialog is taller than wide', box && box.height > box.width, box ? `${Math.round(box.width)}×${Math.round(box.height)}` : '')
r2.check('download link points at the APK', (await page.getByRole('link', { name: 'Λήψη εφαρμογής' }).getAttribute('href')) === '/downloads/xenia-waiter.apk')
await page.screenshot({ path: path.join(OUT, 'install-dialog.png') })
await page.getByRole('button', { name: 'Όχι τώρα' }).click()
await sleep(400)
await page.reload()
await sleep(3500)
r2.check('"Όχι τώρα" → never opens by itself again', !(await dialog(page).isVisible()))
await page.evaluate(t => localStorage.setItem('token', t), token)
await page.goto(`http://${LAN}:15173/tables`)
await sleep(4000)
await hamburger(page).click()
await sleep(600)
const install = page.getByRole('button', { name: 'Εγκατάσταση εφαρμογής' })
const [ib, sb] = [await install.boundingBox(), await page.getByRole('button', { name: 'Settings' }).boundingBox()]
r2.check('drawer shows "Εγκατάσταση εφαρμογής" right above Settings', !!(ib && sb && ib.y < sb.y && sb.y - ib.y < 80))
await install.click()
await sleep(500)
r2.check('drawer entry reopens the dialog', await dialog(page).isVisible())
await ctx.close()
for (const [label, ua] of [['desktop', DESKTOP_UA], ['iPhone', IPHONE_UA]]) {
ctx = await phone(ua)
page = await ctx.newPage()
await page.goto(`http://${LAN}:15173/`)
await page.evaluate(t => localStorage.setItem('token', t), token)
await page.goto(`http://${LAN}:15173/tables`)
await sleep(3500)
const noDialog = !(await dialog(page).isVisible())
await hamburger(page).click()
await sleep(500)
r2.check(`${label}: never offered (no dialog, no drawer entry)`, noDialog && !(await page.getByRole('button', { name: 'Εγκατάσταση εφαρμογής' }).isVisible()))
await ctx.close()
}
ctx = await phone(ANDROID_UA)
page = await ctx.newPage()
await page.goto(`http://${LAN}:15174/`)
await sleep(3500)
r2.check('server without the APK: never offered', !(await dialog(page).isVisible()))
await ctx.close()
failures += r2.done()
} finally {
await browser.close()
vite.stop(); web.stop(); webNoApk.stop()
await backend.stop()
}
process.exit(failures ? 1 : 0)