// Terminal suite (Playwright + Edge, plan step 3.1c): the terminal app for paired screens, // driven like a person at the screen; the manager's side through the API. // Backend :8059 (demo DB, licensing off), terminal Vite :5187 proxied to it. // - pairing through the real screen (code shown → paired from the manager's side) // - sign-in modes: PIN (wrong PIN first), tap your name, password; sign out // - 3.2a: the screen's prep zone is enforced, and every KDS call passes the device scope // - app turned off → "turned off" screen → on again, live // - device moved to another app → its user is signed out // - a customer display (no sign-in) goes straight into its app // - server unreachable → banner → back by itself // - removed from the manager → back to pairing with a notice and a new code // node terminal.mjs import path from 'node:path' import { chromium } from 'playwright' import { BROWSER_CHANNEL, OUT, reporter, sleep } from './lib/env.mjs' import { startBackend, startTerminalVite } from './lib/proc.mjs' import { supportLogin } from './lib/support.mjs' const backend = await startBackend({ port: 8059, siteId: 'test-site-1' }) const term = await startTerminalVite({ port: 5187, backendUrl: backend.url }) const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) const r = reporter('terminal: pairing, sign-in, app states (paired screens)') const errors = [] async function api(method, url, { token, body } = {}) { const res = await fetch(backend.url + url, { method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body), }) const text = await res.text() let data = null try { data = JSON.parse(text) } catch { data = text } if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 200)}`) return data } async function screen(page) { await page.goto(term.url) page.on('pageerror', e => errors.push(e.message)) return page } const shown = (page, testId, timeout = 10_000) => page.getByTestId(testId).waitFor({ timeout }).then(() => true).catch(() => false) /** The code the screen shows, then the manager pairs it. */ async function pairFromManager(page, boss, body) { await shown(page, 'pairing-code', 15_000) const code = await page.getByTestId('pairing-code').getAttribute('data-code') const dev = await api('POST', '/api/devices', { token: boss, body: { code, ...body } }) return { code, dev } } try { const boss = await supportLogin(backend.url) const chef = await api('POST', '/api/waiters/', { token: boss, body: { username: 'term_chef', full_name: 'Maria Chef', pin: '4747', role: 'chef', is_active: true } }) await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: true } }) // Staff get no password from the Staff page yet (phase 6): the demo's store manager has one const mgr = (await api('GET', '/api/waiters/', { token: boss })).find(u => u.username === 'manager') // ── pairing ────────────────────────────────────────────────────────────── const page = await screen(await (await browser.newContext({ viewport: { width: 1280, height: 800 } })).newPage()) r.check('pairing: a new screen shows a 6-character code', await shown(page, 'pairing-code', 15_000) && (await page.getByTestId('pairing-code').getAttribute('data-code')).length === 6) await page.screenshot({ path: path.join(OUT, 'terminal-pairing.png') }) const { dev: kitchen } = await pairFromManager(page, boss, { app_key: 'kds', name: 'Kitchen', login_mode: 'pin' }) r.check('pairing: paired from the manager → the screen asks who is signing in', await shown(page, 'sign-in-screen', 15_000) && await page.getByTestId('sign-in-screen').getAttribute('data-mode') === 'pin') // ── PIN ────────────────────────────────────────────────────────────────── const chefTile = page.locator(`[data-user="${chef.id}"]`) r.check('sign-in: the chef is listed (holds kds.access)', await chefTile.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) await chefTile.click() await page.keyboard.type('9999') await page.keyboard.press('Enter') await sleep(1200) r.check('sign-in PIN: a wrong PIN stays on the pad with a message', await page.getByTestId('sign-in-screen').count() === 1 && (await page.getByRole('alert').allTextContents()).join(' ').length > 0) await page.keyboard.type('4747') await page.keyboard.press('Enter') r.check('sign-in PIN: the right PIN opens the kitchen display', await shown(page, 'app-kds') && (await page.getByTestId('signed-in-user').textContent()).includes('Maria')) await page.screenshot({ path: path.join(OUT, 'terminal-kds.png') }) const sessions = await api('GET', '/api/auth/sessions', { token: boss }) r.check('sign-in PIN: the session is a terminal session on "Kitchen"', sessions.some(s => s.user_id === chef.id && s.client === 'terminal' && s.device_id === kitchen.id), JSON.stringify(sessions.map(s => [s.user_id, s.client, s.device_id]))) await page.reload() r.check('reload keeps the screen paired and the chef signed in', await shown(page, 'app-kds')) // ── 3.2a: the screen's prep zone and the KDS's own scope ───────────────── const grill = await api('POST', '/api/prep-zones', { token: boss, body: { name: 'Grill', notification_name: 'Grill station' } }) const bar = await api('POST', '/api/prep-zones', { token: boss, body: { name: 'Bar' } }) // a waiter orders one product for each zone (the demo's orders are all closed) await api('POST', '/api/business-day/open', { token: boss, body: {} }).catch(() => {}) const maria = (await api('POST', '/api/auth/login', { body: { client: 'waiter', username: 'demo_maria', pin: '3302' } })).access_token await api('POST', '/api/shifts/start', { token: maria, body: {} }).catch(() => {}) const table = (await api('GET', '/api/tables/', { token: boss })).find(t => !t.open_order_id && !t.current_order_id) const opened = await api('POST', '/api/orders/', { token: maria, body: { table_id: table.id } }) const [p1, p2] = (await api('GET', '/api/products/', { token: boss })).filter(p => p.is_active !== false) await api('POST', '/api/products/bulk-prep-zones', { token: boss, body: { product_ids: [p1.id], prep_zone_ids: [grill.id] } }) await api('POST', '/api/products/bulk-prep-zones', { token: boss, body: { product_ids: [p2.id], prep_zone_ids: [bar.id] } }) await api('POST', `/api/orders/${opened.id}/items`, { token: maria, body: { items: [p1, p2].map(p => ({ product_id: p.id, quantity: 1 })) } }) await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { config: { prep_zone_id: grill.id, font_scale: 120 } } }) const order = (await api('GET', '/api/kds/orders', { token: boss })).orders.find(o => o.id === opened.id) const calls = [ ['get', '/api/kds/context'], ['get', '/api/kds/orders'], ['get', `/api/kds/orders?zone_id=${bar.id}`], ['get', '/api/kds/on-shift-waiters'], ['put', `/api/kds/orders/${order.id}/items/${order.items[0].id}/kds_status`, { status: 'preparing' }], ['put', `/api/kds/orders/${order.id}/kds_status`, { status: 'preparing' }], ['post', `/api/kds/orders/${order.id}/notify-items-ready`, { ready_count: 1, total_count: 2 }], ['post', `/api/kds/orders/${order.id}/notify-complete`, {}], ['post', `/api/kds/orders/${order.id}/call-waiter`, {}], ['post', `/api/kds/orders/${order.id}/retry-print`], ['put', `/api/kds/orders/${order.id}/kds_status`, { status: 'pending' }], ] // every call the kitchen screen makes, through the screen's own client (device header + chef's session) const answers = await page.evaluate(async list => { const out = [] for (const [method, url, body] of list) { try { const res = await window.__xeniaClient[method](url, body) out.push({ url, status: res.status, data: res.data }) } catch (e) { out.push({ url, status: e.response?.status ?? 0, code: e.response?.data?.error?.code }) } } return out }, calls) const refused = answers.filter(a => a.status >= 400) r.check('3.2a: no call the kitchen screen makes is refused (device scope kds.*)', refused.length === 0, JSON.stringify(refused)) const ctx = answers[0].data ?? {} r.check('3.2a: the screen gets its zone and settings from /api/kds/context', ctx.zone?.name === 'Grill' && ctx.settings?.font_scale === 120 && ctx.prep_zones?.length >= 2, JSON.stringify(ctx).slice(0, 300)) const items = answers.slice(1, 3).flatMap(a => (a.data?.orders ?? []).flatMap(o => o.items)) r.check('3.2a: it only ever gets its own zone\'s items, even when it asks for another zone', items.length > 0 && items.every(i => i.prep_zone_ids.includes(grill.id)), `${items.length} items`) const outside = await page.evaluate(async () => { try { await window.__xeniaClient.get('/api/prep-zones'); return 'allowed' } catch (e) { return e.response?.data?.error?.code } }) r.check('3.2a: what the old page used instead (/api/prep-zones) stays out of its scope', outside === 'device.out_of_scope', outside) // ── 3.2b: the kitchen board on the screen ──────────────────────────────── await page.reload() // a fresh start: the browser needs a tap before it plays sound r.check('3.2b: "Tap to start" first (sound needs a tap)', await shown(page, 'kds-start')) await page.getByTestId('kds-start').click() const card = page.locator(`[data-testid="kds-card"][data-order="${opened.id}"]`) r.check('3.2b: the board shows the order with its Grill item only', await card.waitFor({ timeout: 8000 }).then(() => true).catch(() => false) && await card.locator('[data-item]').count() === 1 && (await card.textContent()).includes(p1.name), (await card.textContent().catch(() => '')).slice(0, 120)) await page.screenshot({ path: path.join(OUT, 'terminal-kds-board.png') }) // live, without polling: count the screen's order requests while nothing else happens let polls = 0 const countPolls = req => { if (req.url().includes('/api/kds/orders')) polls++ } page.on('request', countPolls) await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { config: { prep_zone_id: grill.id, font_scale: 120, refresh_seconds: 10 } } }) await sleep(12_000) page.off('request', countPolls) r.check('3.2b: no polling while the live connection is up (refresh 10 s, 12 s quiet)', polls <= 1, `${polls} requests`) // ≤1: the settings change may reload once // a new order arrives live, with the chime const chimes0 = await page.evaluate(() => window.__xeniaChimes || 0) const table2 = (await api('GET', '/api/tables/', { token: boss })).find(t => !t.open_order_id && !t.current_order_id && t.id !== table.id) const second = await api('POST', '/api/orders/', { token: maria, body: { table_id: table2.id } }) await api('POST', `/api/orders/${second.id}/items`, { token: maria, body: { items: [{ product_id: p1.id, quantity: 2 }] } }) const card2 = page.locator(`[data-testid="kds-card"][data-order="${second.id}"]`) r.check('3.2b: a new order appears by itself (live) and chimes', await card2.waitFor({ timeout: 5000 }).then(() => true).catch(() => false) && await page.evaluate(() => window.__xeniaChimes || 0) > chimes0) // the zoom is the device's font_scale, changed live from the manager r.check('3.2b: text size follows the device setting live (120%)', (await page.getByTestId('zoom-level').textContent()) === '120%') // tap the card, tap its item → done; the backend agrees const kdsItem = async (orderId, itemId) => (await api('GET', '/api/kds/orders', { token: boss })).orders .find(o => o.id === orderId)?.items.find(i => i.id === itemId) await card2.click({ position: { x: 20, y: 120 } }) const item2 = card2.locator('[data-item]').first() const item2Id = Number(await item2.getAttribute('data-item')) await item2.click() await sleep(800) r.check('3.2b: tapping an item on the selected card marks it done', (await kdsItem(second.id, item2Id))?.kds_status === 'done') // undo await page.getByTestId('kds-undo').click() await sleep(800) r.check('3.2b: undo puts it back', (await kdsItem(second.id, item2Id))?.kds_status === 'pending') // the action bar: in progress await card2.click({ position: { x: 20, y: 120 } }) await card2.getByTestId('card-prepare').click() await sleep(800) r.check('3.2b: "in progress" from the card\'s buttons', (await api('GET', '/api/kds/orders', { token: boss })).orders.find(o => o.id === second.id)?.kds_status === 'preparing') // long press → quick actions → decline with a reason const box = await card.boundingBox() await page.mouse.move(box.x + 30, box.y + 120) await page.mouse.down() await sleep(800) await page.mouse.up() r.check('3.2b: a long press shows the quick actions', await shown(page, 'quick-decline', 3000)) await page.getByTestId('quick-decline').click() await page.locator('[data-reason="out_of_stock"]').click() await sleep(400) // let colour transitions finish await page.screenshot({ path: path.join(OUT, 'terminal-kds-decline.png') }) await page.getByTestId('decline-confirm').click() await sleep(800) const declined = (await api('GET', `/api/kds/orders?zone_id=${grill.id}`, { token: boss })).orders.find(o => o.id === opened.id) r.check('3.2b: declined with the reason', !!declined && declined.items.some(i => i.kds_status === 'declined' && i.decline_note === 'Out of stock'), JSON.stringify(declined?.items?.map(i => [i.kds_status, i.decline_note]))) // settings on the screen: a chef sees them but can't save await page.getByTestId('kds-settings').click() r.check('3.2b: the screen\'s settings: a chef sees them, with "only a manager"', await shown(page, 'kds-settings-panel', 3000) && await page.getByTestId('settings-no-permission').count() === 1 && await page.getByTestId('settings-save').isDisabled()) await page.getByTestId('settings-tab-age').click() await sleep(400) // let colour transitions finish await page.screenshot({ path: path.join(OUT, 'terminal-kds-settings.png') }) await page.keyboard.press('Escape') r.check('3.2b-2: the settings are a shared dialog (Escape closes it)', await page.getByTestId('kds-settings-panel').waitFor({ state: 'detached', timeout: 3000 }).then(() => true).catch(() => false)) // a change made elsewhere (another screen, the waiter) reaches this screen live await api('PUT', `/api/kds/orders/${second.id}/kds_status`, { token: boss, body: { status: 'pending' } }) await page.waitForFunction(id => document.querySelector(`[data-testid="kds-card"][data-order="${id}"]`)?.dataset.status === 'pending', second.id, { timeout: 5000 }).catch(() => {}) r.check('3.2b: a change made elsewhere shows on the screen by itself', await card2.getAttribute('data-status') === 'pending') // ── 3.2c: two screens on the same zone, two cooks, claims ──────────────── const chef2 = await api('POST', '/api/waiters/', { token: boss, body: { username: 'term_chef2', full_name: 'Nikos Cook', nickname: 'Nikos', pin: '5858', role: 'chef', is_active: true } }) const page2 = await screen(await (await browser.newContext({ viewport: { width: 1280, height: 800 } })).newPage()) await pairFromManager(page2, boss, { app_key: 'kds', name: 'Kitchen 2', login_mode: 'pin', config: { prep_zone_id: grill.id } }) await page2.locator(`[data-user="${chef2.id}"]`).click({ timeout: 15_000 }) await page2.keyboard.type('5858') await page2.keyboard.press('Enter') await page2.getByTestId('kds-start').click({ timeout: 15_000 }) const other = page2.locator(`[data-testid="kds-card"][data-order="${second.id}"]`) await other.waitFor({ timeout: 8000 }) const pill = (loc, name) => loc.locator('[data-testid="item-claim"]', { hasText: name }).waitFor({ timeout: 5000 }).then(() => true).catch(() => false) const noPill = loc => loc.locator('[data-testid="item-claim"]').waitFor({ state: 'detached', timeout: 5000 }).then(() => true).catch(() => false) await card2.click({ position: { x: 20, y: 120 } }) await card2.getByTestId('card-claim').click() r.check('3.2c: Maria says "I\'m on it" → the other screen shows her name on the item, live', await pill(other, 'Maria')) await other.click({ position: { x: 20, y: 120 } }) r.check('3.2c: on the other screen there is nothing left to take (no claim button)', await other.getByTestId('card-prepare').isVisible() && await other.getByTestId('card-claim').count() === 0) const takeover = await page2.evaluate(async ([o, i]) => { try { await window.__xeniaClient.post(`/api/kds/orders/${o}/items/${i}/claim`); return 'allowed' } catch (e) { return e.response?.data?.error?.code } }, [second.id, item2Id]) r.check('3.2c: Nikos can\'t take Maria\'s item (kds.item_claimed)', takeover === 'kds.item_claimed', takeover) await page2.keyboard.press('Escape') await card2.click({ position: { x: 20, y: 120 } }) await card2.getByTestId('card-claim').click() // Maria lets go r.check('3.2c: Maria lets go → the name goes on the other screen', await noPill(other)) await other.click({ position: { x: 20, y: 120 } }) await other.getByTestId('card-claim').click() // Nikos takes it r.check('3.2c: Nikos takes it → Maria\'s screen shows "Nikos"', await pill(card2, 'Nikos')) await page.screenshot({ path: path.join(OUT, 'terminal-kds-claim.png') }) await other.click({ position: { x: 20, y: 120 } }) await other.locator('[data-item]').first().click() // Nikos bumps it: done r.check('3.2c: bumping clears the claim (both screens, backend)', await noPill(card2) && (await kdsItem(second.id, item2Id))?.claimed_by == null && (await kdsItem(second.id, item2Id))?.kds_status === 'done') await page2.context().close() await page.getByRole('button', { name: 'Sign out' }).click() r.check('sign out → back to the names', await shown(page, 'user-grid')) // ── tap, password (the manager changes the mode; the screen follows live) ── await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { login_mode: 'tap' } }) await page.waitForFunction(() => document.querySelector('[data-testid="sign-in-screen"]')?.dataset.mode === 'tap', null, { timeout: 8000 }).catch(() => {}) r.check('mode changed in the manager → the screen switches to "tap your name" at once', await page.getByTestId('sign-in-screen').getAttribute('data-mode') === 'tap') await page.locator(`[data-user="${chef.id}"]`).click() r.check('sign-in tap: tapping the name signs in', await shown(page, 'app-kds')) await page.getByRole('button', { name: 'Sign out' }).click() await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { login_mode: 'password' } }) await page.waitForFunction(() => document.querySelector('[data-testid="sign-in-screen"]')?.dataset.mode === 'password', null, { timeout: 8000 }).catch(() => {}) await page.locator(`[data-user="${mgr.id}"]`).click() await page.getByLabel('Password').fill('password') await page.getByRole('button', { name: 'Sign in' }).click() r.check('sign-in password: name + password signs in', await shown(page, 'app-kds')) // ── ended elsewhere: the manager ends the session ───────────────────────── const sid = (await api('GET', '/api/auth/sessions', { token: boss })).find(s => s.device_id === kitchen.id).id await api('POST', `/api/auth/sessions/${sid}/end`, { token: boss }) r.check('session ended by a manager → the screen is back at sign-in at once', await shown(page, 'sign-in-screen', 8000)) // ── app off / on ────────────────────────────────────────────────────────── await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: false } }) r.check('KDS turned off → "turned off" screen, live', await shown(page, 'blocked-screen', 8000) && await page.getByTestId('blocked-screen').getAttribute('data-reason') === 'module.disabled') await page.screenshot({ path: path.join(OUT, 'terminal-app-off.png') }) await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: true } }) r.check('KDS on again → the sign-in comes back by itself', await shown(page, 'sign-in-screen', 8000)) // ── moved to another app: whoever is on it is signed out ───────────────── await page.locator(`[data-user="${mgr.id}"]`).click() await page.getByLabel('Password').fill('password') await page.getByRole('button', { name: 'Sign in' }).click() await shown(page, 'app-kds') await api('POST', `/api/devices/${kitchen.id}/reassign`, { token: boss, body: { app_key: 'pos_counter' } }) await page.waitForFunction(() => document.querySelector('[data-testid="sign-in-screen"]'), null, { timeout: 8000 }).catch(() => {}) r.check('moved to Counter POS → signed out, sign-in for the POS', await page.getByTestId('sign-in-screen').count() === 1 && (await page.getByTestId('sign-in-screen').textContent()).includes('Kitchen')) // ── a customer display: no sign-in ─────────────────────────────────────── const cd = await screen(await (await browser.newContext({ viewport: { width: 1024, height: 600 } })).newPage()) await pairFromManager(cd, boss, { app_key: 'customer_display', name: 'Counter display' }) r.check('customer display (sign-in "none") goes straight into its app', await shown(cd, 'app-customer_display', 15_000) && await cd.getByTestId('terminal-bar').count() === 0) // ── server unreachable → banner → back ─────────────────────────────────── await cd.context().setOffline(true) await cd.evaluate(() => window.__xeniaClient.get('/api/devices/me').catch(() => {})) r.check('server unreachable → the banner shows', await shown(cd, 'offline-banner', 8000)) await cd.context().setOffline(false) // back online: the live connection reconnects by itself (browser `online`); Try again also works await cd.getByRole('button', { name: 'Try again' }).click({ timeout: 2000 }).catch(() => {}) await cd.getByTestId('offline-banner').waitFor({ state: 'detached', timeout: 10_000 }).catch(() => {}) r.check('…and goes away once the server answers', await cd.getByTestId('offline-banner').count() === 0) // ── removed → pairing again ────────────────────────────────────────────── await api('POST', `/api/devices/${kitchen.id}/revoke`, { token: boss }) r.check('removed in the manager → back to pairing with a notice and a new code', await shown(page, 'removed-notice', 10_000) && await shown(page, 'pairing-code', 15_000)) await page.screenshot({ path: path.join(OUT, 'terminal-removed.png') }) r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | ')) } catch (e) { r.check(`terminal: ${e.message.split('\n').slice(0, 8).join(' | ')}`, false) const pages = browser.contexts().flatMap(c => c.pages()) for (const [i, p] of pages.entries()) await p.screenshot({ path: path.join(OUT, `terminal-failure-${i}.png`) }).catch(() => {}) } finally { await browser.close() term.stop() await backend.stop() } process.exit(r.done() ? 1 : 0)