- Pairing screen: requests a code, shows it big, polls with the secret, new code on expiry, keeps the device token; "removed from the venue" notice after a revoke. - Sign-in per device mode: PIN (name + PinPad), tap your name, password (name + password), none (straight into the app). Names = holders of <app>.access, refreshed every 30 s and on reconnect. Slim bar with screen, user and Sign out; idle sign-out after the device's auto_sign_out_minutes; hourly token refresh (same session). - DeviceProvider: GET /api/devices/me (retried while unreachable), session, the live connection with credentials in the first frame (device.updated -> reload, app moved -> sign out, device.revoked -> forget, session.ended -> sign out), offline banner; useLiveEvent for apps. Screen choice is pure (device/flow.js, unit-tested). - Blocked screen: app turned off / not licensed / device refused, recovers by itself. - @xenia/access AccessProvider: autoRetryMs (retry bootstrap while unreachable). - Tests: terminal unit tests (screen choice, live actions, idle, pairing polls), new tests/e2e/terminal.mjs (18 checks), manager.mjs owner flow now pairs and signs in on the real terminal screen; run-all runs terminal.mjs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
183 lines
9.3 KiB
JavaScript
183 lines
9.3 KiB
JavaScript
// Starting and stopping what the suites run against: local backends on a
|
|
// seeded throwaway database, nginx containers serving the waiter build, the
|
|
// Vite dev server, and isolated docker-compose stacks.
|
|
import { execFileSync, spawn } from 'node:child_process'
|
|
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
import path from 'node:path'
|
|
import { BACKEND, CS, OUT, PYTHON, WAITER, sleep } from './env.mjs'
|
|
import { SUPPORT_MASTER, siteSecret, supportLogin } from './support.mjs'
|
|
|
|
/** Kill a process and its children (npx/shell wrappers on Windows). */
|
|
export function killTree(child) {
|
|
if (!child || child.exitCode !== null) return
|
|
if (process.platform === 'win32') {
|
|
try { execFileSync('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore' }) } catch {}
|
|
} else {
|
|
try { process.kill(-child.pid) } catch { child.kill() }
|
|
}
|
|
}
|
|
|
|
export async function waitHttp(url, up = true, timeoutMs = 60_000) {
|
|
const t0 = Date.now()
|
|
while (Date.now() - t0 < timeoutMs) {
|
|
const ok = await fetch(url, { signal: AbortSignal.timeout(2000) }).then(() => true, () => false)
|
|
if (ok === up) return
|
|
await sleep(500)
|
|
}
|
|
throw new Error(`${url} did not ${up ? 'come up' : 'go down'} within ${timeoutMs / 1000}s`)
|
|
}
|
|
|
|
/**
|
|
* A fresh demo-seeded database (demo_seed.py: manager + 4 waiters, 13 tables,
|
|
* order history). Seeded once into out/seed.db, then copied per test run.
|
|
*/
|
|
/** True for a database made by v1 code (tables but no alembic_version): v2 refuses those (CS-1). */
|
|
function isV1Database(file) {
|
|
const v2 = execFileSync(PYTHON, ['-c', 'import sqlite3, sys; print(sqlite3.connect(sys.argv[1]).execute("select count(*) from sqlite_master where name=?", ("alembic_version",)).fetchone()[0])', file], { encoding: 'utf8' })
|
|
return !Number(v2)
|
|
}
|
|
|
|
export function seededDataDir(label = 'data') {
|
|
const template = path.join(OUT, 'seed.db')
|
|
// A template seeded by v1 code has no alembic_version: v2 refuses it (CS-1), so reseed
|
|
if (existsSync(template) && isV1Database(template)) {
|
|
console.log(' seed.db was made by v1 code - reseeding'); rmSync(template, { force: true })
|
|
}
|
|
if (!existsSync(template)) {
|
|
console.log(' seeding a demo database (once)…')
|
|
const partial = `${template}.partial`
|
|
rmSync(partial, { force: true })
|
|
execFileSync(PYTHON, ['demo_seed.py'], {
|
|
cwd: BACKEND, stdio: 'ignore',
|
|
env: { ...process.env, DATABASE_URL: `sqlite:///${partial.replace(/\\/g, '/')}`, PYTHONIOENCODING: 'utf-8' },
|
|
})
|
|
// Only a database that really holds the demo data becomes the template
|
|
const count = execFileSync(PYTHON, ['-c', 'import sqlite3, sys; print(sqlite3.connect(sys.argv[1]).execute("select count(*) from orders").fetchone()[0])', partial], { encoding: 'utf8' })
|
|
if (!Number(count)) throw new Error('demo_seed.py produced no orders — check local_backend/demo_seed.py')
|
|
renameSync(partial, template)
|
|
}
|
|
const dir = mkdtempSync(path.join(OUT, `${label}-`))
|
|
copyFileSync(template, path.join(dir, 'pos.db'))
|
|
return dir
|
|
}
|
|
|
|
/** Local backend (uvicorn) on `port` with its own data dir. Returns { url, dataDir, stop() }. */
|
|
export async function startBackend({ port = 8055, siteId = 'test-site-1', siteKey = 'x', cloudUrl = '', dataDir, env = {} } = {}) {
|
|
dataDir ??= seededDataDir(`backend-${port}`)
|
|
const log = openSync(path.join(dataDir, 'backend.log'), 'a')
|
|
const child = spawn(PYTHON, ['-m', 'uvicorn', 'main:app', '--host', '0.0.0.0', '--port', String(port)], {
|
|
cwd: BACKEND, stdio: ['ignore', log, log],
|
|
env: {
|
|
...process.env, DATABASE_URL: `sqlite:///${path.join(dataDir, 'pos.db').replace(/\\/g, '/')}`,
|
|
SITE_ID: siteId, SITE_KEY: siteKey, CLOUD_URL: cloudUrl, SECRET_KEY: 'e2e-secret',
|
|
// No cloud = a test backend: licensing off (every module). The license suite passes a cloudUrl.
|
|
LICENSE_MODE: cloudUrl ? 'enforced' : 'off',
|
|
SUPPORT_SECRET: siteSecret(SUPPORT_MASTER, siteId), ...env,
|
|
},
|
|
})
|
|
const url = `http://127.0.0.1:${port}`
|
|
await waitHttp(`${url}/api/system/health`)
|
|
return { url, dataDir, child, stop: async () => { killTree(child); await waitHttp(`${url}/api/system/health`, false).catch(() => {}) } }
|
|
}
|
|
|
|
/** A superadmin token for a test backend, through support access (challenge code). */
|
|
export const login = baseUrl => supportLogin(baseUrl)
|
|
|
|
/** nginx:alpine serving a waiter build (`dist`) with the waiter's own nginx.conf, /api → host backend. */
|
|
export async function serveWaiterBuild({ name, port, dist = path.join(WAITER, 'dist'), backendPort = 8055 }) {
|
|
const conf = path.join(OUT, `${name}.nginx.conf`)
|
|
writeFileSync(conf, readFileSync(path.join(WAITER, 'nginx.conf'), 'utf8').replace(/http:\/\/backend:8000/g, `http://host.docker.internal:${backendPort}`))
|
|
try { execFileSync('docker', ['rm', '-f', name], { stdio: 'ignore' }) } catch {}
|
|
execFileSync('docker', ['run', '-d', '--rm', '--name', name, '--add-host', 'host.docker.internal:host-gateway',
|
|
'-p', `${port}:80`, '-v', `${conf}:/etc/nginx/conf.d/default.conf:ro`, '-v', `${dist}:/usr/share/nginx/html:ro`, 'nginx:alpine'],
|
|
{ stdio: 'ignore', env: { ...process.env, MSYS_NO_PATHCONV: '1' } })
|
|
await waitHttp(`http://127.0.0.1:${port}/`)
|
|
return { stop: () => { try { execFileSync('docker', ['rm', '-f', name], { stdio: 'ignore' }) } catch {} } }
|
|
}
|
|
|
|
/** Vite dev server pointed at a backend by URL (VITE_SERVER_URL) — the "native-like" venue mode. */
|
|
export async function startViteNative({ port = 5180, backendUrl }) {
|
|
const log = openSync(path.join(OUT, `vite-${port}.log`), 'w')
|
|
const child = spawn('npx', ['vite', '--port', String(port), '--strictPort'], {
|
|
cwd: WAITER, shell: process.platform === 'win32', detached: process.platform !== 'win32',
|
|
stdio: ['ignore', log, log], env: { ...process.env, VITE_SERVER_URL: backendUrl },
|
|
})
|
|
await waitHttp(`http://localhost:${port}/`)
|
|
await fetch(`http://localhost:${port}/src/main.jsx`).catch(() => {}) // warm the first compile
|
|
await sleep(3000)
|
|
return { stop: () => killTree(child) }
|
|
}
|
|
|
|
/**
|
|
* Isolated docker-compose stack built from this repo (its own project name,
|
|
* images, data dir and host ports) — never touches a developer's running stack.
|
|
*/
|
|
export function composeStack({ project, version, siteId, http, https, manager, terminal, extraEnv = {} }) {
|
|
const dir = path.join(OUT, project)
|
|
mkdirSync(path.join(dir, 'data'), { recursive: true })
|
|
mkdirSync(path.join(dir, 'fiscal'), { recursive: true })
|
|
const db = path.join(dir, 'data', 'pos.db')
|
|
// The stack's data folder is kept between runs; one left by a v1-era run is replaced (CS-1)
|
|
if (existsSync(db) && isV1Database(db)) { console.log(` ${project}: data/pos.db was made by v1 code - replacing`); rmSync(db, { force: true }) }
|
|
if (!existsSync(db)) copyFileSync(path.join(seededDataDir(project), 'pos.db'), db)
|
|
copyFileSync(path.join(CS, 'logo.png'), path.join(dir, 'logo.png'))
|
|
const fwd = p => p.replace(/\\/g, '/')
|
|
const envFile = path.join(dir, 'e2e.env')
|
|
writeFileSync(envFile, Object.entries({
|
|
REGISTRY: 'e2e', VERSION: version, SITE_ID: siteId, SITE_KEY: 'x', CLOUD_URL: '', SECRET_KEY: 'e2e-secret',
|
|
LICENSE_MODE: 'off',
|
|
HOST_IP: '10.0.2.2', TLS_PORT: https, HTTP_PORT: http, SUPPORT_SECRET: siteSecret(SUPPORT_MASTER, siteId),
|
|
DATA_PATH: fwd(path.join(dir, 'data')), LOGO_PATH: fwd(path.join(dir, 'logo.png')), FISCAL_PATH: fwd(path.join(dir, 'fiscal')),
|
|
...extraEnv,
|
|
}).map(([k, v]) => `${k}=${v}`).join('\n') + '\n')
|
|
const ports = path.join(dir, 'ports.yml')
|
|
writeFileSync(ports, `services:
|
|
backend:
|
|
ports: !reset []
|
|
waiter_pwa:
|
|
ports: !reset []
|
|
manager_dashboard:
|
|
ports: !reset []
|
|
terminal:
|
|
ports: !reset []
|
|
netinfo:
|
|
profiles: ["off"]
|
|
proxy:
|
|
ports: !override
|
|
- "${http}:80"
|
|
- "${manager}:8081"
|
|
- "${https}:8443"
|
|
${terminal ? ` - "${terminal}:8082"
|
|
` : ''}`)
|
|
const args = ['compose', '-p', project, '--env-file', envFile, '-f', 'docker-compose.yml', '-f', 'docker-compose.dev.yml', '-f', ports]
|
|
const compose = (...a) => execFileSync('docker', [...args, ...a], { cwd: CS, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
|
|
return {
|
|
dir,
|
|
compose,
|
|
async up() {
|
|
console.log(` building + starting stack ${project} (${version})…`)
|
|
compose('build')
|
|
compose('up', '-d', '--force-recreate')
|
|
await waitHttp(`http://127.0.0.1:${http}/api/system/health`, true, 180_000)
|
|
},
|
|
down() {
|
|
try { compose('down', '-v') } catch {}
|
|
for (const s of ['backend', 'waiter', 'manager', 'terminal']) {
|
|
try { execFileSync('docker', ['rmi', `e2e/pos-${s}:${version}`], { stdio: 'ignore' }) } catch {}
|
|
}
|
|
},
|
|
}
|
|
}
|
|
|
|
/** The terminal app's Vite dev server (plan phase 3) on `port`, proxied to `backendUrl`. */
|
|
export async function startTerminalVite({ port = 5187, backendUrl }) {
|
|
const log = openSync(path.join(OUT, `vite-${port}.log`), 'w')
|
|
const child = spawn('npx', ['vite', '--port', String(port), '--strictPort'], {
|
|
cwd: path.join(CS, 'terminal'), shell: process.platform === 'win32', detached: process.platform !== 'win32',
|
|
stdio: ['ignore', log, log], env: { ...process.env, XENIA_BACKEND: backendUrl },
|
|
})
|
|
await waitHttp(`http://localhost:${port}/`)
|
|
await fetch(`http://localhost:${port}/src/main.jsx`).catch(() => {}) // warm the first compile
|
|
return { url: `http://localhost:${port}`, stop: () => killTree(child) }
|
|
}
|