Files
xenia-pos-local/tests/e2e/order_app.mjs
T
bonaminandClaude Opus 5.5 0ca700279a feat(connect): the site side of online orders: fee line, customer's time, price check
Plan phase 3S, step S.5.
- Pull: an online order keeps the customer's time (orders.requested_for, None = as soon as
  possible) and delivery area; quick options are stored in the site's entry shape; items get
  their cost snapshot.
- The delivery fee is its own order line: a system product (products.system_key
  "delivery_fee", lifecycle "system", sold nowhere; services/system_products.py), created on
  first use in the venue's language with the VAT group most products use. Added printed and
  served, so kitchen tickets and the KDS never see it; paid at the counter with the items,
  counted in the shift, on the fiscal receipt with its VAT group. Never listed in the
  catalogue (products list, export, edit endpoints → 404) and never added by hand.
- Price check (services/online_check.py): each line priced as the snapshot prices it, at the
  order's time, and the fee through the same engine with the site's rules and the cloud's
  area id; differences kept on orders.online_price_diff and shown. The customer pays what
  the cloud charged.
- Counter: time chip (or as soon as possible), area, fee line, price warning; takeaway is
  its own kind (was shown as "at the venue") and finishes as "collected". KDS cards show the
  online reference and the time; kitchen tickets print the reference, the type and the time.
- Manager: Online ordering → "The fee on the receipt" (name, VAT group;
  PUT /api/connect/fees/fee-product, fees.vat_group_unknown); the online orders page shows
  the time, area and price warning.
- Migration 0019. Tests: tests/test_online_site_side.py (6), terminal unit test, e2e
  (terminal: fee, time, warning, paid in full; manager: fee line settings).

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

186 lines
14 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, 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'], prices: { online_takeaway: 4, online_delivery: 4.2 }, 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 },
}
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)
// ── 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)