feat(backend,terminal): online orders on the counter POS (platform-v2 step 3.3d)

- Counter POS gets an "Online" mode (module on + connect_orders.manage): New / In
  progress / Finished, a chime on arrival (and every 30 s while one waits), badge,
  toast in any mode; the order panel offers only the next step: accept / reject with
  a reason, preparing, ready or out for delivery, then take the payment (shared
  PaymentDialog, drawer, shift) and mark delivered/served.
- connect_orders router on v2 conventions: require(connect_orders.manage), error
  codes online.not_found / online.status_changed, the cloud's step order enforced,
  audit rows, GET /api/connect/orders/board. POS device scope gains connect_orders.*;
  barista and barman get the key by default.
- Fixes: the KDS showed online orders before acceptance; accepting printed no
  kitchen tickets; a pull whose synced mark failed stored the order twice
  (store_online_orders skips known cloud ids); pulled orders lacked the business day
  and delivery type; rejected orders kept active items; delivered sets closed_at/by.
- Online orders belong to holders of connect_orders.manage (_can_access_order), so
  the counter pays them with POST /api/pos/orders/{id}/pay.
- Tests: test_pos_online.py (5), terminal unit +1, terminal.mjs +17 with a fake
  cloud (pull, synced, status mirror); fixed a timing race in a 3.3c check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 05:42:06 +02:00
co-authored by Claude Opus 5.5
parent 988d413d8e
commit d542cf7d34
20 changed files with 1052 additions and 176 deletions
+103 -3
View File
@@ -9,7 +9,10 @@
// - a customer display (no sign-in) goes straight into its app
// - server unreachable → banner → back by itself
// - removed from the manager → back to pairing with a notice and a new code
// - 3.3a–d: the counter POS (sale, payment, tables with a waiter's phone, online orders
// pulled from a fake cloud exactly as from the real one)
// node terminal.mjs
import http from 'node:http'
import net from 'node:net'
import path from 'node:path'
import { chromium } from 'playwright'
@@ -17,7 +20,26 @@ import { BROWSER_CHANNEL, OUT, reporter, sleep } from './lib/env.mjs'
import { startBackend, startTerminalVite } from './lib/proc.mjs'
import { supportLogin } from './lib/support.mjs'
const backend = await startBackend({ port: 8059, siteId: 'test-site-1' })
// A fake cloud for online orders (3.3d): the heartbeat names the site, the order pull hands
// over what the test queues, and status changes are recorded (the customer's tracking page).
const cloud = { queue: [], synced: [], statuses: [] }
const cloudServer = http.createServer((req, res) => {
let body = ''
req.on('data', c => { body += c })
req.on('end', () => {
const send = data => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(data)) }
const json = () => { try { return JSON.parse(body || '{}') } catch { return {} } }
let m
if (req.url === '/api/heartbeat/') return send({ site_numeric_id: 7 })
if (req.method === 'GET' && req.url === '/api/orders/pending/7') return send(cloud.queue.filter(o => !cloud.synced.includes(o.id)))
if ((m = req.url.match(/^\/api\/orders\/(\d+)\/synced$/))) { cloud.synced.push(Number(m[1])); return send({ ok: true }) }
if ((m = req.url.match(/^\/api\/orders\/(\d+)\/status$/))) { cloud.statuses.push({ id: Number(m[1]), ...json() }); return send({ ok: true }) }
return send({})
})
})
await new Promise(res => cloudServer.listen(0, '127.0.0.1', res))
const backend = await startBackend({ port: 8059, siteId: 'test-site-1', cloudUrl: `http://127.0.0.1:${cloudServer.address().port}`,
env: { LICENSE_MODE: 'off', CONNECT_SYNC_INTERVAL_SECONDS: '1' } })
const term = await startTerminalVite({ port: 5187, backendUrl: backend.url })
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
const r = reporter('terminal: pairing, sign-in, app states (paired screens)')
@@ -490,10 +512,87 @@ try {
const phoneOrder = await api('POST', '/api/orders/', { token: maria, body: { table_id: phoneTable.id } })
await api('POST', `/api/orders/${phoneOrder.id}/items`, { token: maria, body: { items: [{ product_id: simple.id, quantity: 2 }] } })
r.check('3.3c: a table opened on the phone shows on the counter at once, with what\'s due',
await page.waitForFunction(id => document.querySelector(`[data-testid="pos-table"][data-table="${id}"]`)?.dataset.state === 'open', phoneTable.id, { timeout: 8000 }).then(() => true).catch(() => false)
&& (await page.locator(`[data-testid="pos-table"][data-table="${phoneTable.id}"]`).textContent()).includes((2 * simple.price).toFixed(2)))
// (opened, then its items: wait for both, the card shows the order before its items arrive)
await page.waitForFunction(([id, due]) => {
const card = document.querySelector(`[data-testid="pos-table"][data-table="${id}"]`)
return card?.dataset.state === 'open' && card.textContent.includes(due)
}, [phoneTable.id, (2 * simple.price).toFixed(2)], { timeout: 8000 }).then(() => true).catch(() => false))
await page.screenshot({ path: path.join(OUT, 'terminal-pos-tables.png') })
phoneWs.close()
// ── 3.3d: online orders on the POS ──────────────────────────────────────
await api('PUT', '/api/platform/modules/connect_menu', { token: boss, body: { enabled: true } })
await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } })
r.check('3.3d: online orders on → the counter gets an Online mode', await shown(page, 'mode-online', 10_000))
const cloudOrder = (id, type, name) => ({
id, public_ref: `ORD-${String(id).padStart(4, '0')}`, order_type: type, customer_name: name, customer_phone: '6900000000',
customer_address: type === 'delivery' ? 'Main square 3' : null, customer_notes: 'Ring twice', status: 'pending_acceptance',
items_json: JSON.stringify([{ product_id: simple.id, name: simple.name, quantity: 2, unit_price: simple.price, options: [] }]),
subtotal: 2 * simple.price, delivery_fee: 0, total: 2 * simple.price, created_at: new Date().toISOString(),
})
const chimesBefore = Number(await page.getByTestId('pos-screen').getAttribute('data-chimes'))
cloud.queue.push(cloudOrder(41, 'delivery', 'Nikos Online'))
const rang = await page.waitForFunction(n => Number(document.querySelector('[data-testid="pos-screen"]')?.dataset.chimes) > n, chimesBefore, { timeout: 15_000 })
.then(() => true).catch(() => false)
const badged = await page.waitForFunction(() => document.querySelector('[data-testid="mode-online"]')?.dataset.badge === '1', null, { timeout: 5000 })
.then(() => true).catch(() => false)
r.check('3.3d: an order placed online reaches the counter at once: it rings, and the badge counts it', rang && badged,
`rang ${rang}, badge ${await page.getByTestId('mode-online').getAttribute('data-badge')}`)
r.check('3.3d: …the cloud was told it arrived', cloud.synced.includes(41))
await page.getByTestId('mode-online').click()
const onlineCard = page.locator('[data-testid="online-order"][data-status="pending_acceptance"]').first()
r.check('3.3d: the New list shows it, waiting for an answer', await onlineCard.waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
&& (await onlineCard.textContent()).includes('ORD-0041') && (await onlineCard.textContent()).includes('Nikos Online'))
const onlineId = Number(await onlineCard.getAttribute('data-order'))
await onlineCard.click()
r.check('3.3d: the order shows the customer (phone, address, note) and the items', await shown(page, 'online-panel', 5000)
&& (await page.getByTestId('online-customer').textContent()).includes('Main square 3')
&& (await page.getByTestId('online-customer').textContent()).includes('Ring twice')
&& await page.getByTestId('online-line').count() === 1
&& (await page.getByTestId('online-total').textContent()).includes((2 * simple.price).toFixed(2)))
await page.screenshot({ path: path.join(OUT, 'terminal-pos-online.png') })
const kdsHas = async () => (await api('GET', '/api/kds/orders', { token: boss })).orders.some(o => o.id === onlineId)
r.check('3.3d: the kitchen doesn\'t see it before it is accepted', !(await kdsHas()))
await page.getByTestId('online-accept').click()
await page.waitForFunction(id => document.querySelector(`[data-testid="online-panel"][data-order="${id}"]`)?.dataset.status === 'accepted', onlineId, { timeout: 8000 }).catch(() => {})
r.check('3.3d: Accept → accepted, in the In progress list', await page.getByTestId('online-panel').getAttribute('data-status') === 'accepted'
&& await page.locator(`[data-testid="online-order"][data-order="${onlineId}"]`).count() === 1)
r.check('3.3d: …the kitchen has it now (KDS)', await kdsHas())
for (let i = 0; i < 30 && !cloud.statuses.some(x => x.id === 41 && x.status === 'accepted'); i++) await sleep(100)
r.check('3.3d: …and the customer\'s page follows (status sent to the cloud)', cloud.statuses.some(x => x.id === 41 && x.status === 'accepted'))
r.check('3.3d: …the badge went back to 0', await page.getByTestId('mode-online').getAttribute('data-badge') === '0')
for (const to of ['preparing', 'out_for_delivery']) {
await page.getByTestId('online-next').click()
await page.waitForFunction(st => document.querySelector('[data-testid="online-panel"]')?.dataset.status === st, to, { timeout: 8000 }).catch(() => {})
}
r.check('3.3d: Start preparing → Out for delivery', await page.getByTestId('online-panel').getAttribute('data-status') === 'out_for_delivery')
const drawerBeforeOnline = drawerBytes.length
await page.getByTestId('online-finish').click()
await page.getByTestId('payment-dialog').waitFor({ timeout: 5000 })
await page.getByTestId('pay-confirm').click()
await page.waitForFunction(() => document.querySelector('[data-testid="online-panel"]')?.dataset.status === 'delivered', null, { timeout: 8000 }).catch(() => {})
r.check('3.3d: the driver\'s cash taken at the counter → delivered', await page.getByTestId('online-panel').getAttribute('data-status') === 'delivered')
for (let i = 0; i < 20 && drawerBytes.length === drawerBeforeOnline; i++) await sleep(100)
r.check('3.3d: …the drawer opened and the items are paid', drawerBytes.length > drawerBeforeOnline
&& (await api('GET', `/api/orders/${onlineId}`, { token: boss })).items.every(i => i.status === 'paid'))
for (let i = 0; i < 30 && !cloud.statuses.some(x => x.id === 41 && x.status === 'delivered'); i++) await sleep(100)
r.check('3.3d: …and the cloud heard every step', ['accepted', 'preparing', 'out_for_delivery', 'delivered']
.every(st => cloud.statuses.some(x => x.id === 41 && x.status === st)), JSON.stringify(cloud.statuses))
// a second order is rejected with a reason the customer sees
await page.getByTestId('online-list-incoming').click()
cloud.queue.push(cloudOrder(42, 'dine_in', 'Late Guest'))
const secondOnline = page.locator('[data-testid="online-order"][data-status="pending_acceptance"]').first()
await secondOnline.waitFor({ timeout: 15_000 }).catch(() => {})
await secondOnline.click()
await page.getByTestId('online-reject').click()
await page.getByTestId('reason-busy').click()
await page.getByTestId('reject-confirm').click()
for (let i = 0; i < 50 && !cloud.statuses.some(x => x.id === 42); i++) await sleep(100)
const rejected = cloud.statuses.find(x => x.id === 42)
r.check('3.3d: Reject with a reason → the customer is told why', rejected?.status === 'rejected' && rejected.rejection_reason?.length > 0,
JSON.stringify(rejected))
r.check('3.3d: …and it leaves the New list', await page.waitForFunction(() => !document.querySelector('[data-testid="online-order"]'), null, { timeout: 5000 })
.then(() => true).catch(() => false))
await page.getByTestId('mode-sale').click()
drawerServer.close()
await page.getByRole('button', { name: 'Sign out' }).click()
@@ -528,5 +627,6 @@ try {
await browser.close()
term.stop()
await backend.stop()
cloudServer.close()
}
process.exit(r.done() ? 1 : 0)