Files
xenia-pos-local/tests/e2e/order_app.mjs
T
bonaminandClaude Opus 5.5 70c8f2bb57 feat(connect): table bookings from the online ordering app; food fired to the kitchen before arrival
Plan phase 3S, step S.6.
- Pull: "reservation" / "preorder" orders become Reservations waiting for an answer
  (status "requested"; services/online_reservations.py), with the food ordered ahead kept on
  the booking (items_json at the cloud's prices, the site's price check) — no order yet.
  Migration 0020 (reservations: online_order_cloud_id, online_ref, items_json, total,
  online_price_diff, fire_at, order_id, response_note).
- Confirm → the food's fire time = booking time − fire minutes (setting); the fire worker
  (connect_orders, every 20 s) turns the food into an order at that time (needs an open
  business day; waits otherwise): kitchen tickets, KDS (reference and time). Early arrival
  fires at once. Seating moves the order to the table (refused if the table has an open
  order). Decline / cancel / no-show with a reason. Every step mirrored to the cloud.
- Found: the KDS filter dropped every online order without an online status (SQL NULL in
  NOT(a AND b)) — made NULL-safe.
- Counter: Online → Bookings (requests first, then upcoming), BookingPanel (confirm,
  decline with reasons, food and when it goes to the kitchen, seat at a free table, cancel,
  no-show); the Online badge and chime count booking requests.
- Manager: Online ordering → Table bookings settings (on, food ahead, hours, slot, notice,
  days ahead, party size, fire minutes); the dashboard's reservations card confirms /
  declines online requests; the reservations router delegates online bookings' status steps.
- Tests: tests/test_online_bookings.py (8), unit tests (terminal, manager), e2e: order app
  (book with food → the venue confirms), terminal (request → confirm → the two dishes reach
  the KDS at the fire time, not before → seated), manager (booking settings).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:31:44 +02:00

220 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// End-to-end: the online ordering app (plan phase 3S, step S.4), in a phone-sized browser
// against a real cloud backend (a temp database). Done when: a delivery order with a fee and a
// takeaway order are placed in the browser, priced by the cloud, and tracked to the end.
// - the cloud starts empty; a site is registered and pushes a menu as the venue's server
// does (prices per sales point, delivery areas and fee rules, ordering settings)
// - the app is built with the cloud's address and served by `vite preview` at /order/
// - takeaway: two colas at the takeaway price → placed → tracking page
// - delivery: below the minimum → refused with the minimum; more → the fee for the area
// → placed → the site moves it on (accepted → … → delivered) → the page follows
// node order_app.mjs
import { spawn } from 'node:child_process'
import { openSync, rmSync, mkdirSync } 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, waitHttp } from './lib/proc.mjs'
const CLOUD_PORT = 8113
const APP_PORT = 5211
const CLOUD_URL = `http://127.0.0.1:${CLOUD_PORT}`
const APP_DIR = path.join(REPO, 'cloud-service', 'connect_frontend', 'order-app')
const r = reporter('order app: takeaway + delivery + table booking, priced by the cloud, tracked')
const procs = []
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(method, url, { body, headers = {} } = {}) {
const res = await fetch(`${CLOUD_URL}${url}`, { method, headers: { 'content-type': 'application/json', ...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) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 300)}`)
return data
}
let browser
try {
// ── the cloud, empty ──────────────────────────────────────────────────────
const tmp = path.join(OUT, 'order-app-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' },
}, 'order-app-cloud.log')
await waitHttp(`${CLOUD_URL}/docs`, true, 60_000)
// ── a venue, as the site would set it up ─────────────────────────────────
const admin = await call('POST', '/api/auth/login', { body: { username: 'e2eadmin', password: 'e2e-admin-pass' } })
const site = await call('POST', '/api/sites/', { headers: { authorization: `Bearer ${admin.access_token}` },
body: { name: 'Taverna', owner_name: 'O', contact_email: 'o@example.com', license_expires_at: '2030-01-01T00:00:00+00:00' } })
const siteH = { 'X-Site-ID': site.site_id, 'X-Site-Key': site.secret_key }
const hb = await call('POST', '/api/heartbeat/', { headers: siteH, body: { version: '2.0.0', local_ip: '10.0.0.2', module_catalog: [] } })
const numeric = hb.site_numeric_id
const snapshot = {
timezone: 'Europe/Athens',
categories: [
{ id: 1, name: 'Drinks', products: [
{ id: 11, name: 'Cola 1.5L', base_price: 3.5, digital_price: 3.5, digital_available: true, sold_at: ['qr_table', 'online_takeaway', 'online_delivery'],
prices: { qr_table: 3.5, online_takeaway: 2.5, online_delivery: 2.8 }, quick_options: [{ id: 7, name: 'Ice', price: 0.2 }] },
] },
{ id: 2, name: 'Food', products: [
{ id: 12, name: 'Souvlaki', digital_description: 'Pork, pita, tzatziki', base_price: 4, digital_price: 4, digital_available: true,
sold_at: ['online_takeaway', 'online_delivery', 'online_preorder'], prices: { online_takeaway: 4, online_delivery: 4.2, online_preorder: 3.8 }, quick_options: [] },
{ id: 13, name: 'Soup of the day', base_price: 6, digital_available: false, sold_at: ['online_delivery'], prices: { online_delivery: 6 }, quick_options: [] },
] },
],
fees: {
areas: [{ id: 1, name: 'Centre', postcodes: ['24100'], is_active: true }, { id: 2, name: 'Hills', postcodes: ['24131'], is_active: true }],
rules: [
{ id: 1, name: 'Minimum', action: 'minimum', value: 5, sales_points: ['online_delivery'] },
{ id: 2, name: 'Base', action: 'set', value: 2, sales_points: ['online_delivery'] },
{ id: 3, name: 'Hills', area_ids: [2], action: 'add', value: 1, sales_points: ['online_delivery'] },
],
},
ordering: { services: ['takeaway', 'delivery'], hours: {}, prep_minutes: 20, slot_minutes: 15, days_ahead: 0, asap: true,
// S.6: table bookings, with food ordered ahead
reservations: { enabled: true, with_food: true, hours: {}, slot_minutes: 30, days_ahead: 7, notice_minutes: 0, party_max: 6, fire_minutes: 20 } },
}
await call('POST', '/api/menu/sync', { headers: siteH, body: { site_id: numeric, snapshot_json: JSON.stringify(snapshot) } })
// ── the 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' })
const built = await new Promise(res => build.on('exit', code => res(code === 0)))
r.check('the order app builds with the cloud address', built)
start('npx', ['vite', 'preview', '--port', String(APP_PORT), '--strictPort'], { cwd: APP_DIR }, 'order-app-preview.log')
await waitHttp(`http://localhost:${APP_PORT}/order/`, true, 60_000)
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))
const product = id => page.locator(`[data-testid="product"][data-product="${id}"]`).first()
await page.goto(`http://localhost:${APP_PORT}/order/${site.site_id}`)
r.check('the venue and its services show (takeaway first, open now)', await page.getByTestId('venue-name').waitFor({ timeout: 15_000 }).then(() => true).catch(() => false)
&& await page.getByTestId('service-takeaway').getAttribute('aria-checked') === 'true' && (await page.getByTestId('open-state').textContent()).includes('Open'))
r.check('takeaway prices; the soup (delivery only) is not on the takeaway menu',
(await product(11).getByTestId('price').textContent()).includes('2.50') && await product(13).count() === 0)
await page.getByTestId('service-delivery').click()
r.check('delivery prices; the soup shows as sold out', (await product(11).getByTestId('price').textContent()).includes('2.80')
&& (await product(13).textContent()).includes('Sold out'))
await page.screenshot({ path: path.join(OUT, 'order-app-menu.png'), fullPage: true })
// ── takeaway ─────────────────────────────────────────────────────────────
await page.getByTestId('service-takeaway').click()
await product(12).getByTestId('add').click()
await product(12).getByRole('button', { name: '+' }).click()
await page.getByTestId('view-order').click()
await page.getByTestId('checkout').waitFor({ timeout: 5000 })
await page.waitForFunction(() => document.querySelector('[data-testid="totals"]')?.dataset.total === '8', null, { timeout: 8000 }).catch(() => {})
r.check('takeaway: the cloud prices it (2 × €4.00, no fee)', await page.getByTestId('totals').getAttribute('data-total') === '8'
&& await page.getByTestId('fee').count() === 0)
await page.getByTestId('place-order').click()
r.check('takeaway: name and phone are asked for first', await page.getByText('Enter your name.').count() === 1 && await page.getByText('Enter a phone number we can call.').count() === 1)
await page.getByTestId('f-name').fill('Maria')
await page.getByTestId('f-phone').fill('6900000001')
await page.getByTestId('place-order').click()
await page.getByTestId('track').waitFor({ timeout: 10_000 }).catch(() => {})
r.check('takeaway: placed → the tracking page with the order number and total', (await page.getByTestId('track-ref').textContent().catch(() => '')).includes('ORD-0001')
&& (await page.getByTestId('track-total').textContent()).includes('8.00') && await page.getByTestId('track').getAttribute('data-status') === 'pending_acceptance')
const takeawayUrl = page.url()
// ── delivery ─────────────────────────────────────────────────────────────
await page.goto(`http://localhost:${APP_PORT}/order/${site.site_id}`)
await page.getByTestId('service-delivery').click()
await product(11).getByTestId('add').click()
await page.getByTestId('extras-add').click() // a cola, no extras: €2.80
await page.getByTestId('view-order').click()
await page.getByTestId('f-area').selectOption('1')
await page.waitForFunction(() => document.querySelector('[data-testid="quote-problem"]'), null, { timeout: 8000 }).catch(() => {})
r.check('delivery: below the minimum → refused with the minimum shown', await page.getByTestId('quote-problem').getAttribute('data-code').catch(() => '') === 'minimum_not_met'
&& (await page.getByTestId('quote-problem').textContent()).includes('5.00'))
await page.getByRole('button', { name: 'Back' }).click()
await product(12).getByTestId('add').click() // + souvlaki €4.20 = €7.00
await page.getByTestId('view-order').click()
await page.getByTestId('f-area').selectOption('2') // the hills: €2 + €1
await page.waitForFunction(() => document.querySelector('[data-testid="totals"]')?.dataset.total === '10', null, { timeout: 8000 }).catch(() => {})
r.check('delivery: the area\'s fee comes from the cloud (products €7.00 + fee €3.00)', await page.getByTestId('totals').getAttribute('data-fee') === '3'
&& await page.getByTestId('totals').getAttribute('data-total') === '10', await page.getByTestId('totals').textContent())
await page.getByTestId('f-area').selectOption('1')
await page.waitForFunction(() => document.querySelector('[data-testid="totals"]')?.dataset.total === '9', null, { timeout: 8000 }).catch(() => {})
r.check('delivery: another area, another fee (€2.00)', await page.getByTestId('totals').getAttribute('data-fee') === '2')
await page.getByTestId('f-address').fill('Main square 3')
await page.screenshot({ path: path.join(OUT, 'order-app-checkout.png'), fullPage: true })
await page.getByTestId('place-order').click()
await page.getByTestId('track').waitFor({ timeout: 10_000 }).catch(() => {})
r.check('delivery: placed (the details were remembered) → tracking ORD-0002, €9.00 with the fee',
(await page.getByTestId('track-ref').textContent().catch(() => '')).includes('ORD-0002') && (await page.getByTestId('track-total').textContent()).includes('9.00'))
// ── the venue moves it on; the page follows to the end ───────────────────
const pending = await call('GET', `/api/orders/pending/${numeric}`, { headers: siteH })
const delivery = pending.find(o => o.public_ref === 'ORD-0002')
r.check('the site receives it at the cloud\'s prices with the area', delivery && delivery.total === 9 && delivery.delivery_fee === 2
&& delivery.delivery_area === 'Centre' && delivery.delivery_area_id === 1 && delivery.sales_point === 'online_delivery', JSON.stringify(delivery))
for (const status of ['accepted', 'preparing', 'out_for_delivery', 'delivered']) {
await call('PATCH', `/api/orders/${delivery.id}/status`, { headers: siteH, body: { status } })
const seen = await page.waitForFunction(st => document.querySelector('[data-testid="track"]')?.dataset.status === st, status, { timeout: 15_000 }).then(() => true).catch(() => false)
r.check(`tracking follows: ${status}`, seen)
}
await page.screenshot({ path: path.join(OUT, 'order-app-track.png'), fullPage: true })
// and the takeaway one is rejected with a reason
const takeaway = pending.find(o => o.public_ref === 'ORD-0001')
await call('PATCH', `/api/orders/${takeaway.id}/status`, { headers: siteH, body: { status: 'rejected', rejection_reason: 'Closing early' } })
await page.goto(takeawayUrl)
r.check('a rejected order says so, with the reason', await page.waitForFunction(() => document.querySelector('[data-testid="track"]')?.dataset.status === 'rejected', null, { timeout: 15_000 })
.then(() => true).catch(() => false) && await page.getByText('Closing early').count() === 1)
// ── S.6: book a table, with food ready on arrival ────────────────────────
await page.goto(`http://localhost:${APP_PORT}/order/${site.site_id}`)
await page.getByTestId('service-book').click()
r.check('booking: the days the venue takes bookings (today + 7)', await page.getByTestId('booking').waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
&& await page.getByTestId('book-day').count() === 8)
await page.getByTestId('book-day').nth(1).click() // tomorrow
await page.getByTestId('book-time').filter({ hasText: '20:00' }).click({ timeout: 8000 })
for (let i = 0; i < 2; i++) await page.getByTestId('booking').getByRole('button', { name: '+' }).click()
r.check('booking: 4 people, tomorrow 20:00 picked; no food yet = no menu', await page.getByTestId('party').textContent() === '4' && await product(12).count() === 0)
await page.getByTestId('book-food').check()
r.check('booking: with food → the menu at the pre-order prices (souvlaki €3.80; the cola is not pre-orderable)',
(await product(12).getByTestId('price').textContent()).includes('3.80') && await product(11).count() === 0)
await product(12).getByTestId('add').click()
await product(12).getByRole('button', { name: '+' }).click()
await page.screenshot({ path: path.join(OUT, 'order-app-booking.png'), fullPage: true })
await page.getByTestId('book-continue').click()
await page.waitForFunction(() => document.querySelector('[data-testid="totals"]')?.dataset.total === '7.6', null, { timeout: 8000 }).catch(() => {})
r.check('booking: the summary (table for 4, tomorrow) and the food priced by the cloud (€7.60)',
(await page.getByTestId('booking-summary').textContent()).includes('Table for 4') && await page.getByTestId('totals').getAttribute('data-total') === '7.6')
await page.getByTestId('place-order').click()
await page.getByTestId('track').waitFor({ timeout: 10_000 }).catch(() => {})
r.check('booking: requested → its page (booking ORD-0003, table for 4, waiting for the venue)',
(await page.getByTestId('track-ref').textContent().catch(() => '')).includes('Booking ORD-0003')
&& (await page.getByTestId('track').textContent()).includes('Table for 4') && await page.getByTestId('track').getAttribute('data-status') === 'pending_acceptance')
const booked = (await call('GET', `/api/orders/pending/${numeric}`, { headers: siteH })).find(o => o.public_ref === 'ORD-0003')
r.check('booking: the site receives a pre-order for 4 at the pre-order prices', booked?.order_type === 'preorder' && booked.party_size === 4
&& booked.total === 7.6 && booked.sales_point === 'online_preorder' && !!booked.requested_for, JSON.stringify(booked))
await call('PATCH', `/api/orders/${booked.id}/status`, { headers: siteH, body: { status: 'accepted' } })
r.check('booking: the venue confirms → the page says so', await page.waitForFunction(() => document.querySelector('[data-testid="track"]')?.dataset.status === 'accepted', null, { timeout: 15_000 })
.then(() => true).catch(() => false) && (await page.getByTestId('track').textContent()).includes('Confirmed'))
await page.screenshot({ path: path.join(OUT, 'order-app-booking-track.png'), fullPage: true })
// ── Greek ────────────────────────────────────────────────────────────────
await page.goto(`http://localhost:${APP_PORT}/order/${site.site_id}`)
await page.getByRole('button', { name: 'EL' }).click()
r.check('the app switches to Greek', await page.getByTestId('service-delivery').textContent() === 'Διανομή')
r.check('no page errors', errors.length === 0, errors.join(' | '))
} catch (err) {
r.check(`unexpected error: ${err.message}`, false)
} finally {
await browser?.close()
for (const p of procs) killTree(p)
}
process.exit(r.done() ? 1 : 0)