// 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 // - 3.3a–e: the counter POS (sale, payment, tables with a waiter's phone, online orders // pulled from a fake cloud exactly as from the real one, refunds) // node terminal.mjs import http from 'node:http' import net from 'node:net' import path from 'node:path' import { execFileSync } from 'node:child_process' import { chromium } from 'playwright' import { BROWSER_CHANNEL, OUT, PYTHON, reporter, sleep, waitFor } from './lib/env.mjs' import { startBackend, startTerminalVite } from './lib/proc.mjs' import { supportLogin } from './lib/support.mjs' // A fake cloud for online orders (3.3d): the heartbeat names the site, the order pull hands // over what the test queues, and status changes are recorded (the customer's tracking page). const cloud = { queue: [], synced: [], statuses: [] } const cloudServer = http.createServer((req, res) => { let body = '' req.on('data', c => { body += c }) req.on('end', () => { const send = data => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(data)) } const json = () => { try { return JSON.parse(body || '{}') } catch { return {} } } let m if (req.url === '/api/heartbeat/') return send({ site_numeric_id: 7 }) if (req.method === 'GET' && req.url === '/api/orders/pending/7') return send(cloud.queue.filter(o => !cloud.synced.includes(o.id))) if ((m = req.url.match(/^\/api\/orders\/(\d+)\/synced$/))) { cloud.synced.push(Number(m[1])); return send({ ok: true }) } if ((m = req.url.match(/^\/api\/orders\/(\d+)\/status$/))) { cloud.statuses.push({ id: Number(m[1]), ...json() }); return send({ ok: true }) } return send({}) }) }) await new Promise(res => cloudServer.listen(0, '127.0.0.1', res)) const backend = await startBackend({ port: 8059, siteId: 'test-site-1', cloudUrl: `http://127.0.0.1:${cloudServer.address().port}`, env: { LICENSE_MODE: 'off', CONNECT_SYNC_INTERVAL_SECONDS: '1', XENIA_FIRE_CHECK_SECONDS: '2' } }) 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: { lines: [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: { lines: [{ 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')) // ── 3.3a: the counter POS ──────────────────────────────────────────────── const cats = await api('GET', '/api/products/categories', { token: boss }) const burgerP = await api('POST', '/api/products/', { token: boss, body: { name: 'E2E Burger', base_price: 10, primary_category_id: cats[0].id, category_ids: [cats[0].id], preference_sets: [{ name: 'Cooking', choices: [{ name: 'Rare' }, { name: 'Well done', extra_cost: 0.5 }] }], options: [{ name: 'Sauce', extra_cost: 0.5, sub_choices: [{ name: 'BBQ', extra_cost: 0.2, is_default: true }, { name: 'Mayo' }] }], quick_options: [{ name: 'Cheese', price: 1, allow_multiple: true }], ingredients: [{ name: 'Onion' }], allergens: { gluten: 'contains', sesame: 'may_contain' }, } }) const posMenu = await api('GET', '/api/pos/menu', { token: boss }) const simple = posMenu.products.find(p => !p.prefs.length && p.id !== burgerP.id && p.categories.every(c => c.category_id !== cats[0].id)) // 3.3b: the counter's receipt printer is a local socket that records what it gets (cash drawer) const drawerBytes = [] const drawerServer = net.createServer(sock => { const chunks = []; sock.on('data', c => chunks.push(c)); sock.on('end', () => drawerBytes.push(Buffer.concat(chunks))) }) await new Promise(res => drawerServer.listen(0, '127.0.0.1', res)) const receipt = await api('POST', '/api/system/printers', { token: boss, body: { name: 'Counter receipt', ip_address: '127.0.0.1', port: drawerServer.address().port, is_active: true } }) await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { config: { receipt_printer_id: receipt.id } } }) await page.locator(`[data-user="${mgr.id}"]`).click() await page.getByLabel('Password').fill('password') await page.getByRole('button', { name: 'Sign in' }).click() r.check('3.3a: the cashier is asked to start their shift (business day open, no shift yet)', await shown(page, 'pos-start-shift', 10_000)) await page.getByTestId('starting-cash').fill('20') await page.getByRole('button', { name: 'Start shift' }).click() r.check('3.3a: shift started → the sale screen', await shown(page, 'pos-screen', 10_000)) const posSession = await page.evaluate(async () => (await window.__xeniaClient.get('/api/pos/session')).data) r.check('3.3a: the shift is the cashier\'s own, with the starting cash', posSession.shift?.starting_cash === 20, JSON.stringify(posSession.shift)) await page.getByTestId('pos-search').fill('burg e2e') const burgerCard = page.locator(`[data-testid="pos-product"][data-product="${burgerP.id}"]`) r.check('3.3a: search finds the product by name (words in any order)', await burgerCard.waitFor({ timeout: 5000 }).then(() => true).catch(() => false) && await page.locator('[data-testid="pos-product"]').count() === 1) await burgerCard.getByTestId('product-info').click() r.check('3.3a: price check shows the price without adding it', await shown(page, 'product-dialog', 5000) && (await page.getByTestId('dialog-price').textContent()).includes('10.00') && await page.getByTestId('cart-line').count() === 0) r.check('6.3: …and its allergens (contains gluten, may contain sesame)', await page.getByTestId('product-dialog').locator('[data-allergen="gluten"][data-level="contains"]').count() === 1 && await page.getByTestId('product-dialog').locator('[data-allergen="sesame"][data-level="may_contain"]').count() === 1) await page.keyboard.press('Escape') await burgerCard.locator('button').first().click() await page.getByTestId('product-dialog').waitFor({ timeout: 5000 }) r.check('3.3a: a product with a preference opens its choices; Add waits for the choice', await page.getByTestId('dialog-add').isDisabled() && await page.getByTestId('dialog-missing').count() === 1) const set = burgerP.preference_sets[0] await page.locator(`[data-choice="${set.choices[1].id}"]`).click() await page.locator(`[data-option="${burgerP.options[0].id}"]`).click() await page.locator(`[data-quick="${burgerP.quick_options[0].id}"]`).click() await page.locator(`[data-ingredient="${burgerP.ingredients[0].id}"]`).click() // 10 + 0.50 well done + 0.50 sauce + 0.20 BBQ + 1 cheese, priced by the backend await page.waitForFunction(() => document.querySelector('[data-testid="dialog-add"]')?.textContent.includes('12.20'), null, { timeout: 5000 }).catch(() => {}) r.check('3.3a: the price follows the choices (priced by the backend: 12.20)', (await page.getByTestId('dialog-add').textContent()).includes('12.20'), await page.getByTestId('dialog-add').textContent()) await page.getByTestId('dialog-add').click() await page.waitForFunction(() => document.querySelector('[data-testid="cart-total"]')?.textContent.includes('12.20'), null, { timeout: 5000 }).catch(() => {}) const line1 = page.getByTestId('cart-line').first() r.check('3.3a: the cart has the line with its choices and the total', await page.getByTestId('cart-line').count() === 1 && (await line1.textContent()).includes('Well done') && (await line1.textContent()).includes('Onion') && (await page.getByTestId('cart-total').textContent()).includes('12.20')) await page.getByTestId('pos-search').fill('') const simpleCat = simple.categories[0].category_id await page.getByTestId(`category-${simpleCat}`).click() const simpleCard = page.locator(`[data-testid="pos-product"][data-product="${simple.id}"]`) r.check('3.3a: a category shows its products', await simpleCard.isVisible() && await burgerCard.count() === 0) await simpleCard.locator('button').first().click() await simpleCard.locator('button').first().click() const expected = (12.2 + 2 * simple.price).toFixed(2) await page.waitForFunction(x => document.querySelector('[data-testid="cart-total"]')?.textContent.includes(x), expected, { timeout: 5000 }).catch(() => {}) r.check('3.3a: a product without choices is added by a tap; the same one twice adds up', await page.getByTestId('cart-line').count() === 2 && (await page.getByTestId('line-qty').nth(1).textContent()).includes('2') && (await page.getByTestId('cart-total').textContent()).includes(expected), `${await page.getByTestId('cart-total').textContent()} vs ${expected}`) await page.screenshot({ path: path.join(OUT, 'terminal-pos.png') }) // ── 3.3b: charge it ────────────────────────────────────────────────────── const cartTotal = Number(expected) await page.getByTestId('charge').click() // tap 1 await page.getByTestId('payment-dialog').waitFor({ timeout: 5000 }) r.check('3.3b: Charge opens the payment on cash with the exact amount', await page.getByTestId('pay-cash').getAttribute('aria-checked') === 'true' && (await page.getByTestId('change').textContent()).includes('0.00')) await page.getByTestId('quick-amount').nth(1).click() const givenNow = Number((await page.getByTestId('cash-given').inputValue()).replace(',', '.')) const changeText = await page.getByTestId('change').textContent() r.check('3.3b: a quick amount shows the change', changeText.includes((givenNow - cartTotal).toFixed(2)), `${givenNow} → ${changeText}`) await page.screenshot({ path: path.join(OUT, 'terminal-pos-pay.png') }) await page.getByTestId('pay-confirm').click() // tap 2 (3 with typing an amount) r.check('3.3b: paid → the cart shows the change and is ready for the next sale', await shown(page, 'sale-done', 10_000) && (await page.getByTestId('sale-change').textContent()).includes((givenNow - cartTotal).toFixed(2)) && await page.getByTestId('cart-line').count() === 0) await page.waitForFunction(() => true, null, { timeout: 100 }) for (let i = 0; i < 20 && !drawerBytes.length; i++) await sleep(100) r.check('3.3b: the cash drawer opened (ESC p 0 25 250 to the receipt printer)', drawerBytes.some(b => b.includes(Buffer.from([0x1b, 0x70, 0x00, 0x19, 0xfa]))) && (await page.getByTestId('sale-done').textContent()).includes('Drawer opened')) const myShift = await page.evaluate(async () => (await window.__xeniaClient.get('/api/shifts/my')).data) r.check('3.3b: the sale is in the cashier\'s shift cash', Math.abs(myShift.cash_sales - cartTotal) < 0.005 && Math.abs(myShift.net_to_deliver - (cartTotal + 20)) < 0.005, JSON.stringify({ cash: myShift.cash_sales, net: myShift.net_to_deliver })) const saleOrder = Number(await page.getByTestId('sale-done').getAttribute('data-order')) const kdsSeen = (await api('GET', '/api/kds/orders', { token: boss })).orders.some(o => o.id === saleOrder) r.check('3.3b: the kitchen got the order like any other (KDS)', kdsSeen) await page.getByTestId('same-again').click() r.check('3.3b: "Same again" puts the last sale back in the cart', await page.getByTestId('cart-line').count() === 2) await page.waitForFunction(x => document.querySelector('[data-testid="cart-total"]')?.textContent.includes(x), expected, { timeout: 5000 }).catch(() => {}) await page.getByTestId('charge').click() await page.getByTestId('pay-card').click() const drawerBefore = drawerBytes.length await page.getByTestId('pay-confirm').click() r.check('3.3b: a card payment is recorded as card, no drawer', await page.getByTestId('sale-done').waitFor({ timeout: 10_000 }).then(() => true).catch(() => false) && (await page.getByTestId('sale-done').textContent()).includes('Card') && !(await page.getByTestId('sale-done').textContent()).includes('Drawer')) await sleep(300) r.check('3.3b: …and the drawer stayed shut', drawerBytes.length === drawerBefore) // ── 3.3c: tables at the counter, with a waiter's phone on the same table ─ // the phone: Maria's live connection (as the waiter app opens it) and her API calls const phoneEvents = [] const phoneWs = new WebSocket(`${backend.url.replace(/^http/, 'ws')}/api/ws/connect`) await new Promise(res => { phoneWs.onopen = () => phoneWs.send(JSON.stringify({ cursor: 0, token: maria })) phoneWs.onmessage = e => { const m = JSON.parse(e.data); if (m.type === 'ready') res(); else phoneEvents.push(m) } setTimeout(res, 5000) }) const heard = async (pred, ms = 5000) => { for (let i = 0; i < ms / 100; i++) { if (phoneEvents.some(pred)) return true; await sleep(100) } return false } const mariaTables = new Set((await api('GET', '/api/tables/', { token: maria })).map(t => t.id)) await page.getByTestId('mode-tables').click() r.check('3.3c: Tables shows the table list', await shown(page, 'pos-tables', 10_000)) const counterTables = await page.evaluate(async () => (await window.__xeniaClient.get('/api/pos/tables')).data.tables) const shared = counterTables.find(t => !t.order && mariaTables.has(t.id)) const tableCard = page.locator(`[data-testid="pos-table"][data-table="${shared.id}"]`) r.check('3.3c: …each table with its state (a free one)', await tableCard.getAttribute('data-state') === 'free') await tableCard.click() r.check('3.3c: a table opens with the product grid and its (empty) order', await shown(page, 'table-panel', 5000) && await simpleCard.isVisible()) await simpleCard.locator('button').first().click() await page.getByTestId('table-send').waitFor({ timeout: 5000 }) await page.waitForFunction(() => !document.querySelector('[data-testid="table-send"]')?.disabled, null, { timeout: 5000 }).catch(() => {}) await page.getByTestId('table-send').click() await page.waitForFunction(() => document.querySelectorAll('[data-testid="order-line"]').length === 1, null, { timeout: 8000 }).catch(() => {}) const tableOrder = Number(await page.getByTestId('table-panel').getAttribute('data-order')) r.check('3.3c: Send opens the table\'s order with the line', tableOrder > 0 && await page.getByTestId('order-line').count() === 1) r.check('3.3c: the phone hears it at once (live)', await heard(m => m.type === 'order_updated' && m.data.order_id === tableOrder && m.data.action === 'items_added')) const onPhone = await api('GET', `/api/orders/${tableOrder}`, { token: maria }) r.check('3.3c: …and sees the counter\'s order on that table', onPhone.table_id === shared.id && onPhone.items.length === 1) // the phone adds two items → the counter shows them without a reload await api('POST', `/api/orders/${tableOrder}/items`, { token: maria, body: { lines: [ { product_id: simple.id, quantity: 1, notes: 'from the phone' }, { product_id: simple.id, quantity: 1, notes: 'to cancel' }] } }) await page.waitForFunction(() => document.querySelectorAll('[data-testid="order-line"]').length === 3, null, { timeout: 8000 }).catch(() => {}) r.check('3.3c: the phone adds items → the counter shows them live', await page.getByTestId('order-line').count() === 3 && (await page.getByTestId('order-lines').textContent()).includes('from the phone')) // cancel one from the counter (the cashier is a manager here: no approval needed) const afterPhone = await api('GET', `/api/orders/${tableOrder}`, { token: maria }) const toCancel = afterPhone.items.find(i => i.notes === 'to cancel').id const fromPhone = afterPhone.items.find(i => i.notes === 'from the phone').id await page.locator(`[data-testid="order-line"][data-item="${toCancel}"]`).click() await page.getByTestId('table-cancel').click() await page.getByTestId('cancel-confirm').click() await page.waitForFunction(() => document.querySelectorAll('[data-testid="order-line"]').length === 2, null, { timeout: 8000 }).catch(() => {}) r.check('3.3c: cancel at the counter takes the item off', await page.getByTestId('order-line').count() === 2) r.check('3.3c: …and the phone hears it', await heard(m => m.type === 'order_updated' && m.data.action === 'items_cancelled' && m.data.item_ids?.includes(toCancel))) // pay the phone's item in cash (selected), then the rest by card, then close await page.locator(`[data-testid="order-line"][data-item="${fromPhone}"]`).click() await page.getByTestId('table-pay').click() await page.getByTestId('payment-dialog').waitFor({ timeout: 5000 }) r.check('3.3c: Pay takes only the selected item', (await page.getByTestId('pay-confirm').textContent()).includes(simple.price.toFixed(2))) const drawerBeforeTable = drawerBytes.length await page.getByTestId('pay-confirm').click() const paidShown = await shown(page, 'table-paid', 8000) // the order reloads after the payment (live, coalesced): wait for the line to turn paid await page.waitForFunction(() => document.querySelectorAll('[data-testid="order-line"][data-paid="true"]').length === 1, null, { timeout: 8000 }).catch(() => {}) r.check('3.3c: paid some items: the panel says so and the item shows as paid', paidShown && await page.locator('[data-testid="order-line"][data-paid="true"]').count() === 1) for (let i = 0; i < 20 && drawerBytes.length === drawerBeforeTable; i++) await sleep(100) r.check('3.3c: …cash opens the drawer here too', drawerBytes.length > drawerBeforeTable) r.check('3.3c: the phone sees the payment', await heard(m => m.type === 'order_paid' && m.data.order_id === tableOrder) && (await api('GET', `/api/orders/${tableOrder}`, { token: maria })).items.find(i => i.id === fromPhone).status === 'paid') await page.screenshot({ path: path.join(OUT, 'terminal-pos-table.png') }) await page.getByTestId('table-pay').click() await page.getByTestId('pay-card').click() await page.getByTestId('pay-confirm').click() r.check('3.3c: everything paid → Close', await shown(page, 'table-close', 8000)) await page.getByTestId('table-close').click() r.check('3.3c: closed → back to the list, the table is free again', await shown(page, 'pos-tables', 8000) && await page.waitForFunction(id => document.querySelector(`[data-testid="pos-table"][data-table="${id}"]`)?.dataset.state === 'free', shared.id, { timeout: 5000 }).then(() => true).catch(() => false)) r.check('3.3c: the phone hears the table close', await heard(m => m.type === 'order_closed' && m.data.order_id === tableOrder)) // a waiter opens a table on the phone → the counter's list shows it live const phoneTable = counterTables.find(t => !t.order && mariaTables.has(t.id) && t.id !== shared.id) const phoneOrder = await api('POST', '/api/orders/', { token: maria, body: { table_id: phoneTable.id } }) await api('POST', `/api/orders/${phoneOrder.id}/items`, { token: maria, body: { lines: [{ product_id: simple.id, quantity: 2 }] } }) r.check('3.3c: a table opened on the phone shows on the counter at once, with what\'s due', // (opened, then its items: wait for both, the card shows the order before its items arrive) await page.waitForFunction(([id, due]) => { const card = document.querySelector(`[data-testid="pos-table"][data-table="${id}"]`) return card?.dataset.state === 'open' && card.textContent.includes(due) }, [phoneTable.id, (2 * simple.price).toFixed(2)], { timeout: 8000 }).then(() => true).catch(() => false)) await page.screenshot({ path: path.join(OUT, 'terminal-pos-tables.png') }) phoneWs.close() // ── 3.3d: online orders on the POS ────────────────────────────────────── await api('PUT', '/api/platform/modules/connect_menu', { token: boss, body: { enabled: true } }) await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } }) r.check('3.3d: online orders on → the counter gets an Online mode', await shown(page, 'mode-online', 10_000)) // S.5: a delivery comes with its fee (€2.50 here, a line of its own), the customer's time and area const FEE = 2.5 const cloudOrder = (id, type, name, fee = 0, extra = {}) => ({ id, public_ref: `ORD-${String(id).padStart(4, '0')}`, order_type: type, customer_name: name, customer_phone: '6900000000', customer_address: type === 'delivery' ? 'Main square 3' : null, customer_notes: 'Ring twice', status: 'pending_acceptance', items_json: JSON.stringify([{ product_id: simple.id, name: simple.name, quantity: 2, unit_price: simple.price, options: [] }]), subtotal: 2 * simple.price, delivery_fee: fee, total: 2 * simple.price + fee, created_at: new Date().toISOString(), ...extra, }) const chimesBefore = Number(await page.getByTestId('pos-screen').getAttribute('data-chimes')) const forTime = new Date(Date.now() + 2 * 3600_000) forTime.setUTCMinutes(30, 0, 0) cloud.queue.push(cloudOrder(41, 'delivery', 'Nikos Online', FEE, { requested_for: forTime.toISOString(), delivery_area: 'Centre', delivery_area_id: 1 })) const rang = await page.waitForFunction(n => Number(document.querySelector('[data-testid="pos-screen"]')?.dataset.chimes) > n, chimesBefore, { timeout: 15_000 }) .then(() => true).catch(() => false) const badged = await page.waitForFunction(() => document.querySelector('[data-testid="mode-online"]')?.dataset.badge === '1', null, { timeout: 5000 }) .then(() => true).catch(() => false) r.check('3.3d: an order placed online reaches the counter at once: it rings, and the badge counts it', rang && badged, `rang ${rang}, badge ${await page.getByTestId('mode-online').getAttribute('data-badge')}`) r.check('3.3d: …the cloud was told it arrived', cloud.synced.includes(41)) await page.getByTestId('mode-online').click() const onlineCard = page.locator('[data-testid="online-order"][data-status="pending_acceptance"]').first() r.check('3.3d: the New list shows it, waiting for an answer', await onlineCard.waitFor({ timeout: 5000 }).then(() => true).catch(() => false) && (await onlineCard.textContent()).includes('ORD-0041') && (await onlineCard.textContent()).includes('Nikos Online')) const onlineId = Number(await onlineCard.getAttribute('data-order')) await onlineCard.click() r.check('3.3d: the order shows the customer (phone, address, note) and the items', await shown(page, 'online-panel', 5000) && (await page.getByTestId('online-customer').textContent()).includes('Main square 3') && (await page.getByTestId('online-customer').textContent()).includes('Ring twice') && await page.getByTestId('online-line').count() === 1) const whenText = await page.getByTestId('online-when').textContent().catch(() => '') r.check('S.5: the delivery fee is its own line, in the total; the customer\'s time and area show', await page.getByTestId('online-fee').count() === 1 && (await page.getByTestId('online-total').textContent()).includes((2 * simple.price + FEE).toFixed(2)) && /\d\d:30/.test(whenText) && (await page.getByTestId('online-customer').textContent()).includes('Centre'), whenText) r.check('S.5: the venue\'s own fee rules differ (it has none) → the counter is warned, the customer still pays what they saw', await shown(page, 'online-price-diff', 3000)) await page.screenshot({ path: path.join(OUT, 'terminal-pos-online.png') }) const kdsHas = async () => (await api('GET', '/api/kds/orders', { token: boss })).orders.some(o => o.id === onlineId) r.check('3.3d: the kitchen doesn\'t see it before it is accepted', !(await kdsHas())) await page.getByTestId('online-accept').click() await page.waitForFunction(id => document.querySelector(`[data-testid="online-panel"][data-order="${id}"]`)?.dataset.status === 'accepted', onlineId, { timeout: 8000 }).catch(() => {}) r.check('3.3d: Accept → accepted, in the In progress list', await page.getByTestId('online-panel').getAttribute('data-status') === 'accepted' && await page.locator(`[data-testid="online-order"][data-order="${onlineId}"]`).count() === 1) r.check('3.3d: …the kitchen has it now (KDS)', await kdsHas()) for (let i = 0; i < 30 && !cloud.statuses.some(x => x.id === 41 && x.status === 'accepted'); i++) await sleep(100) r.check('3.3d: …and the customer\'s page follows (status sent to the cloud)', cloud.statuses.some(x => x.id === 41 && x.status === 'accepted')) r.check('3.3d: …the badge went back to 0', await page.getByTestId('mode-online').getAttribute('data-badge') === '0') for (const to of ['preparing', 'out_for_delivery']) { await page.getByTestId('online-next').click() await page.waitForFunction(st => document.querySelector('[data-testid="online-panel"]')?.dataset.status === st, to, { timeout: 8000 }).catch(() => {}) } r.check('3.3d: Start preparing → Out for delivery', await page.getByTestId('online-panel').getAttribute('data-status') === 'out_for_delivery') const drawerBeforeOnline = drawerBytes.length await page.getByTestId('online-finish').click() await page.getByTestId('payment-dialog').waitFor({ timeout: 5000 }) await page.getByTestId('pay-confirm').click() await page.waitForFunction(() => document.querySelector('[data-testid="online-panel"]')?.dataset.status === 'delivered', null, { timeout: 8000 }).catch(() => {}) r.check('3.3d: the driver\'s cash taken at the counter → delivered', await page.getByTestId('online-panel').getAttribute('data-status') === 'delivered') for (let i = 0; i < 20 && drawerBytes.length === drawerBeforeOnline; i++) await sleep(100) const paidOnline = await api('GET', `/api/orders/${onlineId}`, { token: boss }) r.check('3.3d: …the drawer opened and the items are paid (S.5: the fee too)', drawerBytes.length > drawerBeforeOnline && paidOnline.items.every(i => i.status === 'paid') && paidOnline.items.some(i => i.system_key === 'delivery_fee' && i.unit_price === FEE)) r.check('S.5: …the kitchen never got the fee line', !(await api('GET', '/api/kds/orders', { token: boss })).orders .some(o => o.items.some(i => paidOnline.items.find(x => x.id === i.id)?.system_key))) for (let i = 0; i < 30 && !cloud.statuses.some(x => x.id === 41 && x.status === 'delivered'); i++) await sleep(100) r.check('3.3d: …and the cloud heard every step', ['accepted', 'preparing', 'out_for_delivery', 'delivered'] .every(st => cloud.statuses.some(x => x.id === 41 && x.status === st)), JSON.stringify(cloud.statuses)) // a second order is rejected with a reason the customer sees await page.getByTestId('online-list-incoming').click() cloud.queue.push(cloudOrder(42, 'dine_in', 'Late Guest')) const secondOnline = page.locator('[data-testid="online-order"][data-status="pending_acceptance"]').first() await secondOnline.waitFor({ timeout: 15_000 }).catch(() => {}) await secondOnline.click() await page.getByTestId('online-reject').click() await page.getByTestId('reason-busy').click() await page.getByTestId('reject-confirm').click() for (let i = 0; i < 50 && !cloud.statuses.some(x => x.id === 42); i++) await sleep(100) const rejected = cloud.statuses.find(x => x.id === 42) r.check('3.3d: Reject with a reason → the customer is told why', rejected?.status === 'rejected' && rejected.rejection_reason?.length > 0, JSON.stringify(rejected)) r.check('3.3d: …and it leaves the New list', await page.waitForFunction(() => !document.querySelector('[data-testid="online-order"]'), null, { timeout: 5000 }) .then(() => true).catch(() => false)) // ── S.6: a table booking with two dishes: confirmed, the dishes reach the KDS at the fire time ── const ordering = await api('GET', '/api/connect/fees/ordering', { token: boss }) await api('PUT', '/api/connect/fees/ordering', { token: boss, body: { ...ordering, reservations: { ...ordering.reservations, enabled: true, with_food: true, fire_minutes: 1 } } }) const arriving = new Date(Date.now() + 90_000) // the kitchen gets it a minute before: in ~30 s cloud.queue.push(cloudOrder(43, 'preorder', 'Eleni Booking', 0, { party_size: 4, requested_for: arriving.toISOString(), sales_point: 'online_preorder', customer_address: null })) await page.getByTestId('online-list-bookings').click() const bookingCard = page.locator('[data-testid="booking"][data-status="requested"]').first() r.check('S.6: a booking request reaches the counter (Online → Bookings), waiting for an answer', await bookingCard.waitFor({ timeout: 15_000 }).then(() => true).catch(() => false) && (await bookingCard.textContent()).includes('Eleni Booking')) await bookingCard.click() r.check('S.6: …it shows the party and the two dishes ordered ahead', await shown(page, 'booking-panel', 5000) && (await page.getByTestId('booking-guest').textContent()).includes('4 people') && (await page.getByTestId('booking-food').textContent()).includes(`2× ${simple.name}`)) await page.screenshot({ path: path.join(OUT, 'terminal-pos-booking.png') }) await page.getByTestId('booking-confirm').click() await page.waitForFunction(() => document.querySelector('[data-testid="booking-panel"]')?.dataset.status === 'pending', null, { timeout: 8000 }).catch(() => {}) for (let i = 0; i < 30 && !cloud.statuses.some(x => x.id === 43); i++) await sleep(100) r.check('S.6: Confirm → confirmed, and the customer is told', await page.getByTestId('booking-panel').getAttribute('data-status') === 'pending' && cloud.statuses.some(x => x.id === 43 && x.status === 'accepted'), JSON.stringify(cloud.statuses.filter(x => x.id === 43))) const bookingOnKds = async () => (await api('GET', '/api/kds/orders', { token: boss })).orders.find(o => o.online_ref === 'ORD-0043') r.check('S.6: …the kitchen does not get the dishes at once', !(await bookingOnKds()) && (await page.getByTestId('booking-food').textContent()).includes('kitchen')) let fired = null for (let i = 0; i < 90 && !fired; i++) { fired = await bookingOnKds(); if (!fired) await sleep(1000) } const firedAt = Date.now() r.check('S.6: …at the fire time (a minute before arrival) the two dishes are on the KDS, with the time', !!fired && fired.items.reduce((s, i) => s + i.quantity, 0) === 2 && !!fired.requested_for && firedAt < arriving.getTime() - 50_000, JSON.stringify(fired?.items?.map(i => [i.product_name, i.quantity]))) const freeTable = (await api('GET', '/api/pos/tables', { token: boss })).tables.find(x => !x.order) await page.getByTestId('booking-table').selectOption(String(freeTable.id)) await page.getByTestId('booking-arrive').click() for (let i = 0; i < 30 && !cloud.statuses.some(x => x.id === 43 && x.status === 'delivered'); i++) await sleep(100) const seated = await api('GET', `/api/orders/${fired?.id}`, { token: boss }).catch(() => null) r.check('S.6: the guests arrive and are seated → their order moves to the table; the customer\'s page says welcome', seated?.table_id === freeTable.id && cloud.statuses.some(x => x.id === 43 && x.status === 'delivered')) // ── 3.3e: refunds ─────────────────────────────────────────────────────── // fiscal receipts on, with today's text-file bridge: it can't take credit notes yet, so the // cashier is told to issue it on the machine (owner decision 2026-11-15) await api('PUT', '/api/settings/fiscal.enabled', { token: boss, body: { value: 'true' } }) const shiftBeforeRefund = await page.evaluate(async () => (await window.__xeniaClient.get('/api/shifts/my')).data) await page.getByTestId('mode-receipts').click() const saleReceipt = page.locator(`[data-testid="receipt"][data-order="${saleOrder}"]`) r.check('3.3e: Receipts lists today\'s paid orders of the cashier\'s shift (the first quick sale too)', await saleReceipt.waitFor({ timeout: 8000 }).then(() => true).catch(() => false) && (await saleReceipt.textContent()).includes(expected)) await saleReceipt.click() await page.locator(`[data-testid="receipt-panel"][data-order="${saleOrder}"]`).waitFor({ timeout: 5000 }).catch(() => {}) const simpleLine = page.locator('[data-testid="receipt-line"]', { hasText: simple.name }) await simpleLine.locator('button').first().click() await page.getByTestId('refund-qty').locator('button').first().click() // 2 → 1 r.check('3.3e: tap an item, pick how many → the refund amount', (await page.getByTestId('refund-start').textContent()).includes(simple.price.toFixed(2)) && await page.getByTestId('refund-cash').getAttribute('aria-checked') === 'true') await page.getByTestId('refund-reason-quality').click() await page.getByTestId('refund-start').click() r.check('3.3e: the confirmation names the amount and reminds about the credit note', await shown(page, 'refund-dialog', 5000) && (await page.getByTestId('refund-dialog').textContent()).includes('credit note')) await sleep(400) // the dialog's entrance await page.screenshot({ path: path.join(OUT, 'terminal-pos-refund.png') }) const drawerBeforeRefund = drawerBytes.length await page.getByTestId('refund-confirm').click() r.check('3.3e: refunded → "issue the credit note on the fiscal machine"', await shown(page, 'manual-credit-note', 8000) && (await page.getByTestId('manual-credit-note').textContent()).includes(simple.price.toFixed(2))) for (let i = 0; i < 20 && drawerBytes.length === drawerBeforeRefund; i++) await sleep(100) r.check('3.3e: …the cash drawer opened for the money going back', drawerBytes.length > drawerBeforeRefund) const shiftAfterRefund = await page.evaluate(async () => (await window.__xeniaClient.get('/api/shifts/my')).data) r.check('3.3e: …and the shift\'s cash went down by the amount', Math.abs(shiftAfterRefund.cash_refunds - simple.price) < 0.005 && Math.abs((shiftBeforeRefund.net_to_deliver - shiftAfterRefund.net_to_deliver) - simple.price) < 0.005, JSON.stringify({ before: shiftBeforeRefund.net_to_deliver, after: shiftAfterRefund.net_to_deliver, refunds: shiftAfterRefund.cash_refunds })) await page.getByTestId('manual-credit-note-ok').click() r.check('3.3e: the order shows what was given back; one of the two is still refundable', await page.waitForFunction(({ order, name }) => document.querySelector('[data-testid="receipt-refunds"]') && document.querySelector(`[data-testid="receipt"][data-order="${order}"] [data-testid="receipt-refunded"]`) && [...document.querySelectorAll('[data-testid="receipt-line"]')].some(l => l.textContent.includes(name) && l.textContent.includes('already given back')), { order: saleOrder, name: simple.name }, { timeout: 8000 }).then(() => true).catch(() => false)) await api('PUT', '/api/settings/fiscal.enabled', { token: boss, body: { value: 'false' } }) await page.getByTestId('mode-sale').click() // ── 3.4: the customer display ──────────────────────────────────────────── // two displays: one linked to this counter, one not (another counter's); the venue's idle screen await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {}) await api('PUT', '/api/settings/venue.name', { token: boss, body: { value: 'Taverna E2E' } }) // its own address for the pairing rate limit (one per screen in a real venue) const myDisplay = await screen(await (await browser.newContext({ viewport: { width: 1024, height: 600 }, extraHTTPHeaders: { 'x-real-ip': '10.9.0.41' } })).newPage()) await pairFromManager(myDisplay, boss, { app_key: 'customer_display', name: 'Display at the counter', linked_device_id: kitchen.id }) // its own address for the pairing rate limit (one per screen in a real venue) const otherDisplay = await screen(await (await browser.newContext({ viewport: { width: 1024, height: 600 }, extraHTTPHeaders: { 'x-real-ip': '10.9.0.42' } })).newPage()) await pairFromManager(otherDisplay, boss, { app_key: 'customer_display', name: 'Display elsewhere' }) await shown(otherDisplay, 'display-idle', 15_000) // both screens up before the sale r.check('3.4: a display linked to the counter shows the idle screen: the venue name (the default)', await shown(myDisplay, 'display-idle', 15_000) && (await myDisplay.getByTestId('display-name').textContent()) === 'Taverna E2E') await simpleCard.locator('button').first().click() await simpleCard.locator('button').first().click() const started = Date.now() const seen = await myDisplay.waitForFunction(() => document.querySelector('[data-testid="app-customer_display"]')?.dataset.view === 'cart', null, { timeout: 5000 }) .then(() => Date.now() - started).catch(() => null) const shownTotal = await myDisplay.getByTestId('display-total').textContent().catch(() => '') r.check('3.4: a sale shows on its own display within a second (the lines and the total)', seen != null && seen < 1500 && shownTotal.includes((2 * simple.price).toFixed(2)) && await myDisplay.getByTestId('display-line').count() === 1, `${seen} ms, ${shownTotal}`) r.check('3.4: …and not on another counter\'s display', await otherDisplay.getByTestId('app-customer_display').getAttribute('data-view') === 'idle') await myDisplay.screenshot({ path: path.join(OUT, 'terminal-display-cart.png') }) await page.getByTestId('charge').click() await page.getByTestId('payment-dialog').waitFor({ timeout: 5000 }) await page.getByTestId('cash-given').fill('50').catch(() => {}) await page.getByTestId('pay-confirm').click() r.check('3.4: paid → "Thank you" with the change', await shown(myDisplay, 'display-paid', 5000) && (await myDisplay.getByTestId('display-paid').textContent()).includes('Thank you')) await myDisplay.screenshot({ path: path.join(OUT, 'terminal-display-paid.png') }) // the venue's choice: a QR code to its online ordering, then a slideshow of its photos (a look; 5.3) const main = (await api('GET', '/api/display/looks', { token: boss })).find(l => l.is_default) await api('PUT', `/api/display/looks/${main.id}`, { token: boss, body: { config: { style: 'qr', qr_target: 'ordering', qr_caption: 'Order online', theme: 'light' } } }) r.check('3.4: the idle screen follows the look at once (a QR code to the venue ordering, light)', await myDisplay.waitForFunction(() => document.querySelector('[data-testid="display-qr"]'), null, { timeout: 20_000 }).then(() => true).catch(() => false) && (await myDisplay.getByTestId('display-qr').getAttribute('data-link')).includes('/order/') && await myDisplay.evaluate(() => document.documentElement.dataset.theme) === 'light') await myDisplay.screenshot({ path: path.join(OUT, 'terminal-display-qr.png') }) const uploadImg = async (rgb) => { const jpg = execFileSync(PYTHON, ['-c', `import io,sys;from PIL import Image;b=io.BytesIO();Image.new('RGB',(1280,720),(${rgb})).save(b,'JPEG');sys.stdout.buffer.write(b.getvalue())`]) const form = new FormData() form.append('file', new Blob([jpg], { type: 'image/jpeg' }), 'promo.jpg') const res = await fetch(`${backend.url}/api/media`, { method: 'POST', headers: { authorization: `Bearer ${boss}` }, body: form }) return res.json() } const [a, b, c] = [await uploadImg('200,40,40'), await uploadImg('40,200,40'), await uploadImg('40,40,200')] await api('PUT', `/api/display/looks/${main.id}`, { token: boss, body: { config: { style: 'slideshow', slides: [a.id, b.id], slide_seconds: 3, message: 'Today: 2 for 1' } } }) r.check('3.4: …or a slideshow of its photos (from the media library), with its line of text', await myDisplay.waitForFunction(() => document.querySelectorAll('[data-testid="display-slide"]').length === 2, null, { timeout: 20_000 }).then(() => true).catch(() => false) && (await myDisplay.getByTestId('display-message').textContent()) === 'Today: 2 for 1') // 5.3: the other display gets its own look, another slideshow const promo = await api('POST', '/api/display/looks', { token: boss, body: { name: 'Promo', config: { style: 'slideshow', slides: [c.id], slide_seconds: 5 } } }) const otherId = (await api('GET', '/api/display/displays', { token: boss })).find(d => d.name === 'Display elsewhere').id await api('PUT', `/api/display/displays/${otherId}/look`, { token: boss, body: { look_id: promo.id } }) const slidesOf = page => page.evaluate(() => [...document.querySelectorAll('[data-testid="display-slide"]')].map(e => e.getAttribute('src') || e.style.backgroundImage || '')) const otherSlides = await waitFor(async () => { const s = await slidesOf(otherDisplay); return s.length === 1 ? s : null }, 20_000, 300) const mySlides = await slidesOf(myDisplay) r.check('5.3: two displays, two slideshows from the library (each display its own look)', !!otherSlides && otherSlides[0].includes(c.sha256) && mySlides.length === 2 && mySlides.every(u => !u.includes(c.sha256)), JSON.stringify({ mine: mySlides.map(u => u.slice(-40)), other: otherSlides?.map(u => u.slice(-40)) })) await otherDisplay.screenshot({ path: path.join(OUT, 'terminal-display-promo.png') }) // ── 3.5: caller ID at the counter ──────────────────────────────────────── await api('PUT', '/api/platform/modules/caller_id', { token: boss, body: { enabled: true } }).catch(() => {}) await api('POST', '/api/customers/', { token: boss, body: { name: 'Kostas Regular', phone: '+30 697 555 1234', notes: 'Always extra tzatziki' } }) const callRes = await fetch(`${backend.url}/api/phone/call-event?caller=6975551234&ext=100`) r.check('3.5: the phone system\'s webhook takes the call', callRes.ok, String(callRes.status)) r.check('3.5: the counter pops up who is calling (matched on the server)', await shown(page, 'call-popup', 8000) && (await page.getByTestId('call-name').textContent()) === 'Kostas Regular' && (await page.getByTestId('call-popup').textContent()).includes('extra tzatziki')) await page.screenshot({ path: path.join(OUT, 'terminal-pos-call.png') }) await page.getByTestId('call-takeaway').click() r.check('3.5: …"New takeaway sale" opens a takeaway sale', await page.getByTestId('type-takeaway').getAttribute('aria-checked') === 'true' && await page.getByTestId('call-popup').count() === 0) const oldWs = await new Promise(res => { const ws = new WebSocket(`${backend.url.replace('http', 'ws')}/api/phone/ws`) ws.onopen = () => { ws.close(); res('open') } ws.onerror = () => res('refused') setTimeout(() => res('timeout'), 5000) }) r.check('3.5: the old public call socket is gone (nothing listens without signing in)', oldWs !== 'open', oldWs) await myDisplay.context().close() await otherDisplay.context().close() drawerServer.close() await page.getByRole('button', { name: 'Sign out' }).click() // ── 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() cloudServer.close() } process.exit(r.done() ? 1 : 0)