feat(connect): the QR menu at the table: one code per table, orders straight onto the table
Plan phase 3S, step S.7. - tables.qr_token (migration 0021): a random token per active table; services/table_qr.py (tokens, rotate, the snapshot's `qr` with the tokens' sha256 only, the code's link from the cloud's apps_url); setting connect_menu.table_ordering (read-only by default). - /api/connect/qr (connect_menu.manage): the codes, ordering on/off, a new code per table or for all; table and QR changes push the menu at once (MENU_PATHS). - Pull: a QR order with a table id goes onto the table's open order or a new one (services/qr_orders.py): items at the cloud's prices, kitchen tickets, KDS, order_updated (the waiters' phones and the counter), a `qr_order` message to the order's waiters or the table's zone waiters; audit QR_ORDER (a repeated pull adds nothing); the cloud is told "accepted" (the guest's page: in the kitchen). No usable table or no open day → the counter gets it as before. Waiter app: the message's look. - Manager: Online → Table QR codes (/online/qr): ordering switch, the menu link, a QR card per table (print all), new code per table / for all. - Heartbeat: apps_url kept in the license state. - Tests: tests/test_qr_table.py (5); e2e qr_table.mjs (a real cloud and venue: table 5's code → two dishes on table 5's order, KDS, live event, the guest's page; a forged code refused; a new code kills the old one), in run-all. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,164 @@
|
||||
// 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')
|
||||
// the code reaches the cloud with the menu (pushed within seconds of the change)
|
||||
let seen = null
|
||||
for (let i = 0; i < 60 && !seen?.table; i++) {
|
||||
seen = await cloud('GET', `/api/menu/${site.site_id}?t=${encodeURIComponent(token5)}`).catch(() => null)
|
||||
if (!seen?.table) await sleep(500)
|
||||
}
|
||||
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, d2] = dishes
|
||||
|
||||
// ── 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))
|
||||
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('…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)
|
||||
@@ -24,7 +24,8 @@ const suites = [
|
||||
['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E],
|
||||
['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E],
|
||||
['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E],
|
||||
['order app (cloud: takeaway + delivery)', 'node', ['order_app.mjs'], E2E],
|
||||
['order app (cloud: takeaway + delivery + bookings)', 'node', ['order_app.mjs'], E2E],
|
||||
['QR menu at the table (cloud + venue)', 'node', ['qr_table.mjs'], E2E],
|
||||
['stack (compose: terminal :8082, LAN only)', 'node', ['stack.mjs'], E2E],
|
||||
]
|
||||
if (!process.argv.includes('--no-android')) suites.push(['android (emulator)', 'node', ['android.mjs'], E2E])
|
||||
|
||||
Reference in New Issue
Block a user