feat(terminal): kitchen display on paired screens, live without polling (platform-v2 3.2b)

Port of the manager's KdsPage.jsx into terminal/src/apps/kds, split into pure logic
(layout packing, age, buckets, rounds, totals, status cycle, settings; unit-tested) and
components (card, item, action bars, dialogs, item totals, rails, settings panel).
- Settings are the device's config; the settings panel saves them (managers only),
  zoom changes the size for the session.
- Orders reload on live events and every reconnect; polling only while the live
  connection is down (DeviceProvider exposes liveUp; useLiveEvents helper).
- "Tap to start" unlocks sound; venue clock via useFormat; English-first texts.
- Undo of an item recomputes the order status at once; undo/redo clear the selection.
- Tests: terminal unit +15, terminal.mjs +12 KDS checks (no polling, live order + chime,
  item/undo/prepare/decline, settings permission, change made elsewhere), backend
  regression for an item back to pending.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 19:27:11 +02:00
co-authored by Claude Opus 5.5
parent d5c4400fde
commit 5f6d4ab428
24 changed files with 2550 additions and 12 deletions
+366 -3
View File
@@ -1,6 +1,369 @@
// Placeholder until step 3.2 builds this app (plan phase 3). Lazily loaded (apps/registry.js).
import AppPlaceholder from '../AppPlaceholder'
// The kitchen display on a paired screen (plan step 3.2b; ported from the manager's
// KdsPage.jsx, which goes in 3.2d). The same board, actions and sounds as before:
// - side rail: status filters with counts (future / to do / in progress / done; several at
// once or one at a time: setting categories_as_filters), undo/redo, call waiters, sound
// on/off for this session, settings;
// - top bar: here / takeaway / delivery tabs, item totals button, the venue's clock, zoom
// (this session only; the saved size is the font_scale setting);
// - the board: cards packed in columns without vertical scrolling (logic/layout.js), tap a
// card to select it, tap its items to move them on, long press to decline;
// - item totals panel, decline / call-waiter dialogs, toasts.
// Settings are the device's (3.2a): GET /api/devices/me → me.config, live on device.updated.
// Orders come from the backend for this screen's zone and stay fresh through the live
// connection (useKdsData). Sound needs one tap after the screen starts (browser rule).
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { CookingPot } from 'lucide-react'
import { useLanguage, useTranslation } from '@xenia/i18n'
import client from '../../api/client'
import { useDevice } from '../../device/context'
import { chime, soundUnlocked, unlockSound } from './chime'
import { CallWaiterDialog, DeclineDialog, Toasts } from './components/Dialogs'
import MeasureLayer from './components/MeasureLayer'
import OrderCard from './components/OrderCard'
import { SideRail, TopBar } from './components/Rails'
import SettingsPanel from './components/SettingsPanel'
import SummaryPanel from './components/SummaryPanel'
import {
ageLabel, ageOrderFor, ageState, bucketCounts, nextItemStatus, readyNotice, tabCounts, visibleOrders,
withItemStatus, withOrderStatus,
} from './logic/board'
import { layoutBoard } from './logic/layout'
import { boardSettings, senderName, zoomStep } from './logic/settings'
import { KDS, KEYFRAMES } from './theme'
import useKdsData from './useKdsData'
const HISTORY = 10
const TOAST_MS = 2200
export default function KdsApp() {
return <AppPlaceholder appKey="kds" />
const { t } = useTranslation('terminal')
const { language } = useLanguage()
const { me } = useDevice()
const config = me?.config
const [zoom, setZoom] = useState(null) // percent; null = the saved font_scale
const settings = useMemo(() => boardSettings(config, zoom), [config, zoom])
const { orders: loaded, context, reload } = useKdsData({ refreshSeconds: settings.refreshSeconds, zoneId: settings.zoneId })
const [orders, setOrders] = useState([])
const [filters, setFilters] = useState(() => new Set(['future', 'pending', 'preparing']))
const [tab, setTab] = useState('all')
const [focusId, setFocusId] = useState(null)
const [now, setNow] = useState(() => Date.now())
const [dialog, setDialog] = useState(null) // 'settings' | 'call' | {decline: {...}}
const [showSummary, setShowSummary] = useState(false)
const [soundOn, setSoundOn] = useState(true)
const [started, setStarted] = useState(() => soundUnlocked())
const [toasts, setToasts] = useState([])
const [boardH, setBoardH] = useState(0)
const [measured, setMeasured] = useState({})
const undoStack = useRef([])
const redoStack = useRef([])
const [hist, setHist] = useState({ undo: 0, redo: 0 }) // stack sizes, for the rail buttons
const known = useRef(null) // order ids seen so far (new-order chime)
const toast = useCallback(msg => {
const id = Math.random().toString(36).slice(2)
setToasts(ts => [...ts, { id, msg }])
setTimeout(() => setToasts(ts => ts.filter(x => x.id !== id)), TOAST_MS)
}, [])
// a fresh answer replaces the board; new orders chime (not the first load)
const soundRef = useRef(false)
useEffect(() => { soundRef.current = soundOn && settings.sound })
useEffect(() => {
if (!loaded) return
setOrders(loaded)
const ids = new Set(loaded.map(o => o.id))
const arrived = known.current ? [...ids].filter(id => !known.current.has(id)).length : 0
known.current = ids
if (arrived && soundRef.current) {
chime()
toast(t('kds.toast.newOrders', { count: arrived }))
}
}, [loaded, t, toast])
useEffect(() => {
const id = setInterval(() => setNow(Date.now()), 1000)
return () => clearInterval(id)
}, [])
// board height (for the layout) and drag-to-scroll (cards block native touch scrolling)
const boardRef = useRef(null)
useEffect(() => {
const el = boardRef.current
if (!el) return undefined
const measure = () => setBoardH(p => (Math.abs(p - el.clientHeight) > 1 ? el.clientHeight : p))
measure()
const ro = new ResizeObserver(measure)
ro.observe(el)
let startX = 0, startScroll = 0, dragging = false, moved = false
const down = e => {
if (e.button !== 0 && e.pointerType === 'mouse') return
startX = e.clientX; startScroll = el.scrollLeft; dragging = true; moved = false
}
const move = e => {
if (!dragging) return
const dx = e.clientX - startX
if (!moved && Math.abs(dx) < 6) return
moved = true
el.scrollLeft = startScroll - dx
}
const up = () => { dragging = false }
el.addEventListener('pointerdown', down, { capture: true })
window.addEventListener('pointermove', move)
window.addEventListener('pointerup', up)
return () => {
ro.disconnect()
el.removeEventListener('pointerdown', down, { capture: true })
window.removeEventListener('pointermove', move)
window.removeEventListener('pointerup', up)
}
}, [])
const pushHistory = useCallback(entry => {
undoStack.current.push(entry)
if (undoStack.current.length > HISTORY) undoStack.current.shift()
redoStack.current = []
setHist({ undo: undoStack.current.length, redo: 0 })
}, [])
const putOrderStatus = useCallback((orderId, status) =>
client.put(`/api/kds/orders/${orderId}/kds_status`, { status }).finally(reload), [reload])
const putItemStatus = useCallback((orderId, itemId, status) =>
client.put(`/api/kds/orders/${orderId}/items/${itemId}/kds_status`, { status }).finally(reload), [reload])
const sender = senderName(context) // the backend signs a screen's messages itself; kept for the dialog text
const callWaiter = useCallback(orderId => {
client.post(`/api/kds/orders/${orderId}/call-waiter`, {})
.then(() => toast(t('kds.toast.waiterCalled'))).catch(() => toast(t('kds.toast.sendFailed')))
}, [t, toast])
const setOrderStatus = useCallback((orderId, status) => {
const order = orders.find(o => o.id === orderId)
if (!order) return
setOrders(prev => prev.map(o => (o.id === orderId ? withOrderStatus(o, status) : o)))
pushHistory({ type: 'order', orderId, prev: order.kds_status, next: status, prevItems: order.items.map(it => ({ id: it.id, kds_status: it.kds_status })) })
putOrderStatus(orderId, status).catch(() => {})
if (status === 'done' && settings.notifyOrderComplete) client.post(`/api/kds/orders/${orderId}/notify-complete`, {}).catch(() => {})
setFocusId(null)
toast(t(`kds.toast.${status}`))
}, [orders, pushHistory, putOrderStatus, settings.notifyOrderComplete, t, toast])
const bumpItem = useCallback((orderId, itemId) => {
const order = orders.find(o => o.id === orderId)
const item = order?.items.find(it => it.id === itemId)
if (!item) return
const next = nextItemStatus(item.kds_status, settings.tripleState)
setOrders(prev => prev.map(o => (o.id === orderId ? withItemStatus(o, itemId, next) : o)))
pushHistory({ type: 'item', orderId, itemId, prev: item.kds_status, next })
putItemStatus(orderId, itemId, next).catch(() => {})
if (next === 'done') {
const notice = readyNotice(order, itemId, settings)
if (notice?.kind === 'order') client.post(`/api/kds/orders/${orderId}/notify-complete`, {}).catch(() => {})
if (notice?.kind === 'items') {
client.post(`/api/kds/orders/${orderId}/notify-items-ready`, { ready_count: notice.ready_count, total_count: notice.total_count }).catch(() => {})
}
}
}, [orders, settings, pushHistory, putItemStatus])
const confirmDecline = useCallback(async ({ orderId, itemId }, note) => {
try {
if (itemId) {
await client.put(`/api/kds/orders/${orderId}/items/${itemId}/decline`, { decline_note: note ?? null })
setOrders(prev => prev.map(o => (o.id !== orderId ? o : { ...o, items: o.items.map(it => (it.id === itemId ? { ...it, kds_status: 'declined' } : it)) })))
toast(t('kds.toast.itemDeclined'))
} else {
await client.put(`/api/kds/orders/${orderId}/decline`, { decline_note: note ?? null })
setOrders(prev => prev.map(o => (o.id !== orderId ? o : {
...o, kds_status: 'declined',
items: o.items.map(it => (it.status !== 'cancelled' ? { ...it, kds_status: 'declined', decline_note: note ?? null } : it)),
})))
toast(t('kds.toast.orderDeclined'))
}
reload()
} catch { toast(t('kds.toast.declineFailed')) }
}, [reload, t, toast])
const print = useCallback(async orderId => {
try {
await client.post(`/api/kds/orders/${orderId}/retry-print`)
toast(t('kds.toast.printSent'))
} catch { toast(t('kds.toast.printFailed')) }
}, [t, toast])
const replay = useCallback((entry, which) => {
const status = entry[which]
if (entry.type === 'order') {
setOrders(prev => prev.map(o => {
if (o.id !== entry.orderId) return o
if (which === 'next') return withOrderStatus(o, status)
const items = o.items.map(it => { const f = entry.prevItems.find(p => p.id === it.id); return f ? { ...it, kds_status: f.kds_status } : it })
return { ...o, kds_status: status, items }
}))
putOrderStatus(entry.orderId, status).catch(() => {})
} else {
setOrders(prev => prev.map(o => (o.id !== entry.orderId ? o : withItemStatus(o, entry.itemId, status))))
putItemStatus(entry.orderId, entry.itemId, status).catch(() => {})
}
}, [putOrderStatus, putItemStatus])
const undo = useCallback(() => {
const entry = undoStack.current.pop()
if (!entry) return
redoStack.current.push(entry)
setHist({ undo: undoStack.current.length, redo: redoStack.current.length })
replay(entry, 'prev')
setFocusId(null)
toast(t('kds.toast.undone'))
}, [replay, t, toast])
const redo = useCallback(() => {
const entry = redoStack.current.pop()
if (!entry) return
undoStack.current.push(entry)
setHist({ undo: undoStack.current.length, redo: redoStack.current.length })
replay(entry, 'next')
setFocusId(null)
toast(t('kds.toast.redone'))
}, [replay, t, toast])
useEffect(() => {
const h = e => {
if (e.key === 'Escape') setFocusId(null)
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') { e.preventDefault(); if (e.shiftKey) redo(); else undo() }
}
window.addEventListener('keydown', h)
return () => window.removeEventListener('keydown', h)
}, [undo, redo])
const counts = useMemo(() => bucketCounts(orders, now), [orders, now])
const tabs = useMemo(() => tabCounts(orders, filters, now), [orders, filters, now])
const visible = useMemo(() => visibleOrders(orders, {
filters, tab, now, sortBy: context?.zone?.sort_items_by ?? 'order_time', batchMode: settings.batchMode, locale: language,
}), [orders, filters, tab, now, context, settings.batchMode, language])
const courses = context?.courses_enabled ? (context.courses ?? []) : []
const layout = useMemo(() => layoutBoard({
orders: visible, measured, boardH, colW: settings.colW, fontScale: settings.fontScale,
groupByCourse: settings.groupByCourse, courses, batchMode: settings.batchMode,
}), [visible, measured, boardH, settings, courses])
const toggleFilter = key => {
if (settings.categoriesAsFilters) {
setFilters(prev => {
const next = new Set(prev)
if (next.has(key)) next.delete(key); else next.add(key)
return next.size === 0 ? prev : next
})
} else {
setFilters(new Set([key]))
}
setTab('all')
setFocusId(null)
}
const fs = settings.fontScale
const summary = settings.groupItems
const sideWidth = `${Math.round(20 * fs)}vw`
return (
<div data-testid="app-kds" style={{
display: 'flex', position: 'absolute', inset: 0, overflow: 'hidden',
background: KDS.bg, color: '#e7ecf2', WebkitFontSmoothing: 'antialiased', userSelect: 'none', WebkitUserSelect: 'none',
}}>
<style>{KEYFRAMES}</style>
<SideRail filters={filters} counts={counts} fontScale={fs} onToggleFilter={toggleFilter}
soundOn={soundOn} onToggleSound={() => setSoundOn(v => { if (!v) { unlockSound(); chime() } return !v })}
canUndo={hist.undo > 0} canRedo={hist.redo > 0} onUndo={undo} onRedo={redo}
onSettings={() => setDialog('settings')} onCall={() => setDialog('call')} />
<div style={{ flex: '1 1 auto', display: 'flex', flexDirection: 'column', minWidth: 0 }}>
<TopBar tab={tab} counts={tabs} onTab={k => { setTab(k); setFocusId(null) }} now={now} fontScale={fs}
zoomPercent={Math.round(fs * 100)} onZoom={dir => setZoom(zoomStep(Math.round(fs * 100), dir))}
showSummaryButton={summary === 'topbar_button'} summaryOpen={showSummary} onToggleSummary={() => setShowSummary(v => !v)} />
<div style={{ flex: '1 1 auto', display: 'flex', minHeight: 0 }}>
{summary === 'left_sidebar' && (
<div style={{ width: sideWidth, flexShrink: 0, minHeight: 0 }}>
<SummaryPanel orders={visible} mode="left_sidebar" fontScale={fs} fontWeight={settings.fontWeight} />
</div>
)}
<div style={{ flex: '1 1 auto', position: 'relative', minWidth: 0, minHeight: 0 }}>
<div ref={boardRef} data-testid="kds-board" onClick={() => setFocusId(null)}
style={{ position: 'absolute', inset: 0, overflowX: 'auto', overflowY: 'hidden' }}>
<div style={{ position: 'relative', height: '100%', width: Math.max(layout.totalW, 1), minWidth: '100%',
paddingRight: summary === 'floating' ? `calc(${sideWidth} + 32px)` : 0 }}>
{loaded === null && (
<div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#5e6772', fontSize: 14 }}>
{t('kds.loading')}
</div>
)}
{loaded !== null && visible.length === 0 && (
<div data-testid="kds-empty" onClick={e => e.stopPropagation()} style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
alignItems: 'center', justifyContent: 'center', gap: 14, color: '#5e6772' }}>
<CookingPot style={{ width: 54, height: 54, opacity: 0.5 }} />
<div style={{ fontSize: 17, fontWeight: 600, color: '#7b8694' }}>{t('kds.empty')}</div>
</div>
)}
{visible.map(order => {
const lo = layout.map[order.id]
if (!lo) return null
const realId = order._realId ?? order.id
const age = ageState(ageOrderFor(order), now, settings.thresholds)
return (
<OrderCard key={order.id} order={{ ...order, id: realId }} age={age} ageText={ageLabel(age, t)} layout={lo} now={now}
focused={focusId === order.id} dimmed={focusId != null && focusId !== order.id}
settings={settings} multiFilter={filters.size > 1} courses={courses}
onFocus={id => setFocusId(id === realId ? order.id : id)}
onStatus={setOrderStatus} onBumpItem={bumpItem} onPrint={print} onCallWaiter={callWaiter}
onDecline={orderId => setDialog({ decline: { orderId, itemId: null } })}
onItemDecline={(orderId, itemId, itemName) => setDialog({ decline: { orderId, itemId, itemName } })} />
)
})}
</div>
</div>
{summary === 'floating' && (
<div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 50 }}>
<SummaryPanel orders={visible} mode="floating" fontScale={fs} fontWeight={settings.fontWeight} />
</div>
)}
{summary === 'topbar_button' && showSummary && (
<SummaryPanel orders={visible} mode="topbar_button" open onClose={() => setShowSummary(false)} fontScale={fs} fontWeight={settings.fontWeight} />
)}
</div>
{summary === 'right_sidebar' && (
<div style={{ width: sideWidth, flexShrink: 0, minHeight: 0 }}>
<SummaryPanel orders={visible} mode="right_sidebar" fontScale={fs} fontWeight={settings.fontWeight} />
</div>
)}
</div>
</div>
<MeasureLayer orders={visible} colW={settings.colW} fontScale={fs} fontWeight={settings.fontWeight}
combineModifiers={settings.combineModifiers} onResult={setMeasured} />
{dialog === 'settings' && (
<SettingsPanel config={config} context={context} onClose={() => setDialog(null)} onSaved={() => { setZoom(null); toast(t('kds.toast.settingsSaved')) }} />
)}
{dialog === 'call' && (
<CallWaiterDialog zoneName={sender} onClose={() => setDialog(null)}
onSend={ids => client.post('/api/kds/call-waiter-general', { waiter_ids: ids })
.then(() => toast(t('kds.toast.called'))).catch(() => toast(t('kds.toast.sendFailed')))} />
)}
{dialog?.decline && (
<DeclineDialog itemId={dialog.decline.itemId} itemName={dialog.decline.itemName}
onConfirm={note => confirmDecline(dialog.decline, note)} onClose={() => setDialog(null)} />
)}
{!started && settings.sound && (
<button type="button" data-testid="kds-start" onClick={() => { unlockSound(); setStarted(true) }} style={{
position: 'absolute', inset: 0, zIndex: 400, background: 'rgba(10,13,17,.72)', border: 'none', cursor: 'pointer', color: '#e7ecf2',
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10, fontFamily: 'inherit',
}}>
<span style={{ fontSize: 28, fontWeight: 800 }}>{t('kds.start.title')}</span>
<span style={{ fontSize: 15, color: '#aab4c0', maxWidth: 420, textAlign: 'center' }}>{t('kds.start.body')}</span>
</button>
)}
<Toasts toasts={toasts} />
</div>
)
}