Files
xenia-pos-local/tests/e2e/qr_table.mjs
T
bonaminandClaude Opus 5.5 e395d99704 feat(menu): the menu in English and Greek (platform-v2 step 6.4, D-29)
- products.translations / categories.translations (Alembic 0033, core/menu_languages.py: el + en,
  name / description / quick options by their base name; catalog.translation). Empty = the text
  as typed; no machine translation (owner).
- In the manager's product editor ("In English" / "In Greek", quick extras), the category dialog,
  and a menu board's Language (signage MenuContent.language).
- Customer screens only: cloud snapshot names / descriptions per language (C-2), the menu tablet's
  EL / EN switch the names (localize), signage boards; tickets, KDS, counter, phones keep the base.
- Catalogue bundles carry translations; @xenia/access menuLanguages.js (a backend test compares).
- e2e: manager (the other language saved), menu tablet (EN / EL names), QR table (English on
  the menu, the base name on the kitchen's order, Greek page as typed).

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

181 lines
13 KiB
JavaScript

// End-to-end: the QR menu at the table (plan phase 3S, step S.7), with a real cloud and a
// real venue server talking to each other, and the QR menu app in a phone-sized browser.
// Done when: scanning table 5's QR and ordering puts the items on table 5's order, live on
// the waiter's phone and the counter, and a forged table token is refused.
// - the cloud starts empty; a site is registered; the venue's server runs with its keys
// - the venue turns ordering at the table on; table 5's code (from the manager's QR page
// API) opens the menu app at table 5
// - a guest orders two dishes → the items land on table 5's order, go to the kitchen
// (KDS), the live stream announces it (what the waiters' phones and the counter follow)
// and the guest's page says it's in the kitchen
// - a forged code: the menu says the code isn't valid and an order with it is refused
// - a new code for table 5: the old one stops working
// node qr_table.mjs
import { spawn } from 'node:child_process'
import { mkdirSync, openSync, rmSync } from 'node:fs'
import crypto from 'node:crypto'
import path from 'node:path'
import { chromium } from 'playwright'
import { BROWSER_CHANNEL, CLOUD, OUT, PYTHON, REPO, reporter, sleep } from './lib/env.mjs'
import { killTree, login, startBackend, waitHttp } from './lib/proc.mjs'
const CLOUD_PORT = 8114
const SITE_PORT = 8063
const APP_PORT = 5212
const CLOUD_URL = `http://127.0.0.1:${CLOUD_PORT}`
const APP_DIR = path.join(REPO, 'cloud-service', 'connect_frontend', 'menu-app')
const r = reporter('QR menu at the table: a real cloud and venue, table 5 orders')
const procs = []
let backend, browser
function start(cmd, args, opts, logName) {
const log = openSync(path.join(OUT, logName), 'w')
const p = spawn(cmd, args, { ...opts, shell: process.platform === 'win32', detached: process.platform !== 'win32', stdio: ['ignore', log, log] })
procs.push(p)
return p
}
async function call(base, method, url, { body, headers = {}, token } = {}) {
const res = await fetch(`${base}${url}`, { method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}), ...headers },
body: body ? JSON.stringify(body) : undefined })
const text = await res.text()
let data = null
try { data = text ? JSON.parse(text) : null } catch { data = text }
if (!res.ok) { const e = new Error(`${method} ${url} → ${res.status} ${text.slice(0, 300)}`); e.status = res.status; e.data = data; throw e }
return data
}
const cloud = (m, u, o) => call(CLOUD_URL, m, u, o)
try {
// ── the cloud, empty; a venue registered on it ───────────────────────────
const tmp = path.join(OUT, 'qr-table-cloud')
rmSync(tmp, { recursive: true, force: true })
mkdirSync(tmp, { recursive: true })
const key = crypto.generateKeyPairSync('ed25519').privateKey.export({ format: 'der', type: 'pkcs8' }).subarray(-32).toString('base64')
start(PYTHON, ['-m', 'uvicorn', 'main:app', '--port', String(CLOUD_PORT)], {
cwd: CLOUD, env: { ...process.env, DATABASE_URL: `sqlite:///${path.join(tmp, 'cloud.db').replace(/\\/g, '/')}`, ADMIN_USERNAME: 'e2eadmin',
ADMIN_PASSWORD: 'e2e-admin-pass', SECRET_KEY: 'e2e', LICENSE_SIGNING_KEY: key, PYTHONIOENCODING: 'utf-8',
PUBLIC_APPS_URL: `http://localhost:${APP_PORT}` },
}, 'qr-table-cloud.log')
await waitHttp(`${CLOUD_URL}/docs`, true, 60_000)
const admin = await cloud('POST', '/api/auth/login', { body: { username: 'e2eadmin', password: 'e2e-admin-pass' } })
const site = await cloud('POST', '/api/sites/', { token: admin.access_token,
body: { name: 'Taverna', owner_name: 'O', contact_email: 'o@example.com', license_expires_at: '2030-01-01T00:00:00+00:00' } })
// ── the venue's server, with that site's keys ────────────────────────────
backend = await startBackend({ port: SITE_PORT, siteId: site.site_id, siteKey: site.secret_key, cloudUrl: CLOUD_URL, env: { LICENSE_MODE: 'off', CONNECT_SYNC_INTERVAL_SECONDS: '1' } })
const boss = await login(backend.url)
const api = (m, u, o = {}) => call(backend.url, m, u, { token: boss, ...o })
await api('PUT', '/api/platform/modules/connect_menu', { body: { enabled: true } })
await api('PUT', '/api/platform/modules/connect_orders', { body: { enabled: true } })
await api('POST', '/api/business-day/open', { body: {} }).catch(() => {})
const t5 = (await api('GET', '/api/tables/')).find(t => t.number === 5)
r.check('the venue has a table 5', !!t5)
// the venue turns ordering at the table on; table 5's code
let qr = await api('PUT', '/api/connect/qr/ordering', { body: { on: true } })
// the heartbeat brings the apps' address; the codes then point at the menu app
for (let i = 0; i < 40 && !qr.menu_url.startsWith(`http://localhost:${APP_PORT}`); i++) { await sleep(500); qr = await api('GET', '/api/connect/qr') }
const code5 = qr.tables.find(t => t.id === t5.id)
r.check('table 5 has its own code, pointing at the QR menu app', !!code5 && code5.url.startsWith(`http://localhost:${APP_PORT}/menu/${site.site_id}?t=`), code5?.url)
const token5 = new URL(code5.url).searchParams.get('t')
// 6.4: a dish translated to English (the venue types its menu in Greek)
const firstDish = (await api('GET', '/api/products/')).find(p => !p.is_service_item && p.is_available && p.sold_at.includes('qr_table'))
await api('PUT', `/api/products/${firstDish.id}`, { body: { translations: { en: { name: 'E2E dish in English' } } } })
// the code reaches the cloud with the menu (pushed within seconds of the change)
let seen = null
const translated = m => m?.categories?.some(c => c.products.some(p => p.id === firstDish.id && p.names?.en === 'E2E dish in English'))
for (let i = 0; i < 60 && !(seen?.table && translated(seen)); i++) {
seen = await cloud('GET', `/api/menu/${site.site_id}?t=${encodeURIComponent(token5)}`).catch(() => null)
if (!(seen?.table && translated(seen))) await sleep(500)
}
r.check('6.4: the cloud menu carries the dish\'s name per language', translated(seen))
r.check('the cloud knows table 5 by its code (the hash came with the menu), and ordering is on', seen?.table?.id === t5.id && seen.table_ordering === true,
JSON.stringify(seen?.table))
const dishes = seen.categories.flatMap(c => c.products).filter(p => p.digital_available !== false && (!p.sold_at || p.sold_at.includes('qr_table')))
const d1 = dishes.find(p => p.id === firstDish.id)
const d2 = dishes.find(p => p.id !== firstDish.id)
// ── the menu app, built for this cloud ────────────────────────────────────
const build = spawn('npx', ['vite', 'build'], { cwd: APP_DIR, shell: process.platform === 'win32', env: { ...process.env, VITE_CLOUD_URL: CLOUD_URL }, stdio: 'ignore' })
r.check('the QR menu app builds with the cloud address', await new Promise(res => build.on('exit', code => res(code === 0))))
start('npx', ['vite', 'preview', '--port', String(APP_PORT), '--strictPort'], { cwd: APP_DIR }, 'qr-table-preview.log')
await waitHttp(`http://localhost:${APP_PORT}/menu/`, true, 60_000)
// the live stream the waiters' phones and the counter follow
const events = []
const ws = new WebSocket(`ws://127.0.0.1:${SITE_PORT}/api/ws/connect`)
ws.onopen = () => ws.send(JSON.stringify({ cursor: 0, token: boss }))
ws.onmessage = m => { try { events.push(JSON.parse(m.data)) } catch { /* not json */ } }
browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
const page = await browser.newPage({ viewport: { width: 390, height: 844 }, locale: 'en-GB' })
const errors = []
page.on('pageerror', e => errors.push(e.message))
// ── table 5 scans and orders ─────────────────────────────────────────────
await page.goto(code5.url)
r.check('scanning table 5: the menu says "Table 5" and lets them order', await page.getByTestId('table-banner').waitFor({ timeout: 15_000 }).then(() => true).catch(() => false)
&& (await page.getByTestId('table-banner').textContent()).includes(seen.table.label))
r.check('6.4: in English the menu shows the dish\'s English name', (await page.locator(`[data-testid="menu-product"][data-product="${d1.id}"]`).textContent()).includes('E2E dish in English'))
await page.locator(`[data-testid="menu-product"][data-product="${d1.id}"]`).getByTestId('menu-add').click()
await page.locator(`[data-testid="menu-product"][data-product="${d2.id}"]`).getByTestId('menu-add').click()
await page.getByTestId('cart-button').click()
await page.getByTestId('cart-continue').click()
r.check('checkout names the table (no table number to type)', (await page.getByTestId('checkout-table').textContent()).includes(seen.table.label))
await page.screenshot({ path: path.join(OUT, 'qr-table-checkout.png'), fullPage: true })
const before = events.length
await page.getByTestId('place-order').click()
const confirmed = await page.waitForFunction(() => document.querySelector('[data-testid="confirm-status"]')?.dataset.status === 'accepted', null, { timeout: 30_000 })
.then(() => true).catch(() => false)
r.check('the guest\'s page: the order is in the kitchen', confirmed)
await page.screenshot({ path: path.join(OUT, 'qr-table-confirm.png'), fullPage: true })
const onTable = (await api('GET', '/api/orders/active')).find(o => o.table_id === t5.id)
const order = onTable ? await api('GET', `/api/orders/${onTable.id}`) : null
const names = (order?.items ?? []).map(i => i.product_id)
r.check('the two dishes are on table 5\'s order', !!order && names.includes(d1.id) && names.includes(d2.id), JSON.stringify(order?.items?.map(i => [i.product_name, i.unit_price])))
r.check('…at the QR menu\'s prices', order?.items?.find(i => i.product_id === d1.id)?.unit_price === d1.prices.qr_table)
r.check('6.4: the kitchen gets the name as typed (not the English one)', order?.items?.find(i => i.product_id === d1.id)?.product_name === firstDish.name,
order?.items?.find(i => i.product_id === d1.id)?.product_name)
const greek = await browser.newPage({ viewport: { width: 390, height: 844 } })
await greek.addInitScript(() => localStorage.setItem('ot_lang', 'gr'))
await greek.goto(code5.url)
const gCard = greek.locator(`[data-testid="menu-product"][data-product="${d1.id}"]`)
r.check('6.4: in Greek the menu shows the name as typed', await gCard.waitFor({ timeout: 15_000 }).then(() => true).catch(() => false)
&& (await gCard.textContent()).includes(firstDish.digital_name || firstDish.name) && !(await gCard.textContent()).includes('E2E dish in English'))
await greek.close()
r.check('…and in the kitchen (KDS)', (await api('GET', '/api/kds/orders')).orders.some(o => o.id === order?.id))
for (let i = 0; i < 20 && !events.slice(before).some(e => e.type === 'order_updated' && e.data?.table_id === t5.id); i++) await sleep(200)
r.check('…announced live to the waiters\' phones and the counter (order_updated for table 5)',
events.slice(before).some(e => e.type === 'order_updated' && e.data?.table_id === t5.id && e.data?.order_id === order?.id))
// ── a forged code ────────────────────────────────────────────────────────
const page2 = await browser.newPage({ viewport: { width: 390, height: 844 }, locale: 'en-GB' })
await page2.goto(`http://localhost:${APP_PORT}/menu/${site.site_id}?t=forged-token-for-table-5`)
r.check('a forged code: the menu says it isn\'t valid and offers no ordering',
await page2.getByTestId('table-invalid').waitFor({ timeout: 15_000 }).then(() => true).catch(() => false) && await page2.getByTestId('menu-add').count() === 0)
const forged = await cloud('POST', `/api/orders/${site.site_id}`, { body: { order_type: 'dine_in', table_token: 'forged-token-for-table-5', customer_name: 'X',
items: [{ product_id: d1.id, quantity: 1 }] } }).catch(e => e)
r.check('…and an order sent with it is refused', forged?.status === 403 && forged.data?.detail?.code === 'order.table_invalid', JSON.stringify(forged?.data))
// ── a new code for table 5: the old one stops working ────────────────────
await api('POST', `/api/connect/qr/tables/${t5.id}/rotate`)
let old = null
for (let i = 0; i < 60; i++) {
old = await cloud('GET', `/api/menu/${site.site_id}?t=${encodeURIComponent(token5)}`)
if (old.table_invalid) break
await sleep(500)
}
r.check('a new code for table 5: the printed one stops working within seconds', old?.table_invalid === true)
ws.close()
r.check('no page errors', errors.length === 0, errors.join(' | '))
} catch (err) {
r.check(`unexpected error: ${err.message}`, false)
} finally {
await browser?.close()
await backend?.stop()
for (const p of procs) killTree(p)
}
process.exit(r.done() ? 1 : 0)