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>
)
}
+44
View File
@@ -0,0 +1,44 @@
// The new-order sound (two short tones). Browsers only play sound after a tap on the page:
// unlockSound() runs on the "Tap to start" screen (plan step 3.2b).
let audio = null
function context() {
const Ctx = window.AudioContext || window.webkitAudioContext
if (!Ctx) return null
audio = audio || new Ctx()
return audio
}
/** Call from a tap: lets the screen play sounds from now on. True if it can. */
export function unlockSound() {
try {
const a = context()
if (!a) return false
if (a.state === 'suspended') a.resume()
return true
} catch { return false }
}
export function soundUnlocked() {
return audio != null && audio.state === 'running'
}
export function chime() {
try {
const a = context()
if (!a) return
if (a.state === 'suspended') a.resume()
const t = a.currentTime
;[880, 1320].forEach((f, i) => {
const o = a.createOscillator(), g = a.createGain()
o.type = 'sine'; o.frequency.value = f
o.connect(g); g.connect(a.destination)
const s = t + i * 0.13
g.gain.setValueAtTime(0.0001, s)
g.gain.exponentialRampToValueAtTime(0.28, s + 0.02)
g.gain.exponentialRampToValueAtTime(0.0001, s + 0.26)
o.start(s); o.stop(s + 0.28)
})
if (import.meta.env?.DEV) window.__xeniaChimes = (window.__xeniaChimes || 0) + 1 // e2e counts chimes
} catch { /* no sound device */ }
}
@@ -0,0 +1,95 @@
// The buttons over an order card's header (plan step 3.2b, from KdsPage.jsx):
// - ActionBar (the selected card): in progress / done (or back), print, and "Call waiter"
// over the footer when the order has a waiter.
// - QuickActionBar (long press on a card that isn't selected): prep, ready, decline, close.
import { Ban, BellRing, Check, Flame, Printer, Undo2, X } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { CARD_FOOT_H_BASE, CARD_HEAD_H_BASE, CARD_SUB_H_BASE } from '../logic/layout'
import { KDS } from '../theme'
function Bar({ fs, z, children }) {
const pad = Math.round(6 * fs)
return (
<div onClick={e => e.stopPropagation()} style={{
position: 'absolute', left: 0, right: 0, top: 0, height: Math.round((CARD_HEAD_H_BASE + CARD_SUB_H_BASE) * fs), zIndex: z,
background: '#0a0e13', borderRadius: '10px 10px 0 0', display: 'flex', alignItems: 'stretch', padding: pad, gap: pad,
}}>
{children}
</div>
)
}
function BarButton({ bg, label, title, onClick, fs, children, testId }) {
return (
<button type="button" title={title} aria-label={title} data-testid={testId}
onClick={e => { e.stopPropagation(); onClick() }}
style={{
flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: Math.round(3 * fs),
background: bg, color: '#fff', border: 'none', cursor: 'pointer', fontFamily: 'inherit', borderRadius: Math.round(9 * fs),
fontSize: Math.round(10 * fs), fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase',
}}>
{children}
{label}
</button>
)
}
export function ActionBar({ order, onStatus, onPrint, onCallWaiter, fs = 1, hasWaiter }) {
const { t } = useTranslation('terminal')
const isDone = order.kds_status === 'done'
const isPreparing = order.kds_status === 'preparing'
const icon = { width: Math.round(22 * fs), height: Math.round(22 * fs) }
return (
<>
<Bar fs={fs} z={4}>
<BarButton fs={fs} testId="card-prepare" title={isPreparing ? t('kds.actions.reset') : t('kds.actions.prepare')}
bg={isPreparing ? '#3d4757' : KDS.accent} onClick={() => onStatus(order.id, isPreparing ? 'pending' : 'preparing')}>
{isPreparing ? <Undo2 style={icon} /> : <Flame style={icon} />}
</BarButton>
<BarButton fs={fs} testId="card-complete" title={isDone ? t('kds.actions.reset') : t('kds.actions.complete')}
bg={isDone ? '#3d4757' : KDS.greenD} onClick={() => onStatus(order.id, isDone ? 'pending' : 'done')}>
{isDone ? <Undo2 style={icon} /> : <Check style={icon} />}
</BarButton>
<BarButton fs={fs} testId="card-print" title={t('kds.actions.print')} bg="rgba(255,255,255,.12)" onClick={() => onPrint(order.id)}>
<Printer style={icon} />
</BarButton>
</Bar>
{hasWaiter && (
<button type="button" data-testid="card-call-waiter" onClick={e => { e.stopPropagation(); onCallWaiter(order.id) }} style={{
position: 'absolute', left: 0, right: 0, bottom: 0, height: Math.round(CARD_FOOT_H_BASE * fs), zIndex: 4,
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: Math.round(7 * fs),
background: KDS.amberD, color: '#fff', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
fontSize: Math.round(13 * fs), fontWeight: 700,
}}>
<BellRing style={{ width: Math.round(14 * fs), height: Math.round(14 * fs) }} />
{t('kds.actions.callWaiter')}
</button>
)}
</>
)
}
export function QuickActionBar({ order, onStatus, onDecline, onDismiss, fs = 1 }) {
const { t } = useTranslation('terminal')
const isDone = order.kds_status === 'done'
const isPreparing = order.kds_status === 'preparing'
const icon = { width: Math.round(20 * fs), height: Math.round(20 * fs) }
return (
<Bar fs={fs} z={5}>
<BarButton fs={fs} testId="quick-prepare" bg={isPreparing ? '#3d4757' : KDS.accent} label={isPreparing ? t('kds.quick.undo') : t('kds.quick.prep')}
onClick={() => { onStatus(order.id, isPreparing ? 'pending' : 'preparing'); onDismiss() }}>
{isPreparing ? <Undo2 style={icon} /> : <Flame style={icon} />}
</BarButton>
<BarButton fs={fs} testId="quick-ready" bg={isDone ? '#3d4757' : KDS.greenD} label={isDone ? t('kds.quick.undo') : t('kds.quick.ready')}
onClick={() => { onStatus(order.id, isDone ? 'pending' : 'done'); onDismiss() }}>
{isDone ? <Undo2 style={icon} /> : <Check style={icon} />}
</BarButton>
<BarButton fs={fs} testId="quick-decline" bg={KDS.redD} label={t('kds.quick.decline')} onClick={() => { onDecline(order.id); onDismiss() }}>
<Ban style={icon} />
</BarButton>
<BarButton fs={fs} testId="quick-close" bg="rgba(255,255,255,.10)" label={t('kds.quick.close')} onClick={onDismiss}>
<X style={icon} />
</BarButton>
</Bar>
)
}
@@ -0,0 +1,180 @@
// The kitchen board's dialogs (plan step 3.2b, from KdsPage.jsx), dark like the board:
// decline an order or an item (with a reason), call waiters on shift, and the small toasts.
import { useEffect, useState } from 'react'
import { Ban, BellRing, Check, X } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import client from '../../../api/client'
import { KDS, secondaryButton } from '../theme'
export function KdsModal({ width, onClose, children, testId, z = 200 }) {
return (
<div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: z, background: 'rgba(10,13,17,.78)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<div role="dialog" data-testid={testId} onClick={e => e.stopPropagation()} style={{
width, maxWidth: 'calc(100vw - 32px)', maxHeight: 'calc(100vh - 32px)', background: KDS.panel, border: `1px solid ${KDS.panelLine}`, borderRadius: 18,
boxShadow: '0 32px 80px rgba(0,0,0,.6)', color: KDS.panelInk, display: 'flex', flexDirection: 'column', overflow: 'hidden',
}}>
{children}
</div>
</div>
)
}
export function CloseButton({ onClick, label }) {
return (
<button type="button" aria-label={label} onClick={onClick} style={{ width: 40, height: 40, borderRadius: 10, display: 'flex', alignItems: 'center',
justifyContent: 'center', color: KDS.panelInk2, background: 'none', border: 'none', cursor: 'pointer', flexShrink: 0 }}>
<X style={{ width: 20, height: 20 }} />
</button>
)
}
const REASONS = ['out_of_stock', 'too_many_orders', 'other']
export function DeclineDialog({ itemId, itemName, onConfirm, onClose }) {
const { t } = useTranslation('terminal')
const [reason, setReason] = useState(null)
const [note, setNote] = useState('')
const isItem = itemId != null
const title = isItem ? t('kds.decline.item') : t('kds.decline.order')
const confirm = () => {
if (!reason) return
// the waiter app shows this text as it is: the reason in the screen's language, or the note
onConfirm(reason === 'other' ? (note.trim() || null) : t(`kds.decline.reasons.${reason}`))
onClose()
}
return (
<KdsModal width={380} onClose={onClose} testId="decline-dialog" z={300}>
<div style={{ padding: '18px 20px 14px', borderBottom: `1px solid ${KDS.panelLine2}` }}>
<div style={{ fontSize: 17, fontWeight: 700 }}>{title}</div>
{isItem && itemName && <div style={{ fontSize: 13, color: KDS.panelInk2, marginTop: 4 }}>{itemName}</div>}
</div>
<div style={{ padding: '14px 20px', display: 'flex', flexDirection: 'column', gap: 8 }}>
{REASONS.map(r => {
const on = reason === r
return (
<button key={r} type="button" data-reason={r} onClick={() => setReason(r)} style={{
width: '100%', padding: '12px 14px', borderRadius: 10, textAlign: 'left', fontFamily: 'inherit', cursor: 'pointer',
background: on ? 'rgba(232,81,63,.15)' : KDS.field, border: `2px solid ${on ? KDS.red : KDS.panelLine}`,
color: on ? '#f5a7a0' : '#9ca8b6', fontSize: 14, fontWeight: on ? 600 : 400,
}}>
{t(`kds.decline.reasons.${r}`)}
</button>
)
})}
{reason === 'other' && (
<input value={note} onChange={e => setNote(e.target.value)} placeholder={t('kds.decline.notePlaceholder')} autoFocus style={{
width: '100%', height: 44, borderRadius: 10, padding: '0 12px', background: '#232d38', border: '1px solid #3d4f5e',
color: KDS.panelInk, fontSize: 14, fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box',
}} />
)}
</div>
<div style={{ display: 'flex', gap: 10, padding: '12px 20px 18px' }}>
<button type="button" onClick={onClose} style={secondaryButton}>{t('kds.cancel')}</button>
<button type="button" data-testid="decline-confirm" onClick={confirm} disabled={!reason} style={{
flex: 2, height: 48, borderRadius: 11, background: reason ? KDS.redD : KDS.panelLine, color: reason ? '#fff' : '#5e6772',
fontSize: 15, fontWeight: 700, border: 'none', cursor: reason ? 'pointer' : 'default', fontFamily: 'inherit',
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
}}>
<Ban style={{ width: 16, height: 16 }} />
{title}
</button>
</div>
</KdsModal>
)
}
export function CallWaiterDialog({ zoneName, onSend, onClose }) {
const { t } = useTranslation('terminal')
const [waiters, setWaiters] = useState(null)
const [selected, setSelected] = useState(() => new Set())
const [sending, setSending] = useState(false)
useEffect(() => {
let alive = true
client.get('/api/kds/on-shift-waiters')
.then(r => { if (alive) setWaiters(r.data) })
.catch(() => { if (alive) setWaiters([]) })
return () => { alive = false }
}, [])
const toggle = id => setSelected(prev => {
const next = new Set(prev)
if (next.has(id)) next.delete(id); else next.add(id)
return next
})
const all = waiters?.length > 0 && selected.size === waiters.length
const send = async () => {
if (!selected.size) return
setSending(true)
try { await onSend([...selected]); onClose() } finally { setSending(false) }
}
const chip = on => ({
width: '100%', borderRadius: 12, marginBottom: 8, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center',
background: on ? 'rgba(47,127,240,.18)' : KDS.field, border: `2px solid ${on ? KDS.accent : KDS.panelLine}`,
})
const ready = selected.size > 0 && !sending
return (
<KdsModal width={420} onClose={onClose} testId="call-dialog">
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 20px 14px' }}>
<div>
<div style={{ fontSize: 18, fontWeight: 700 }}>{t('kds.call.title')}</div>
{zoneName && <div style={{ fontSize: 12.5, color: KDS.panelInk2, marginTop: 2 }}>{t('kds.call.needsHelp', { zone: zoneName })}</div>}
</div>
<CloseButton onClick={onClose} label={t('kds.close')} />
</div>
<div style={{ padding: '0 14px', maxHeight: 320, overflowY: 'auto' }}>
{waiters === null && <div style={{ textAlign: 'center', padding: '32px 0', color: '#5e6772', fontSize: 14 }}>{t('kds.loading')}</div>}
{waiters?.length === 0 && <div style={{ textAlign: 'center', padding: '32px 0', color: '#5e6772', fontSize: 14 }}>{t('kds.call.none')}</div>}
{waiters?.length > 0 && (
<>
<button type="button" onClick={() => setSelected(all ? new Set() : new Set(waiters.map(w => w.id)))}
style={{ ...chip(all), height: 52, justifyContent: 'center', gap: 8, color: all ? KDS.accent : '#7b8694', fontSize: 14, fontWeight: 700 }}>
{all ? <Check style={{ width: 16, height: 16 }} /> : null}
{t('kds.call.all')}
</button>
{waiters.map(w => {
const on = selected.has(w.id)
const name = w.nickname || w.username
return (
<button key={w.id} type="button" data-waiter={w.id} onClick={() => toggle(w.id)}
style={{ ...chip(on), height: 60, gap: 14, padding: '0 16px', color: KDS.panelInk, fontSize: 15, fontWeight: 600 }}>
<span style={{ width: 36, height: 36, borderRadius: '50%', flexShrink: 0, background: on ? KDS.accent : KDS.panelLine,
display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontWeight: 700 }}>
{on ? <Check style={{ width: 18, height: 18 }} /> : name?.[0]?.toUpperCase()}
</span>
<span style={{ flex: 1, textAlign: 'left' }}>{name}</span>
</button>
)
})}
</>
)}
</div>
<div style={{ display: 'flex', gap: 10, padding: '14px 20px', borderTop: `1px solid ${KDS.panelLine2}` }}>
<button type="button" onClick={onClose} style={{ ...secondaryButton, height: 52 }}>{t('kds.cancel')}</button>
<button type="button" data-testid="call-send" onClick={send} disabled={!ready} style={{
flex: 2, height: 52, borderRadius: 11, background: ready ? KDS.amber : KDS.panelLine, color: ready ? '#0e1217' : '#5e6772',
fontSize: 15, fontWeight: 700, border: 'none', cursor: ready ? 'pointer' : 'default', fontFamily: 'inherit',
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
}}>
<BellRing style={{ width: 18, height: 18 }} />
{sending ? t('kds.call.sending') : selected.size ? t('kds.call.sendCount', { count: selected.size }) : t('kds.call.send')}
</button>
</div>
</KdsModal>
)
}
export function Toasts({ toasts }) {
return (
<div style={{ position: 'absolute', bottom: 18, left: '50%', transform: 'translateX(-50%)', zIndex: 300, display: 'flex',
flexDirection: 'column', gap: 8, alignItems: 'center', pointerEvents: 'none' }}>
{toasts.map(x => (
<div key={x.id} data-testid="kds-toast" style={{ background: '#2b333d', color: '#eef2f6', border: '1px solid #3a4450', padding: '11px 18px',
borderRadius: 10, fontSize: 14, fontWeight: 600, boxShadow: '0 8px 22px rgba(0,0,0,.4)' }}>
{x.msg}
</div>
))}
</div>
)
}
@@ -0,0 +1,99 @@
// One item on an order card: quantity badge, name, changes (− removed, + extras, → choices)
// and its note. On the selected card a tap moves it on, a long press declines it.
import { useRef } from 'react'
import { ArrowRight, Info, Minus, Plus } from 'lucide-react'
import { dedupeModifiers, formatQty, hasUnit } from '../logic/board'
import { KDS } from '../theme'
const MOD_ICON_SZ = 13
const HOLD_MS = 500
export function ModRow({ Icon, color, text, done, fs }) {
const col = done ? KDS.doneInk : color
const fontSize = Math.round(12 * fs)
const lineH = Math.round(fontSize * 1.4)
const iconSz = Math.round(MOD_ICON_SZ * fs)
return (
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 4, color: col, fontSize, fontWeight: 600, textDecoration: done ? 'line-through' : 'none' }}>
{/* one line tall, so the icon sits on the first line when the text wraps */}
<span style={{ flexShrink: 0, width: iconSz, height: lineH, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
<Icon style={{ width: iconSz, height: iconSz, color: col }} />
</span>
<span style={{ lineHeight: `${lineH}px` }}>{text}</span>
</div>
)
}
export default function ItemBlock({ item, focused, onBump, onDecline, fontScale = 1, fontWeight = 600, combineModifiers }) {
const status = item.kds_status
const done = status === 'done' || status === 'served'
const preparing = status === 'preparing'
const fs = fontScale
const removed = dedupeModifiers(item.removed ?? [])
const extras = dedupeModifiers(item.extras ?? [])
const prefs = dedupeModifiers(item.prefs ?? [])
const hasMods = removed.length || extras.length || prefs.length || item.notes
const nameFontSize = Math.round(15 * fs)
const nameLineH = Math.round(nameFontSize * 1.4)
const badgeH = nameLineH
const hold = useRef(null)
const cancelHold = () => { if (hold.current) { clearTimeout(hold.current); hold.current = null } }
const onPointerDown = focused && onDecline ? e => {
e.stopPropagation()
hold.current = setTimeout(() => { hold.current = null; onDecline(item) }, HOLD_MS)
} : undefined
return (
<div
data-item={item.id} data-status={status}
onClick={focused ? e => { e.stopPropagation(); cancelHold(); onBump?.(item) } : undefined}
onPointerDown={onPointerDown} onPointerUp={cancelHold} onPointerLeave={cancelHold} onPointerCancel={cancelHold}
style={{ borderRadius: 7, margin: '0 -5px', padding: '2px 5px', cursor: focused ? 'pointer' : 'default',
transition: 'background .1s', opacity: done ? 0.55 : 1, touchAction: 'none' }}
>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
<span style={{
flexShrink: 0, minWidth: badgeH, height: badgeH,
paddingLeft: hasUnit(item.unit_type) ? Math.round(4 * fs) : 0, paddingRight: hasUnit(item.unit_type) ? Math.round(4 * fs) : 0,
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
background: done ? '#f1f2f4' : KDS.qtyBg, color: done ? KDS.doneInk : KDS.qtyInk,
borderRadius: Math.round(5 * fs), fontFamily: 'ui-monospace, monospace', fontWeight: 700, fontSize: Math.round(12 * fs), lineHeight: 1,
}}>
{formatQty(item.quantity, item.unit_type)}
</span>
<span style={{
color: done ? KDS.doneInk : KDS.ink, fontSize: nameFontSize, fontWeight, lineHeight: `${nameLineH}px`,
textDecoration: done ? 'line-through' : 'none', textDecorationThickness: 2, flex: '1 1 auto', minWidth: 0,
}}>
{item.product_name}
</span>
{focused && (
<span style={{
flexShrink: 0, width: 8, height: 8, borderRadius: 4, display: 'inline-block', marginTop: Math.round((badgeH - 8) / 2),
background: done ? KDS.green : preparing ? KDS.accent : KDS.qtyBg,
border: `1px solid ${done ? KDS.greenD : preparing ? KDS.accent : '#ccc'}`,
}} />
)}
</div>
{hasMods ? (
<div style={{ marginTop: 3, paddingLeft: badgeH + 7, display: 'flex', flexDirection: 'column', gap: 3 }}>
{combineModifiers ? (
<>
{removed.length > 0 && <ModRow Icon={Minus} color={KDS.redD} text={removed.join(' · ')} done={done} fs={fs} />}
{extras.length > 0 && <ModRow Icon={Plus} color={KDS.greenD} text={extras.join(' · ')} done={done} fs={fs} />}
{prefs.length > 0 && <ModRow Icon={ArrowRight} color={KDS.amberD} text={prefs.join(' · ')} done={done} fs={fs} />}
</>
) : (
<>
{removed.map((r, i) => <ModRow key={`r${i}`} Icon={Minus} color={KDS.redD} text={r} done={done} fs={fs} />)}
{extras.map((x, i) => <ModRow key={`e${i}`} Icon={Plus} color={KDS.greenD} text={x} done={done} fs={fs} />)}
{prefs.map((p, i) => <ModRow key={`p${i}`} Icon={ArrowRight} color={KDS.amberD} text={p} done={done} fs={fs} />)}
</>
)}
{item.notes && <ModRow Icon={Info} color="#3b82f6" text={item.notes} done={done} fs={fs} />}
</div>
) : null}
</div>
)
}
@@ -0,0 +1,42 @@
// Off-screen copy of every visible card's items, so the layout engine knows each item's real
// height (plan step 3.2b, from KdsPage.jsx). Reports { [orderId]: { blocks: [px…] } } when
// anything changed by more than half a pixel.
import { useEffect, useRef } from 'react'
import { BLOCK_GAP, BODY_PAD_H } from '../logic/layout'
import ItemBlock from './ItemBlock'
export default function MeasureLayer({ orders, colW, fontScale, fontWeight, combineModifiers, onResult }) {
const itemRefs = useRef({})
const prevRef = useRef({})
useEffect(() => {
const measured = {}
for (const o of orders) {
const refs = itemRefs.current[o.id] || []
measured[o.id] = { blocks: o.items.map((_, i) => refs[i]?.offsetHeight ?? 36) }
}
const prev = prevRef.current
const keys = Object.keys(measured)
const changed = keys.length !== Object.keys(prev).length || keys.some(k => {
const a = prev[k], b = measured[k]
return !a || a.blocks.length !== b.blocks.length || a.blocks.some((h, i) => Math.abs(h - b.blocks[i]) > 0.5)
})
if (changed) { prevRef.current = measured; onResult(measured) }
})
return (
<div aria-hidden="true" style={{ position: 'absolute', left: -99999, top: 0, visibility: 'hidden', pointerEvents: 'none',
width: colW - BODY_PAD_H * 2, fontSize: 14 * fontScale }}>
{orders.map(o => (
<div key={o.id} style={{ padding: '9px 10px' }}>
{o.items.map((item, i) => (
<div key={item.id} style={{ marginBottom: i < o.items.length - 1 ? BLOCK_GAP : 0 }}
ref={el => { (itemRefs.current[o.id] ||= [])[i] = el }}>
<ItemBlock item={item} focused={false} fontScale={fontScale} fontWeight={fontWeight} combineModifiers={combineModifiers} />
</div>
))}
</div>
))}
</div>
)
}
@@ -0,0 +1,213 @@
// An order on the kitchen board (plan step 3.2b, from KdsPage.jsx): header coloured by how
// late it is (age colours are device settings), item count, table / takeaway / delivery,
// order number and status, the items (in columns, by course or by round), the order note
// and the waiter. Tap selects it (buttons appear, items become tappable; it deselects
// itself after 5 s without a touch); a long press on an unselected card shows quick actions.
import { Fragment, useCallback, useEffect, useRef, useState } from 'react'
import { Bike, Info, ShoppingBag, User, Utensils } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { courseGroups, minutesSince } from '../logic/board'
import { BLOCK_GAP, BODY_PAD_B, BODY_PAD_H, BODY_PAD_T, CARD_FOOT_H_BASE, CARD_HEAD_H_BASE, CARD_SUB_H_BASE } from '../logic/layout'
import { KDS } from '../theme'
import { ActionBar, QuickActionBar } from './ActionBars'
import ItemBlock from './ItemBlock'
const HOLD_MS = 500
const IDLE_DESELECT_MS = 5000
const CHANNEL_ICONS = { here: Utensils, takeaway: ShoppingBag, delivery: Bike }
function ChannelBadge({ orderType, tableName, fs }) {
const { t } = useTranslation('terminal')
const type = CHANNEL_ICONS[orderType] ? orderType : 'here'
const Icon = CHANNEL_ICONS[type]
const iconSz = Math.round(17 * fs)
return (
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: Math.round(15 * fs), fontWeight: 700, whiteSpace: 'nowrap', color: 'rgba(255,255,255,0.60)', flexShrink: 0 }}>
<Icon style={{ width: iconSz, height: iconSz, opacity: 0.65 }} />
{type === 'here' && tableName ? tableName : t(`kds.channel.${type}`)}
</span>
)
}
function headColours(age, colours) {
if (age === 'done') return [colours.done, KDS.doneSub]
if (age === 'future') return [KDS.futureHead, KDS.futureSubBg]
if (age === 'green') return [colours.fresh, KDS.greenD]
if (age === 'amber') return [colours.warning, KDS.amberD]
return [colours.late, KDS.redD]
}
function glowFor(order, age) {
if (age === 'done') return KDS.glowDone
if (age === 'future') return KDS.glowFuture
return order.kds_status === 'preparing' ? KDS.glowPreparing : KDS.glowPending
}
export default function OrderCard({ order, age, ageText, layout, focused, dimmed, settings, multiFilter, courses, now,
onFocus, onStatus, onBumpItem, onPrint, onDecline, onItemDecline, onCallWaiter }) {
const { t } = useTranslation('terminal')
const fs = settings.fontScale
const [headBg, subBg] = headColours(age.age, settings.colours)
const glow = multiFilter ? glowFor(order, age.age) : null
const itemCount = order.items.reduce((s, it) => s + it.quantity, 0)
const waiter = order.waiters?.length ? order.waiters[0] : null
const isFuture = age.age === 'future'
// long press on an unselected card → quick actions
const [quick, setQuick] = useState(false)
const hold = useRef(null)
const cancelHold = () => { if (hold.current) { clearTimeout(hold.current); hold.current = null } }
const onPointerDown = () => {
if (focused) return
hold.current = setTimeout(() => { hold.current = null; setQuick(true) }, HOLD_MS)
}
// a selected card deselects itself after a few seconds without a touch
const idle = useRef(null)
const resetIdle = useCallback(() => {
if (!focused) return
if (idle.current) clearTimeout(idle.current)
idle.current = setTimeout(() => onFocus(null), IDLE_DESELECT_MS)
}, [focused, onFocus])
useEffect(() => {
if (focused) resetIdle()
else if (idle.current) { clearTimeout(idle.current); idle.current = null }
return () => { if (idle.current) clearTimeout(idle.current) }
}, [focused, resetIdle])
const item = it => (
<ItemBlock key={it.id} item={it} focused={focused} fontScale={fs} fontWeight={settings.fontWeight}
combineModifiers={settings.combineModifiers}
onBump={x => { resetIdle(); onBumpItem(order.id, x.id) }}
onDecline={focused ? x => { resetIdle(); onItemDecline(order.id, x.id, x.product_name) } : null} />
)
const column = (key, children) => (
<div key={key} style={{ display: 'flex', flexDirection: 'column', gap: BLOCK_GAP, flex: '1 1 0', minWidth: 0 }}>{children}</div>
)
const deselect = e => { if (focused) { e.stopPropagation(); onFocus(null) } }
let body
if (settings.batchMode === 'grouped' && order._batches?.length > 1) {
body = column('rounds', order._batches.map((batch, bi) => {
const items = order.items.filter(it => (it._batchIndex ?? 0) === bi)
if (!items.length) return null
return (
<Fragment key={bi}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 10 * fs, fontWeight: 700, textTransform: 'uppercase',
letterSpacing: '.1em', color: '#7b8694', padding: bi === 0 ? '0 0 2px' : '4px 0 2px' }}>
<div style={{ flex: 1, height: 1, background: '#e0e5eb' }} />
<span>{t('kds.card.batch', { n: bi + 1 })}</span>
<span style={{ background: '#f0f2f5', color: '#5b6370', borderRadius: 5, padding: '1px 6px', fontFamily: 'ui-monospace, monospace' }}>
{t('kds.age.minutes', { m: Math.max(0, minutesSince(batch.opened_at, now)) })}
</span>
<div style={{ flex: 1, height: 1, background: '#e0e5eb' }} />
</div>
{items.map(item)}
</Fragment>
)
}))
} else {
body = layout.cols.map((col, ci) => {
const colItems = col.map(idx => order.items[idx]).filter(Boolean)
if (settings.groupByCourse && courses?.length > 0) {
return column(ci, courseGroups(colItems, courses).map((g, gi) => (
<div key={gi}>
<div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em',
color: g.course ? g.course.color : '#6b7a8d', padding: '4px 10px 2px' }}>
{g.course ? g.course.name : t('kds.card.noCourse')}
</div>
{g.items.map(item)}
</div>
)))
}
return column(ci, colItems.map(item))
})
}
return (
<div
data-testid="kds-card" data-order={order.id} data-status={order.kds_status} data-age={age.age} data-focused={focused ? 'true' : 'false'}
onClick={e => { e.stopPropagation(); cancelHold(); if (!quick) { onFocus(order.id); resetIdle() } }}
onPointerDown={onPointerDown} onPointerUp={cancelHold} onPointerLeave={cancelHold} onPointerCancel={cancelHold}
style={{
position: 'absolute', left: layout.x, top: layout.y, width: layout.w, height: layout.h,
background: headBg, borderRadius: 10, overflow: 'hidden',
boxShadow: focused
? `0 10px 24px rgba(0,0,0,.4), 0 0 0 4px rgba(47,127,240,.25)${glow ? `, 0 0 0 2px ${glow}40` : ''}`
: `0 1px 2px rgba(0,0,0,.25), 0 6px 16px rgba(0,0,0,.22)${glow ? `, 0 0 12px 2px ${glow}55, 0 0 0 2px ${glow}44` : ''}`,
outline: focused ? `2px solid ${KDS.accent}` : '2px solid transparent', outlineOffset: 2,
display: 'flex', flexDirection: 'column',
transform: focused ? 'scale(1.012)' : 'none', transition: 'box-shadow .15s, transform .15s, outline-color .15s',
opacity: dimmed ? 0.42 : 1, filter: dimmed ? 'saturate(.7)' : 'none', zIndex: focused ? 60 : 1,
cursor: 'pointer', userSelect: 'none', WebkitUserSelect: 'none', touchAction: 'none',
}}
>
<div className={age.flash && settings.flashLate ? 'kds-flash' : undefined} style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 11px', color: '#fff',
height: Math.round(CARD_HEAD_H_BASE * fs), flexShrink: 0, background: headBg, gap: 8,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
<span data-testid="card-age" style={{
background: 'rgba(255,255,255,0.92)', color: '#0a0c0f', borderRadius: 7, padding: `0 ${Math.round(9 * fs)}px`,
height: Math.round(30 * fs), fontSize: Math.round(17 * fs), fontWeight: 800, fontVariantNumeric: 'tabular-nums',
letterSpacing: '-0.02em', flexShrink: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
}}>
{ageText}
</span>
<span style={{ fontSize: 12 * fs, fontWeight: 600, opacity: 0.9, whiteSpace: 'nowrap', lineHeight: 1 }}>
{t('kds.card.items', { count: itemCount })}
</span>
</div>
<div onClick={deselect}><ChannelBadge orderType={order.order_type} tableName={order.table_name} fs={fs} /></div>
</div>
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: subBg, color: 'rgba(255,255,255,0.88)',
padding: '0 11px', height: Math.round(CARD_SUB_H_BASE * fs), flexShrink: 0, fontSize: 12.5 * fs, fontWeight: 600,
}}>
<span style={{ fontFamily: 'ui-monospace, monospace', letterSpacing: '.02em', opacity: 0.85, lineHeight: 1 }}>#{order.id}</span>
<span onClick={deselect} style={{ fontSize: 11 * fs, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', lineHeight: 1 }}>
{t(`kds.card.status.${order.kds_status === 'done' || order.kds_status === 'preparing' ? order.kds_status : 'pending'}`)}
</span>
</div>
<div style={{
background: isFuture ? '#f0f2f5' : order.kds_status === 'done' ? '#f4f7f4' : order.kds_status === 'preparing' ? '#f3f8ff' : '#ffffff',
paddingTop: BODY_PAD_T, paddingBottom: BODY_PAD_B, paddingLeft: BODY_PAD_H, paddingRight: BODY_PAD_H,
display: 'flex', gap: 12, flex: '1 1 auto', overflow: 'hidden',
}}>
{body}
</div>
{order.notes && (
<div style={{ background: '#fffbeb', borderTop: `1px solid ${KDS.line}`, flexShrink: 0 }}>
<div style={{ height: Math.round(6 * fs) }} />
<div style={{
padding: `0 ${Math.round(BODY_PAD_H * fs)}px ${Math.round(8 * fs)}px`, fontSize: Math.round(12.5 * fs), fontWeight: 600,
color: '#b45309', fontStyle: 'italic', lineHeight: 1.45, display: 'flex', alignItems: 'flex-start', gap: Math.round(5 * fs),
}}>
<Info style={{ width: Math.round(13 * fs), height: Math.round(13 * fs), flexShrink: 0, marginTop: Math.round(2 * fs), color: '#d97706' }} />
<span>{order.notes}</span>
</div>
</div>
)}
{waiter && (
<div style={{
background: KDS.cardFoot, color: KDS.cardFootInk, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
height: Math.round(CARD_FOOT_H_BASE * fs), flexShrink: 0, fontSize: 13 * fs, fontWeight: 700, borderTop: `1px solid ${KDS.line}`,
}}>
<User style={{ width: 13, height: 13, opacity: 0.7 }} />
{waiter}
</div>
)}
{quick && !focused && (
<QuickActionBar order={order} onStatus={onStatus} onDecline={onDecline} onDismiss={() => setQuick(false)} fs={fs} />
)}
{focused && (
<ActionBar order={order} onStatus={onStatus} onPrint={onPrint} onCallWaiter={onCallWaiter} fs={fs} hasWaiter={!!waiter} />
)}
</div>
)
}
+131
View File
@@ -0,0 +1,131 @@
// The board's side rail (status filters with counts, undo/redo, call, sound, settings) and
// top bar (here / takeaway / delivery tabs, item totals button, venue clock, zoom).
// Plan step 3.2b, from KdsPage.jsx.
import { BellRing, CheckCheck, Clock, CookingPot, Flame, Redo2, Settings, Timer, Undo2, Volume2, VolumeX, ZoomIn, ZoomOut } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { KDS } from '../theme'
const STATUSES = [
{ key: 'future', Icon: Clock, colour: KDS.green },
{ key: 'pending', Icon: Timer, colour: KDS.amber },
{ key: 'preparing', Icon: Flame, colour: KDS.accent },
{ key: 'done', Icon: CheckCheck, colour: '#cdd6e0' },
]
function RailButton({ active, colour, onClick, disabled, fs, children, testId }) {
return (
<button type="button" data-testid={testId} data-active={active ? 'true' : 'false'} onClick={onClick} disabled={disabled} style={{
position: 'relative', width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center',
gap: Math.round(4 * fs), padding: `${Math.round(9 * fs)}px ${Math.round(4 * fs)}px`, borderRadius: Math.round(10 * fs),
color: active ? colour : '#8b95a1', background: active ? 'rgba(255,255,255,0.06)' : 'none',
border: active ? '1px solid rgba(255,255,255,0.08)' : '1px solid transparent',
cursor: disabled ? 'default' : 'pointer', fontFamily: 'inherit', opacity: disabled ? 0.32 : 1, transition: 'background .12s, color .12s, opacity .15s',
}}>
{children}
</button>
)
}
export function SideRail({ filters, counts, onToggleFilter, soundOn, onToggleSound, canUndo, canRedo, onUndo, onRedo, onSettings, onCall, fontScale = 1 }) {
const { t } = useTranslation('terminal')
const fs = fontScale
const lg = { width: Math.round(24 * fs), height: Math.round(24 * fs) }
const sm = { width: Math.round(20 * fs), height: Math.round(20 * fs) }
const label = text => <span style={{ fontSize: Math.round(10 * fs), fontWeight: 600, letterSpacing: '.06em', textTransform: 'uppercase' }}>{text}</span>
const badgeH = Math.round(22 * fs)
const group = { display: 'flex', flexDirection: 'column', gap: 2, padding: `2px ${Math.round(8 * fs)}px` }
return (
<nav data-testid="kds-rail" style={{ width: Math.round(KDS.railW * fs), flexShrink: 0, background: KDS.rail, borderRight: `1px solid ${KDS.railLine}`,
display: 'flex', flexDirection: 'column', alignItems: 'stretch', padding: `${Math.round(10 * fs)}px 0`, gap: 2, overflowY: 'auto' }}>
<div style={group}>
{STATUSES.map(({ key, Icon, colour }) => {
const active = filters.has(key)
return (
<RailButton key={key} testId={`filter-${key}`} active={active} colour={colour} onClick={() => onToggleFilter(key)} fs={fs}>
<Icon style={lg} />
{label(t(`kds.rail.${key}`))}
<span data-testid={`count-${key}`} style={{ minWidth: badgeH, height: badgeH, padding: `0 ${Math.round(6 * fs)}px`, display: 'inline-flex',
alignItems: 'center', justifyContent: 'center', borderRadius: Math.round(11 * fs), fontSize: Math.round(12 * fs), fontWeight: 700,
background: active ? colour : '#2b333d', color: active ? '#0e1217' : '#cfd6df' }}>
{counts[key] || 0}
</span>
</RailButton>
)
})}
<div style={{ height: 1, background: KDS.railLine, margin: `${Math.round(6 * fs)}px` }} />
<RailButton testId="kds-undo" active={false} colour="#fff" onClick={onUndo} disabled={!canUndo} fs={fs}><Undo2 style={sm} />{label(t('kds.rail.undo'))}</RailButton>
<RailButton testId="kds-redo" active={false} colour="#fff" onClick={onRedo} disabled={!canRedo} fs={fs}><Redo2 style={sm} />{label(t('kds.rail.redo'))}</RailButton>
</div>
<div style={{ flex: '1 1 auto' }} />
<div style={group}>
<RailButton testId="kds-call" active={false} colour="#fff" onClick={onCall} fs={fs}><BellRing style={sm} />{label(t('kds.rail.call'))}</RailButton>
<RailButton testId="kds-sound" active={false} colour="#fff" onClick={onToggleSound} fs={fs}>
{soundOn ? <Volume2 style={sm} /> : <VolumeX style={sm} />}{label(soundOn ? t('kds.rail.sound') : t('kds.rail.muted'))}
</RailButton>
<RailButton testId="kds-settings" active={false} colour="#fff" onClick={onSettings} fs={fs}><Settings style={sm} />{label(t('kds.rail.settings'))}</RailButton>
</div>
</nav>
)
}
const TABS = ['all', 'here', 'takeaway', 'delivery']
export function TopBar({ tab, counts, onTab, now, fontScale = 1, zoomPercent, onZoom, showSummaryButton, summaryOpen, onToggleSummary }) {
const { t } = useTranslation('terminal')
const { formatDate, formatTime } = useFormat()
const fs = fontScale
const tabH = Math.round(36 * fs)
const tabR = Math.round(9 * fs)
const clockFont = { fontSize: Math.round(14 * fs), fontFamily: 'Arial, "Helvetica Neue", sans-serif' }
const zoomButton = { width: tabH, height: tabH, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'none', border: 'none',
cursor: 'pointer', color: KDS.tabInk, borderRadius: Math.round(7 * fs) }
const zi = { width: Math.round(15 * fs), height: Math.round(15 * fs) }
return (
<div data-testid="kds-topbar" style={{ height: Math.round(KDS.topbarH * fs), flexShrink: 0, background: KDS.topbar, borderBottom: `1px solid ${KDS.railLine}`,
display: 'flex', alignItems: 'center', gap: 8, padding: '0 12px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0, overflowX: 'auto' }}>
{TABS.map(key => {
const active = tab === key
return (
<button key={key} type="button" data-testid={`tab-${key}`} onClick={() => onTab(key)} style={{
flexShrink: 0, display: 'flex', alignItems: 'center', gap: Math.round(7 * fs), height: tabH, padding: `0 ${Math.round(14 * fs)}px`,
borderRadius: tabR, background: active ? KDS.tabActiveBg : KDS.tab, color: active ? KDS.tabActiveInk : KDS.tabInk,
fontSize: Math.round(13 * fs), fontWeight: 600, whiteSpace: 'nowrap', border: 'none', cursor: 'pointer', fontFamily: 'inherit',
}}>
{key === 'all' ? t('kds.tabs.all') : t(`kds.channel.${key}`)}
<span style={{ minWidth: Math.round(20 * fs), height: Math.round(20 * fs), padding: `0 ${Math.round(5 * fs)}px`, display: 'inline-flex',
alignItems: 'center', justifyContent: 'center', borderRadius: Math.round(6 * fs), fontSize: Math.round(11 * fs), fontWeight: 700,
background: active ? 'rgba(0,0,0,.10)' : 'rgba(255,255,255,.08)', color: active ? '#41474f' : KDS.tabInk }}>
{counts[key] ?? 0}
</span>
</button>
)
})}
</div>
<div style={{ flex: '1 1 0' }} />
{showSummaryButton && (
<button type="button" data-testid="summary-button" onClick={onToggleSummary} style={{
flexShrink: 0, display: 'flex', alignItems: 'center', gap: Math.round(6 * fs), height: tabH, padding: `0 ${Math.round(14 * fs)}px`,
borderRadius: tabR, background: summaryOpen ? KDS.tabActiveBg : KDS.tab, color: summaryOpen ? KDS.tabActiveInk : KDS.tabInk,
fontSize: Math.round(13 * fs), fontWeight: 600, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
}}>
<CookingPot style={zi} />
{t('kds.summary.button')}
</button>
)}
<div style={{ flex: '1 1 0' }} />
<div data-testid="kds-clock" style={{ display: 'flex', alignItems: 'center', gap: Math.round(6 * fs), flexShrink: 0, whiteSpace: 'nowrap' }}>
<span style={{ ...clockFont, fontWeight: 600, color: '#c8d0db' }}>{formatDate(now, 'dateLong')}</span>
<span style={{ ...clockFont, fontWeight: 700, color: '#f1f4f8' }}>{formatTime(now)}</span>
</div>
<div style={{ width: 1, height: Math.round(24 * fs), background: KDS.railLine, flexShrink: 0 }} />
<div style={{ display: 'flex', alignItems: 'center', gap: 2, background: KDS.tab, borderRadius: tabR, padding: `0 ${Math.round(4 * fs)}px`, flexShrink: 0, height: tabH }}>
<button type="button" data-testid="zoom-out" aria-label={t('kds.zoom.smaller')} title={t('kds.zoom.smaller')} onClick={() => onZoom(-1)} style={zoomButton}><ZoomOut style={zi} /></button>
<span data-testid="zoom-level" style={{ fontSize: Math.round(11 * fs), fontWeight: 700, color: KDS.tabInk, minWidth: Math.round(34 * fs), textAlign: 'center', fontFamily: 'ui-monospace, monospace' }}>
{zoomPercent}%
</span>
<button type="button" data-testid="zoom-in" aria-label={t('kds.zoom.larger')} title={t('kds.zoom.larger')} onClick={() => onZoom(1)} style={zoomButton}><ZoomIn style={zi} /></button>
</div>
</div>
)
}
@@ -0,0 +1,214 @@
// This screen's settings, changed on the screen itself (plan step 3.2b): the device config of
// 3.2a, saved with PATCH /api/devices/me/config (only someone holding core.devices.manage;
// others see the settings and a note). The texts are the Devices page's
// (modules:kds.config.*), so both places say the same thing. The saved settings come back
// through device.updated → GET /api/devices/me, like an edit on the Devices page.
import { useState } from 'react'
import { Check } from 'lucide-react'
import { useCan } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import client from '../../../api/client'
import { DEFAULT_CONFIG, FONT_SCALE_MAX, FONT_SCALE_MIN, FONT_SCALE_STEP } from '../logic/settings'
import { KDS, secondaryButton } from '../theme'
import { CloseButton, KdsModal } from './Dialogs'
const CARD_WIDTHS = [200, 220, 240, 260, 272, 280, 300, 320, 340, 360, 380, 400, 420, 440, 460, 480, 500, 540, 580, 620, 660, 700, 750, 800]
const WEIGHTS = [300, 400, 500, 600, 700, 800]
const REFRESH = [10, 15, 20, 30, 45, 60, 90, 120]
const SIGN_OUT = [0, 2, 5, 10, 30, 60]
const FONT_SCALES = Array.from({ length: (FONT_SCALE_MAX - FONT_SCALE_MIN) / FONT_SCALE_STEP + 1 }, (_, i) => FONT_SCALE_MIN + i * FONT_SCALE_STEP)
const PRESETS = ['#34b56a', '#7ec828', '#f5c518', '#f07d2a', '#e8513f', '#e84f9a', '#9b5de5', '#2f7ff0', '#1fabbe', '#e7ecf2', '#3d4757']
const TABS = ['zone', 'behaviour', 'board', 'age', 'notifications']
const nearest = (steps, v) => steps.reduce((a, b) => (Math.abs(b - v) < Math.abs(a - v) ? b : a))
function Stepper({ value, steps, display, onChange, min = -Infinity, max = Infinity, testId }) {
const options = steps.filter(s => s >= min && s <= max)
const cur = nearest(options, value)
const i = options.indexOf(cur)
const btn = on => ({
width: 44, height: 44, borderRadius: 10, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
background: on ? '#2e3a47' : '#232d38', color: on ? KDS.panelInk : '#4a5568', border: `1px solid ${on ? '#3d4f5e' : '#2a3542'}`,
cursor: on ? 'pointer' : 'default', fontFamily: 'inherit', fontSize: 22, fontWeight: 300, userSelect: 'none',
})
return (
<div data-testid={testId} style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
<button type="button" aria-label="-" style={btn(i > 0)} onClick={() => i > 0 && onChange(options[i - 1])}>−</button>
<span style={{ minWidth: 64, textAlign: 'center', fontSize: 16, fontWeight: 700, fontFamily: 'ui-monospace, monospace' }}>{display(cur)}</span>
<button type="button" aria-label="+" style={btn(i < options.length - 1)} onClick={() => i < options.length - 1 && onChange(options[i + 1])}>+</button>
</div>
)
}
function Toggle({ on, onToggle, testId }) {
return (
<button type="button" role="switch" aria-checked={on} data-testid={testId} onClick={onToggle} style={{
width: 56, height: 32, borderRadius: 16, flexShrink: 0, background: on ? KDS.accent : '#3a4450', position: 'relative', border: 'none', cursor: 'pointer',
}}>
<span style={{ position: 'absolute', top: 4, left: 4, width: 24, height: 24, borderRadius: '50%', background: '#fff',
transform: on ? 'translateX(24px)' : 'none', transition: 'transform .15s' }} />
</button>
)
}
function Swatches({ value, onChange, testId }) {
return (
<div data-testid={testId} style={{ display: 'flex', flexWrap: 'wrap', gap: 6, maxWidth: 260, justifyContent: 'flex-end' }}>
{PRESETS.map(p => (
<button key={p} type="button" aria-label={p} data-colour={p} onClick={() => onChange(p)} style={{
width: 30, height: 30, borderRadius: 8, background: p, cursor: 'pointer', border: value === p ? '2px solid #fff' : '2px solid transparent',
}} />
))}
{!PRESETS.includes(value) && <span style={{ width: 30, height: 30, borderRadius: 8, background: value, border: '2px solid #fff' }} />}
</div>
)
}
export default function SettingsPanel({ config, context, onClose, onSaved }) {
const { t } = useTranslation('terminal')
const canEdit = useCan('core.devices.manage')
const [local, setLocal] = useState(() => ({ ...DEFAULT_CONFIG, ...(config || {}) }))
const [tab, setTab] = useState('zone')
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const set = (k, v) => setLocal(s => ({ ...s, [k]: v }))
const L = (key, part = 'label') => t(`modules:kds.config.${key}.${part}`, { defaultValue: part === 'label' ? key : '' })
const choice = (key, v) => t(`modules:kds.config.${key}.choices.${v}`, { defaultValue: String(v) })
const row = (key, control) => (
<div key={key} data-setting={key} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, padding: '10px 0', borderBottom: `1px solid ${KDS.panelLine2}` }}>
<div style={{ flex: '1 1 auto', minWidth: 0 }}>
<div style={{ fontSize: 15, fontWeight: 500 }}>{L(key)}</div>
{L(key, 'hint') && <div style={{ fontSize: 12.5, color: KDS.panelInk2, marginTop: 3, lineHeight: 1.4 }}>{L(key, 'hint')}</div>}
</div>
<div style={{ flexShrink: 0 }}>{control}</div>
</div>
)
const toggle = key => row(key, <Toggle testId={`set-${key}`} on={!!local[key]} onToggle={() => set(key, !local[key])} />)
const select = (key, options) => row(key, (
<select data-testid={`set-${key}`} value={String(local[key])} onChange={e => set(key, options.find(o => String(o) === e.target.value))} style={{
height: 44, padding: '0 10px', borderRadius: 10, background: '#232d38', border: '1px solid #3d4f5e', color: KDS.panelInk,
fontSize: 13, fontWeight: 600, fontFamily: 'inherit', maxWidth: 240,
}}>
{options.map(o => <option key={o} value={String(o)}>{choice(key, o)}</option>)}
</select>
))
const minutes = (key, min, max) => row(key, (
<Stepper testId={`set-${key}`} value={local[key]} steps={Array.from({ length: 120 }, (_, i) => i + 1)} min={min} max={max}
display={v => t('kds.age.minutes', { m: v })} onChange={v => set(key, v)} />
))
const zones = context?.prep_zones ?? []
const zoneButton = (id, name) => {
const on = (local.prep_zone_id ?? null) === id
return (
<button key={id ?? 'all'} type="button" data-zone={id ?? 'all'} onClick={() => set('prep_zone_id', id)} style={{
padding: '12px 8px', borderRadius: 10, minHeight: 64, fontFamily: 'inherit', cursor: 'pointer', fontSize: 12, fontWeight: on ? 700 : 500,
background: on ? 'rgba(47,127,240,.15)' : KDS.field, border: `2px solid ${on ? KDS.accent : KDS.panelLine}`, color: on ? KDS.panelInk : '#9ca8b6',
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4,
}}>
{on && <Check style={{ width: 14, height: 14, color: KDS.accent }} />}
<span style={{ lineHeight: 1.3 }}>{name}</span>
</button>
)
}
const content = {
zone: (
<div>
<div style={{ fontSize: 12.5, color: KDS.panelInk2, padding: '12px 0 14px', lineHeight: 1.5 }}>{L('prep_zone_id', 'hint')}</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
{zoneButton(null, t('modules:kds.config.prep_zone_id.none'))}
{zones.map(z => zoneButton(z.id, z.name))}
</div>
</div>
),
behaviour: (
<div>
{row('refresh_seconds', <Stepper testId="set-refresh_seconds" value={local.refresh_seconds} steps={REFRESH} display={v => t('kds.settings.seconds', { s: v })} onChange={v => set('refresh_seconds', v)} />)}
{toggle('triple_state')}
{toggle('categories_as_filters')}
{toggle('group_by_course')}
{select('group_items', ['off', 'floating', 'right_sidebar', 'left_sidebar', 'topbar_button'])}
{select('batch_mode', ['merged', 'grouped', 'split'])}
{select('auto_sign_out_minutes', SIGN_OUT)}
</div>
),
board: (
<div>
{row('card_width', <Stepper testId="set-card_width" value={local.card_width} steps={CARD_WIDTHS} display={v => `${v}px`} onChange={v => set('card_width', v)} />)}
{row('font_scale', <Stepper testId="set-font_scale" value={local.font_scale} steps={FONT_SCALES} display={v => `${v}%`} onChange={v => set('font_scale', v)} />)}
{select('font_weight', WEIGHTS)}
{toggle('flash_late')}
{toggle('combine_modifiers')}
</div>
),
age: (
<div>
{minutes('age_warning_minutes', 1, local.age_late_minutes - 1)}
{minutes('age_late_minutes', local.age_warning_minutes + 1, local.age_flash_minutes - 1)}
{minutes('age_flash_minutes', local.age_late_minutes + 1, 120)}
{['colour_fresh', 'colour_warning', 'colour_late', 'colour_done'].map(k => row(k, <Swatches testId={`set-${k}`} value={local[k]} onChange={v => set(k, v)} />))}
</div>
),
notifications: (
<div>
{toggle('sound')}
{toggle('notify_order_complete')}
{toggle('notify_item_complete')}
</div>
),
}
const save = async () => {
setBusy(true)
setError('')
const changed = Object.fromEntries(Object.entries(local).filter(([k, v]) => (config || {})[k] !== v && k in DEFAULT_CONFIG))
try {
if (Object.keys(changed).length) await client.patch('/api/devices/me/config', { config: changed })
onSaved?.()
onClose()
} catch (err) {
setError(errorMessage(err, t))
} finally {
setBusy(false)
}
}
return (
<KdsModal width={680} onClose={onClose} testId="kds-settings-panel">
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 22px 0' }}>
<h2 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>{t('kds.settings.title')}</h2>
<CloseButton onClick={onClose} label={t('kds.close')} />
</div>
<div style={{ display: 'flex', gap: 4, padding: '14px 22px 0', borderBottom: `1px solid ${KDS.panelLine2}`, overflowX: 'auto' }}>
{TABS.map(k => (
<button key={k} type="button" data-testid={`settings-tab-${k}`} onClick={() => setTab(k)} style={{
height: 40, padding: '0 18px', borderRadius: '9px 9px 0 0', background: tab === k ? KDS.panelLine2 : 'none',
color: tab === k ? '#f1f4f8' : KDS.panelInk2, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 14,
fontWeight: tab === k ? 700 : 500, borderBottom: tab === k ? `2px solid ${KDS.accent}` : '2px solid transparent', whiteSpace: 'nowrap',
}}>
{t(`kds.settings.tabs.${k}`)}
</button>
))}
</div>
<div style={{ height: 470, maxHeight: '60vh', overflowY: 'auto', padding: '6px 22px 12px' }}>{content[tab]}</div>
{!canEdit && (
<div data-testid="settings-no-permission" style={{ padding: '10px 22px', fontSize: 13, color: '#fcd34d', borderTop: `1px solid ${KDS.panelLine2}` }}>
{t('kds.settings.noPermission')}
</div>
)}
{error && <div role="alert" style={{ padding: '10px 22px', fontSize: 13, color: '#fca5a5' }}>{error}</div>}
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '14px 22px', borderTop: `1px solid ${KDS.panelLine2}` }}>
<button type="button" onClick={onClose} style={{ ...secondaryButton, flex: '0 0 auto', padding: '0 22px' }}>{t('kds.cancel')}</button>
<button type="button" data-testid="settings-save" onClick={save} disabled={!canEdit || busy} style={{
height: 48, padding: '0 24px', borderRadius: 11, background: canEdit ? KDS.accent : KDS.panelLine, color: canEdit ? '#fff' : '#5e6772',
fontSize: 15, fontWeight: 700, border: 'none', cursor: canEdit && !busy ? 'pointer' : 'default', display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'inherit',
}}>
<Check style={{ width: 18, height: 18 }} /> {t('kds.settings.save')}
</button>
</div>
</KdsModal>
)
}
@@ -0,0 +1,104 @@
// Item totals across the visible orders (device setting group_items, plan step 3.2b): a side
// panel left or right, a floating panel, or a window opened from the top bar.
import { useMemo } from 'react'
import { ArrowRight, Info, Minus, Plus, X } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { buildItemGroups } from '../logic/board'
const MOD_ICON_SZ = 13
function Mod({ Icon, color, text, fs }) {
const fontSize = Math.round(12 * fs)
const iconSz = Math.round(MOD_ICON_SZ * fs)
return (
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 4, color, fontSize, fontWeight: 600 }}>
<span style={{ flexShrink: 0, width: iconSz, height: Math.round(fontSize * 1.4), display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
<Icon style={{ width: iconSz, height: iconSz }} />
</span>
<span>{text}</span>
</div>
)
}
export default function SummaryPanel({ orders, mode, open, onClose, fontScale = 1, fontWeight = 600 }) {
const { t } = useTranslation('terminal')
const groups = useMemo(() => buildItemGroups(orders), [orders])
const fs = fontScale
const nameFontSize = Math.round(15 * fs)
const nameLineH = Math.round(nameFontSize * 1.4)
const isModal = mode === 'floating' || mode === 'topbar_button'
const panel = { background: '#161b21', border: '1px solid #2b3540', borderRadius: isModal ? 14 : 0, color: '#e7ecf2',
display: 'flex', flexDirection: 'column', overflow: 'hidden' }
const header = (
<div style={{ padding: `${Math.round(10 * fs)}px ${Math.round(14 * fs)}px`, borderBottom: '1px solid #252e38', flexShrink: 0,
display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div>
<div style={{ fontSize: Math.round(13 * fs), fontWeight: 700, letterSpacing: '.02em' }}>{t('kds.summary.title')}</div>
<div style={{ fontSize: Math.round(11 * fs), color: '#6b7a8d', marginTop: 1 }}>{t('kds.summary.subtitle', { count: groups.length })}</div>
</div>
{mode === 'topbar_button' && (
<button type="button" aria-label={t('kds.close')} onClick={onClose} style={{ width: Math.round(28 * fs), height: Math.round(28 * fs), borderRadius: 8,
display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'none', border: 'none', cursor: 'pointer', color: '#6b7a8d' }}>
<X style={{ width: Math.round(13 * fs), height: Math.round(13 * fs) }} />
</button>
)}
</div>
)
const list = (
<div style={{ overflowY: 'auto', flex: '1 1 auto', padding: `${Math.round(6 * fs)}px 0` }}>
{groups.length === 0 ? (
<div style={{ textAlign: 'center', padding: `${Math.round(24 * fs)}px 0`, color: '#4a5568', fontSize: nameFontSize }}>{t('kds.summary.empty')}</div>
) : groups.map(g => (
<div key={g.key} data-testid="summary-row" style={{ padding: `${Math.round(4 * fs)}px ${Math.round(14 * fs)}px` }}>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
<span style={{ flexShrink: 0, minWidth: nameLineH, height: nameLineH, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
background: '#2b3540', color: '#f1f5f9', borderRadius: Math.round(5 * fs), fontFamily: 'ui-monospace, monospace', fontWeight: 700,
fontSize: Math.round(12 * fs), lineHeight: 1 }}>
{g.count}
</span>
<span style={{ fontSize: nameFontSize, fontWeight, lineHeight: `${nameLineH}px`, flex: '1 1 auto', minWidth: 0 }}>{g.product_name}</span>
</div>
{(g.removed.length || g.extras.length || g.prefs.length || g.notes) ? (
<div style={{ marginTop: 3, paddingLeft: nameLineH + 7, display: 'flex', flexDirection: 'column', gap: 3 }}>
{g.removed.length > 0 && <Mod Icon={Minus} color="#fca5a5" text={g.removed.join(' · ')} fs={fs} />}
{g.extras.length > 0 && <Mod Icon={Plus} color="#86efac" text={g.extras.join(' · ')} fs={fs} />}
{g.prefs.length > 0 && <Mod Icon={ArrowRight} color="#fcd34d" text={g.prefs.join(' · ')} fs={fs} />}
{g.notes && <Mod Icon={Info} color="#93c5fd" text={g.notes} fs={fs} />}
</div>
) : null}
</div>
))}
</div>
)
if (mode === 'right_sidebar' || mode === 'left_sidebar') {
return (
<div data-testid="summary-panel" style={{ ...panel, height: '100%', borderLeft: mode === 'right_sidebar' ? '1px solid #2b3540' : 'none',
borderRight: mode === 'left_sidebar' ? '1px solid #2b3540' : 'none' }}>
{header}{list}
</div>
)
}
if (mode === 'floating') {
return (
<div data-testid="summary-panel" style={{ position: 'absolute', right: 18, zIndex: 50, top: '50%', transform: 'translateY(-50%)',
width: `${Math.round(20 * fs)}vw`, minWidth: 200, maxHeight: '90%', pointerEvents: 'auto', ...panel,
boxShadow: '0 8px 40px rgba(0,0,0,.7), 0 0 0 1px rgba(255,255,255,.06)' }}>
{header}{list}
</div>
)
}
if (mode === 'topbar_button' && open) {
return (
<div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 150, background: 'rgba(10,13,17,.6)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<div data-testid="summary-panel" onClick={e => e.stopPropagation()} style={{ ...panel, width: `${Math.round(20 * fs)}vw`, minWidth: 220, maxHeight: '80vh',
boxShadow: '0 24px 80px rgba(0,0,0,.7)' }}>
{header}{list}
</div>
</div>
)
}
return null
}
+224
View File
@@ -0,0 +1,224 @@
// What the kitchen board shows (ported from the manager's KdsPage.jsx, plan step 3.2b):
// how late an order is, which bucket it's in, the visible cards (filters, tab, sorting,
// rounds/"batches"), item totals and the status changes a tap makes. Pure: unit-tested in
// Node (tests/kds.test.mjs). Texts are made by the components (ageLabel takes `t`).
const HAS_OFFSET = /(?:[zZ]|[+-]\d\d:?\d\d)$/
export const BATCH_GAP_MS = 2 * 60 * 1000 // items more than 2 minutes apart = a new round
/** Epoch ms of a backend timestamp (UTC; a string without an offset is UTC too), or null. */
export function parseUTC(value) {
if (!value) return null
const d = new Date(HAS_OFFSET.test(value) ? value : `${String(value).replace(' ', 'T')}Z`)
return Number.isNaN(d.getTime()) ? null : d.getTime()
}
export function minutesSince(value, now) {
const t = parseUTC(value)
return t == null ? 0 : Math.floor((now - t) / 60_000)
}
/** How late an order is.
* thr = {warning, late, flash} minutes (device settings age_*_minutes):
* age 'green' (new) → 'amber' at warning → 'red' at late → 'red' + flash at flash.
* Done orders count minutes since they were done ('ago'); future orders count down ('until').
* → { age: 'green'|'amber'|'red'|'done'|'future', flash, minutes, kind: 'new'|'elapsed'|'ago'|'until' } */
export function ageState(order, now, thr) {
if (order.kds_status === 'done') {
const minutes = Math.max(0, minutesSince(order.closed_at || order.opened_at, now))
return { age: 'done', flash: false, minutes, kind: 'ago' }
}
const m = minutesSince(order.opened_at, now)
if (m < 0) return { age: 'future', flash: false, minutes: -m, kind: 'until' }
const kind = m === 0 ? 'new' : 'elapsed'
if (m >= thr.flash) return { age: 'red', flash: true, minutes: m, kind }
if (m >= thr.late) return { age: 'red', flash: false, minutes: m, kind }
if (m >= thr.warning) return { age: 'amber', flash: false, minutes: m, kind }
return { age: 'green', flash: false, minutes: m, kind }
}
/** "12m", "1h 5m" (t = useTranslation('terminal').t). */
export function durationLabel(minutes, t) {
return minutes >= 60
? t('kds.age.hours', { h: Math.floor(minutes / 60), m: minutes % 60 })
: t('kds.age.minutes', { m: minutes })
}
export function ageLabel(state, t) {
if (state.kind === 'new') return t('kds.age.new')
const d = durationLabel(state.minutes, t)
return state.kind === 'ago' ? t('kds.age.ago', { time: d }) : d
}
/** The card's clock for a card with several rounds: the oldest round that still has work. */
export function ageOrderFor(order) {
if (!(order._batches?.length > 1)) return order
const open = order._batches.find(b => b.items.some(it => it.kds_status !== 'done' && it.kds_status !== 'served' && it.status !== 'cancelled'))
return open ? { ...order, opened_at: open.opened_at } : order
}
/** Side-rail bucket: future (a pending order scheduled later), pending, preparing, done. */
export function orderBucket(order, now) {
if (order.kds_status !== 'pending') return order.kds_status
return minutesSince(order.opened_at, now) < 0 ? 'future' : 'pending'
}
export function bucketCounts(orders, now) {
const c = { future: 0, pending: 0, preparing: 0, done: 0 }
for (const o of orders) { const b = orderBucket(o, now); c[b] = (c[b] || 0) + 1 }
return c
}
/** Top-bar tab counts within the active buckets. */
export function tabCounts(orders, filters, now) {
const inStatus = orders.filter(o => filters.has(orderBucket(o, now)))
const c = { all: inStatus.length, here: 0, takeaway: 0, delivery: 0 }
for (const o of inStatus) c[o.order_type] = (c[o.order_type] || 0) + 1
return c
}
/** Rounds within an order: items added more than BATCH_GAP_MS apart. Stamps _batchIndex on
* every item (sorted by when it was added) and sets _batches [{opened_at, items}]. */
export function withBatches(order) {
if (!order.items?.length) return order
const sorted = [...order.items].sort((a, b) => (parseUTC(a.added_at) ?? 0) - (parseUTC(b.added_at) ?? 0))
const batches = []
let cur = null
for (const item of sorted) {
const ts = parseUTC(item.added_at) ?? 0
if (!cur || ts - cur.lastTs > BATCH_GAP_MS) {
cur = { opened_at: item.added_at || order.opened_at, items: [], lastTs: ts }
batches.push(cur)
}
cur.items.push(item)
cur.lastTs = ts
}
return {
...order,
_batches: batches.map(({ opened_at, items }) => ({ opened_at, items })),
items: batches.flatMap((b, bi) => b.items.map(it => ({ ...it, _batchIndex: bi }))),
}
}
/** The cards to show, oldest first: active buckets, the tab, the zone's item order
* (sort_items_by: order_time | item_count | alpha), rounds; batchMode 'split' = one card
* per round (id "<order>_b<n>", _realId = the order). */
export function visibleOrders(orders, { filters, tab = 'all', now, sortBy = 'order_time', batchMode = 'merged', locale = 'el' }) {
let v = orders.filter(o => filters.has(orderBucket(o, now)))
if (tab !== 'all') v = v.filter(o => o.order_type === tab)
v = v.slice().sort((a, b) => (parseUTC(a.opened_at) ?? 0) - (parseUTC(b.opened_at) ?? 0))
if (sortBy !== 'order_time') {
v = v.map(o => (!o.items?.length ? o : {
...o,
items: [...o.items].sort((a, b) => {
if (sortBy === 'item_count') return b.quantity - a.quantity
if (sortBy === 'alpha') return (a.product_name || '').localeCompare(b.product_name || '', locale)
return 0
}),
}))
}
v = v.map(withBatches)
if (batchMode !== 'split') return v
const out = []
for (const o of v) {
if (!o._batches || o._batches.length <= 1) { out.push(o); continue }
o._batches.forEach((batch, bi) => out.push({
...o, id: `${o.id}_b${bi}`, _realId: o.id, _batchIndex: bi,
opened_at: batch.opened_at, items: batch.items, _batches: [batch],
}))
}
return out
}
/** Items on a card grouped by course (in the venue's course order; no course last). */
export function courseGroups(items, courses) {
const byKey = {}
for (const item of items) {
const key = item.course_id != null ? String(item.course_id) : '__none__'
;(byKey[key] ||= []).push(item)
}
const out = []
for (const course of courses) if (byKey[String(course.id)]?.length) out.push({ course, items: byKey[String(course.id)] })
if (byKey.__none__?.length) out.push({ course: null, items: byKey.__none__ })
return out
}
/** "2x Sauce" for repeated changes. */
export function dedupeModifiers(arr) {
const counts = new Map()
for (const name of arr) counts.set(name, (counts.get(name) || 0) + 1)
return [...counts.entries()].map(([name, n]) => (n > 1 ? `${n}x ${name}` : name))
}
const UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }
export const hasUnit = unitType => !!UNIT_LABELS[unitType]
export function formatQty(quantity, unitType) {
const label = UNIT_LABELS[unitType]
if (!label) return String(quantity)
if (unitType === 'kg' || unitType === 'liter') return `${Number(quantity).toFixed(1)}${label}`
return `${quantity}${label}`
}
/** Item totals across the visible orders (to do / in progress only): the same product with
* the same changes and note counts together. Most first. */
export function buildItemGroups(orders) {
const map = new Map()
for (const order of orders) {
for (const item of order.items) {
if (['done', 'served', 'cancelled', 'declined'].includes(item.kds_status)) continue
if (item.status === 'cancelled') continue
const notes = (item.notes ?? '').trim()
const key = [item.product_name, [...(item.removed ?? [])].sort().join('|'), [...(item.extras ?? [])].sort().join('|'),
[...(item.prefs ?? [])].sort().join('|'), notes].join('\u0000')
if (!map.has(key)) {
map.set(key, { key, product_name: item.product_name, removed: item.removed ?? [], extras: item.extras ?? [],
prefs: item.prefs ?? [], notes, count: 0 })
}
map.get(key).count += item.quantity ?? 1
}
}
return [...map.values()].sort((a, b) => b.count - a.count)
}
/** What a tap on an item does: to do → (in progress →) done → to do. */
export function nextItemStatus(status, tripleState) {
const cycle = tripleState
? { pending: 'preparing', preparing: 'done', done: 'pending' }
: { pending: 'done', preparing: 'done', done: 'pending' }
return cycle[status] ?? 'done'
}
/** The order's status from its items (mirrors the backend's _sync_order_kds_status). */
export function orderStatusFromItems(items, fallback) {
const statuses = new Set(items.filter(it => it.status !== 'cancelled').map(it => it.kds_status))
if (statuses.size === 0) return fallback
const only = (...vals) => [...statuses].every(s => vals.includes(s))
if (only('served')) return 'served'
if (only('done', 'served')) return 'done'
if (statuses.has('preparing') || statuses.has('done')) return 'preparing'
return 'pending'
}
/** An order set to a status; pending/preparing/done also set every open item. */
export function withOrderStatus(order, status) {
const cascade = ['pending', 'preparing', 'done'].includes(status)
const items = cascade
? order.items.map(it => (it.status !== 'cancelled' && it.kds_status !== 'served' ? { ...it, kds_status: status } : it))
: order.items
return { ...order, kds_status: status, items }
}
export function withItemStatus(order, itemId, status) {
const items = order.items.map(it => (it.id === itemId ? { ...it, kds_status: status } : it))
return { ...order, items, kds_status: orderStatusFromItems(items, order.kds_status) }
}
/** After an item is done: tell the waiters the whole order is done, or how many items are. */
export function readyNotice(order, itemId, settings) {
const items = order.items.map(it => (it.id === itemId ? { ...it, kds_status: 'done' } : it))
const active = items.filter(it => it.status !== 'cancelled' && it.kds_status !== 'served')
const done = active.filter(it => it.kds_status === 'done').length
if (done === active.length) return settings.notifyOrderComplete ? { kind: 'order' } : null
return settings.notifyItemComplete ? { kind: 'items', ready_count: done, total_count: active.length } : null
}
+145
View File
@@ -0,0 +1,145 @@
// The kitchen board's layout engine (ported from the manager's KdsPage.jsx, plan step 3.2b).
// Pure: unit-tested in Node (tests/kds.test.mjs).
//
// THE RULE: no vertical scrolling. Every card must fit within maxH (the available board
// height). Cards widen into extra columns until they fit. If even MAX_UNITS columns aren't
// enough, the last column overflows: the only acceptable compromise, and only with extremely
// tall items. Cards are absolutely positioned; their height is set from the layout.
export const COL_GAP = 14
export const CARD_GAP_Y = 14
export const BOARD_PAD = 14
export const BLOCK_GAP = 4 // vertical gap between item blocks
export const BODY_PAD_T = 8
export const BODY_PAD_B = 10 // a bit extra so the last item clears the footer
export const BODY_PAD_H = 10
export const MAX_UNITS = 3
// Base chrome heights at font scale 1; cardChrome() scales them so the layout stays exact
// at any text size.
export const CARD_HEAD_H_BASE = 46
export const CARD_SUB_H_BASE = 28
export const CARD_FOOT_H_BASE = 32
export const CARD_NOTE_H_BASE = 35 // spacer (6) + icon line (≈20) + bottom pad (8) + border (1)
export const COURSE_HEADER_H_BASE = 18
export const BATCH_DIVIDER_H_BASE = 22
/** Fixed rows of a card (header, subheader, waiter footer, order note) + body padding. */
export function cardChrome(fs, hasWaiter, hasNote) {
const head = Math.round(CARD_HEAD_H_BASE * fs)
const sub = Math.round(CARD_SUB_H_BASE * fs)
const foot = hasWaiter ? Math.round(CARD_FOOT_H_BASE * fs) : 0
const note = hasNote ? Math.round(CARD_NOTE_H_BASE * fs) : 0
return head + sub + foot + note + BODY_PAD_T + BODY_PAD_B
}
export function colHeight(col, blocks, gap) {
if (!col.length) return 0
let h = 0
for (const idx of col) h += blocks[idx]
return h + (col.length - 1) * gap
}
/** Items into columns of at most bodyH each (block indexes per column). */
export function distribute(blocks, gap, bodyH) {
if (!blocks.length) return [[]]
const cols = []
let cur = [], curH = 0
for (let i = 0; i < blocks.length; i++) {
const h = blocks[i]
const tentative = cur.length ? curH + gap + h : h
if (cur.length && tentative > bodyH) {
cols.push(cur); cur = [i]; curH = h
} else {
cur.push(i); curH = tentative
}
}
if (cur.length) cols.push(cur)
return cols
}
function foldInto(cols, units) {
if (cols.length <= units) return cols
const head = cols.slice(0, units - 1)
const tail = []
for (let i = units - 1; i < cols.length; i++) tail.push(...cols[i])
return [...head, tail]
}
/** A card's size: more columns (units) until it fits in maxH. Each attempt divides the body
* height by the number of columns, so more columns = shorter columns = a shorter card. */
export function sizeCard({ blocks, blockGap, chrome, maxH, base, maxUnits = MAX_UNITS }) {
const availBodyH = Math.max(40, maxH - chrome)
for (let units = 1; units <= maxUnits; units++) {
const cols = foldInto(distribute(blocks, blockGap, availBodyH / units), units)
const actualUnits = cols.length
let maxColH = 0
for (const c of cols) maxColH = Math.max(maxColH, colHeight(c, blocks, blockGap))
const cardH = chrome + maxColH
const cardW = actualUnits * base + (actualUnits - 1) * COL_GAP
if (cardH <= maxH + 0.5) return { units: actualUnits, cols, cardW, cardH }
}
// Extreme content: maxUnits wide, height capped (content clipped only as a last resort)
const cols = foldInto(distribute(blocks, blockGap, availBodyH / maxUnits), maxUnits)
return { units: maxUnits, cols, cardW: maxUnits * base + (maxUnits - 1) * COL_GAP, cardH: maxH }
}
/** Skyline packing: cards stack in a column until the next would exceed maxH, then a new
* column starts to the right. Oldest orders are leftmost. */
export function packBoard(cards, colW, maxH) {
const tracks = [] // tracks[i] = current bottom y of track column i
const positions = {}
const trackW = colW + COL_GAP
const topOf = (s, u) => {
let y = 0
for (let k = 0; k < u; k++) y = Math.max(y, tracks[s + k] || 0)
return y
}
for (const card of cards) {
const u = card.units
let placed = null
for (let s = 0; s + u <= tracks.length; s++) {
const y = topOf(s, u)
if (y + card.cardH <= maxH + 0.5) { placed = { s, y }; break }
}
if (!placed) placed = { s: tracks.length, y: 0 }
const { s, y } = placed
const bottom = y + card.cardH + CARD_GAP_Y
for (let k = 0; k < u; k++) tracks[s + k] = bottom
positions[card.id] = { x: s * trackW, y }
}
let totalW = 0
for (const card of cards) {
const p = positions[card.id]
if (p) totalW = Math.max(totalW, p.x + card.cardW)
}
return { positions, totalW }
}
/** Every visible card's place on the board: { map: {id: {cols, x, y, w, h}}, totalW }.
* measured[id].blocks = item heights from the measure layer (an estimate until then);
* course headers and batch dividers add rows. */
export function layoutBoard({ orders, measured, boardH, colW, fontScale, groupByCourse, courses, batchMode }) {
if (!orders.length || !boardH) return { map: {}, totalW: BOARD_PAD * 2 }
const maxH = boardH - BOARD_PAD * 2
const sized = orders.map(o => {
const chrome = cardChrome(fontScale, o.waiters?.length > 0, !!o.notes)
const m = measured[o.id]
let blocks = m ? m.blocks : o.items.map(() => Math.round(28 * fontScale))
if (groupByCourse && courses?.length > 0 && o.items?.length > 0) {
const groups = new Set(o.items.map(it => (it.course_id != null ? String(it.course_id) : '__none__')))
blocks = [...Array(groups.size).fill(Math.round(COURSE_HEADER_H_BASE * fontScale)), ...blocks]
}
if (batchMode === 'grouped' && o._batches?.length > 1) {
blocks = [...Array(o._batches.length).fill(Math.round(BATCH_DIVIDER_H_BASE * fontScale)), ...blocks]
}
return { id: o.id, ...sizeCard({ blocks, blockGap: BLOCK_GAP, chrome, maxH, base: colW }) }
})
const { positions, totalW } = packBoard(sized, colW, maxH)
const map = {}
for (const s of sized) {
const p = positions[s.id]
if (p) map[s.id] = { cols: s.cols, x: p.x + BOARD_PAD, y: p.y + BOARD_PAD, w: s.cardW, h: s.cardH }
}
return { map, totalW: totalW + BOARD_PAD * 2 }
}
+52
View File
@@ -0,0 +1,52 @@
// The kitchen screen's settings (plan steps 3.2a, 3.2b): device config (GET /api/devices/me →
// config, the same as GET /api/kds/context → settings; modules/kds/manifest.py) → what the
// board uses. Pure.
export const FONT_SCALE_MIN = 60
export const FONT_SCALE_MAX = 200
export const FONT_SCALE_STEP = 10
export const DEFAULT_CONFIG = {
prep_zone_id: null, card_width: 272, font_scale: 100, font_weight: 600, batch_mode: 'merged',
group_items: 'off', group_by_course: false, combine_modifiers: false, categories_as_filters: true,
age_warning_minutes: 5, age_late_minutes: 10, age_flash_minutes: 15, flash_late: true,
colour_fresh: '#34b56a', colour_warning: '#f0a52a', colour_late: '#e8513f', colour_done: '#3d4757',
triple_state: false, sound: true, notify_order_complete: false, notify_item_complete: false,
refresh_seconds: 30, auto_sign_out_minutes: 0,
}
/** Device config → board settings. `fontScale` (percent) overrides font_scale for this
* session (the top bar's zoom buttons). */
export function boardSettings(config, fontScale = null) {
const c = { ...DEFAULT_CONFIG, ...(config || {}) }
return {
zoneId: c.prep_zone_id,
colW: c.card_width,
fontScale: (fontScale ?? c.font_scale) / 100,
fontWeight: c.font_weight,
batchMode: c.batch_mode,
groupItems: c.group_items,
groupByCourse: c.group_by_course,
combineModifiers: c.combine_modifiers,
categoriesAsFilters: c.categories_as_filters,
thresholds: { warning: c.age_warning_minutes, late: c.age_late_minutes, flash: c.age_flash_minutes },
flashLate: c.flash_late,
colours: { fresh: c.colour_fresh, warning: c.colour_warning, late: c.colour_late, done: c.colour_done },
tripleState: c.triple_state,
sound: c.sound,
notifyOrderComplete: c.notify_order_complete,
notifyItemComplete: c.notify_item_complete,
refreshSeconds: c.refresh_seconds,
}
}
/** The zoom buttons: one step, kept within the allowed range. */
export function zoomStep(percent, dir) {
return Math.min(FONT_SCALE_MAX, Math.max(FONT_SCALE_MIN, percent + dir * FONT_SCALE_STEP))
}
/** How the screen signs its calls to waiters (the backend does the same, routers/kds.py). */
export function senderName(context) {
const z = context?.zone
return (z && (z.notification_name || z.name)) || context?.device?.name || ''
}
+50
View File
@@ -0,0 +1,50 @@
// The kitchen board's palette (ported from the manager's KdsPage.jsx, plan step 3.2b). The
// board is always dark, whatever the terminal's theme: these values are what cooks are used
// to, so they stay as they were (the age colours themselves are device settings).
export const KDS = {
bg: '#1d232b',
rail: '#161b21',
railLine: '#2b333d',
topbar: '#20272f',
tab: '#2b333d',
tabInk: '#aab4c0',
tabActiveBg: '#f3f6f9',
tabActiveInk: '#1d232b',
cardFoot: '#eef1f5',
cardFootInk: '#41474f',
ink: '#1f242b',
qtyBg: '#f0f2f5',
qtyInk: '#2b3038',
line: '#e8ebef',
doneInk: '#aeb4bc',
green: '#34b56a',
greenD: '#1e8048',
amber: '#f0a52a',
amberD: '#b87310',
red: '#e8513f',
redD: '#a02d1e',
futureHead: '#4a5568',
futureSubBg: '#374151',
doneSub: '#2a3140',
accent: '#2f7ff0',
railW: 104,
topbarH: 54,
glowFuture: '#6dd08a',
glowPending: '#f0a52a',
glowPreparing: '#2f7ff0',
glowDone: '#e7ecf2',
// dialogs
panel: '#1a2029',
panelLine: '#2c3744',
panelLine2: '#252e38',
panelInk: '#e7ecf2',
panelInk2: '#6b7a8d',
field: '#1e2832',
}
export const secondaryButton = { flex: 1, height: 48, borderRadius: 11, background: KDS.panelLine2, color: '#aab8c8', fontSize: 15, fontWeight: 600, border: 'none', cursor: 'pointer', fontFamily: 'inherit' }
export const KEYFRAMES = `
@keyframes kds-redflash { 0%,100% { background: #e8513f; } 50% { background: #0a0c0f; } }
.kds-flash { animation: kds-redflash 1.4s ease-in-out infinite; }
`
+53
View File
@@ -0,0 +1,53 @@
// The kitchen screen's data (plan step 3.2b): its open orders (GET /api/kds/orders; the
// backend gives this screen its own prep zone, 3.2a) and its context (GET /api/kds/context:
// zone, prep zones, courses). Kept fresh by the live connection: an order or KDS event →
// reload (coalesced); every reconnect (`ready`) → reload. Polling (the screen's "check for
// orders every N seconds") runs only while the live connection is down.
import { useCallback, useEffect, useRef, useState } from 'react'
import client from '../../api/client'
import { useDevice, useLiveEvent, useLiveEvents } from '../../device/context'
export const ORDER_EVENTS = ['kds_order_updated', 'kds_item_updated', 'order_updated', 'order_paid', 'order_closed', 'products_changed']
const COALESCE_MS = 150
const quiet = { xenia: { noOverride: true } }
export default function useKdsData({ refreshSeconds, zoneId }) {
const { liveUp } = useDevice()
const [orders, setOrders] = useState(null) // null until the first answer
const [context, setContext] = useState(null)
const seq = useRef(0)
const timer = useRef(null)
const loadOrders = useCallback(async () => {
const mine = ++seq.current
try {
const { data } = await client.get('/api/kds/orders', quiet)
if (mine === seq.current) setOrders(data.orders) // an older answer never overwrites a newer one
} catch { /* offline banner / sign-out are handled by the shell */ }
}, [])
const loadContext = useCallback(async () => {
try { setContext((await client.get('/api/kds/context', quiet)).data) } catch { /* next event or poll */ }
}, [])
const reload = useCallback(() => {
if (timer.current) return
timer.current = setTimeout(() => { timer.current = null; loadOrders() }, COALESCE_MS)
}, [loadOrders])
useEffect(() => { loadOrders(); loadContext() }, [loadOrders, loadContext, zoneId])
useEffect(() => () => { if (timer.current) clearTimeout(timer.current) }, [])
useLiveEvent('ready', () => { loadOrders(); loadContext() })
useLiveEvent('products_changed', loadContext)
useLiveEvents(ORDER_EVENTS, reload)
// fallback: poll only while the live connection is down
useEffect(() => {
if (liveUp) return undefined
const id = setInterval(() => { loadOrders(); loadContext() }, Math.max(5, refreshSeconds) * 1000)
return () => clearInterval(id)
}, [liveUp, refreshSeconds, loadOrders, loadContext])
return { orders, setOrders, context, reload: loadOrders }
}
+8 -5
View File
@@ -10,7 +10,8 @@
// - Live: one connection per device + session, credentials in the first frame (3.1a):
// device.updated → re-read /me (app moved → sign out), device.revoked → forget,
// session.ended → sign out; `ready` (every reconnect) → re-read /me. Apps listen with
// useLiveEvent(type, fn).
// useLiveEvent(type, fn). `liveUp`: the connection is open (apps poll only while it isn't,
// 3.2b).
// - Offline: any request without an answer sets `offline` (banner); any answer clears it.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createLiveClient, wsUrlFor } from '@xenia/api'
@@ -32,6 +33,7 @@ export default function DeviceProvider({ children }) {
const [meError, setMeError] = useState(null)
const [offline, setOffline] = useState(false)
const [notice, setNotice] = useState(null) // e.g. 'removed' on the pairing screen
const [liveUp, setLiveUp] = useState(false)
const listeners = useRef(new Map()) // live event type -> Set(fn)
const liveRef = useRef(null)
@@ -94,12 +96,13 @@ export default function DeviceProvider({ children }) {
credentials: () => ({ device: deviceStore.deviceToken(), token: deviceStore.sessionToken() }),
cursor: { load: () => seq, save: s => { seq = s } },
onEvent: (type, data) => { act(liveAction(type, data)); emit(type, data) },
onReady: () => { setOffline(false); loadMe(); emit('ready', null) },
onReady: () => { setOffline(false); setLiveUp(true); loadMe(); emit('ready', null) },
onDisconnect: () => setLiveUp(false),
onRefused: code => act(refusedAction(code)),
})
liveRef.current = live
live.start()
return () => { live.stop(); liveRef.current = null }
return () => { live.stop(); liveRef.current = null; setLiveUp(false) }
}, [deviceToken, sessionKey, forget, dropSession, loadMe])
// Keep a long shift signed in: a fresh token for the same session every hour
@@ -121,7 +124,7 @@ export default function DeviceProvider({ children }) {
}, [])
const value = useMemo(() => ({
deviceToken, me, meError, offline, notice, sessionKey,
deviceToken, me, meError, offline, notice, sessionKey, liveUp,
session: sessionKey ? deviceStore.sessionToken() : null,
paired(token) {
deviceStore.setDeviceToken(token)
@@ -142,7 +145,7 @@ export default function DeviceProvider({ children }) {
liveRef.current?.reconnect()
},
subscribe,
}), [deviceToken, me, meError, offline, notice, sessionKey, dropSession, loadMe, subscribe])
}), [deviceToken, me, meError, offline, notice, sessionKey, liveUp, dropSession, loadMe, subscribe])
return <DeviceContext.Provider value={value}>{children}</DeviceContext.Provider>
}
+12
View File
@@ -16,3 +16,15 @@ export function useLiveEvent(type, handler) {
useEffect(() => { ref.current = handler })
useEffect(() => subscribe(type, data => ref.current(data)), [subscribe, type])
}
/** handler(type, data) for every live event of any of `types` (a fixed list). */
export function useLiveEvents(types, handler) {
const { subscribe } = useDevice()
const ref = useRef(handler)
useEffect(() => { ref.current = handler })
const key = types.join('|')
useEffect(() => {
const offs = key.split('|').map(type => subscribe(type, data => ref.current(type, data)))
return () => offs.forEach(off => off())
}, [subscribe, key])
}
+2 -2
View File
@@ -17,9 +17,9 @@ export default function AppScreen() {
const withUser = me.login_mode !== 'none'
useIdleSignOut(withUser ? me.config?.auto_sign_out_minutes : 0, signOut)
return (
<div className="min-h-screen flex flex-col" data-testid="app-screen" data-app={me.app_key}>
<div className="h-screen flex flex-col" data-testid="app-screen" data-app={me.app_key}>
{withUser && <TerminalBar onSignOut={signOut} />}
<div className="flex-1 min-h-0"><AppHost appKey={me.app_key} /></div>
<div className="flex-1 min-h-0 relative overflow-auto"><AppHost appKey={me.app_key} /></div>
</div>
)
}