// 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 (@xenia/ui). // Look: the board design language of @xenia/ui (--x-board-* tokens, ./theme.js); the app runs // in the dark theme (apps/registry.js), so the shared dialogs and toasts match the board. // 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 { useAccess, useCan } from '@xenia/access' import { useLanguage, useTranslation } from '@xenia/i18n' import { useToast } from '@xenia/ui' import client from '../../api/client' import { useDevice } from '../../device/context' import { chime, soundUnlocked, unlockSound } from './chime' import { CallWaiterDialog, DeclineDialog } 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, claimState, claimTargets, nextItemStatus, readyNotice, tabCounts, visibleOrders, withItemStatus, withOrderStatus, } from './logic/board' import { layoutBoard } from './logic/layout' import { boardSettings, senderName, zoomStep } from './logic/settings' import { KDS, KEYFRAMES, alpha } from './theme' import useKdsData from './useKdsData' const HISTORY = 10 const TOAST_MS = 2200 export default function KdsApp() { const { t } = useTranslation('terminal') const { language } = useLanguage() const { me } = useDevice() const { user } = useAccess() const canClaim = useCan('kds.bump') 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 [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 ui = useToast() const toast = useCallback((msg, tone = 'neutral') => ui.show({ title: msg, tone, duration: TOAST_MS }), [ui]) // 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'), 'danger')) }, [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'), 'danger') } }, [reload, t, toast]) // "I'm on it" / let go, for every open item of the card nobody has (or that I hold) const claim = useCallback(async (orderId, action, items) => { const targets = claimTargets(items, user?.id, action) const results = await Promise.allSettled(targets.map(it => (action === 'take' ? client.post(`/api/kds/orders/${orderId}/items/${it.id}/claim`) : client.delete(`/api/kds/orders/${orderId}/items/${it.id}/claim`)))) const taken = results.find(r => r.status === 'rejected' && r.reason?.xenia?.code === 'kds.item_claimed') if (taken) toast(t('kds.claim.taken', { name: taken.reason.xenia.params?.name ?? '' }), 'warning') else if (results.some(r => r.status === 'rejected')) toast(t('kds.toast.sendFailed'), 'danger') else toast(action === 'take' ? t('kds.claim.taken_by_me') : t('kds.claim.released')) setFocusId(null) reload() }, [user?.id, 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'), 'danger') } }, [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 (
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')} />
{ 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)} />
{summary === 'left_sidebar' && (
)}
setFocusId(null)} style={{ position: 'absolute', inset: 0, overflowX: 'auto', overflowY: 'hidden' }}>
{loaded === null && (
{t('kds.loading')}
)} {loaded !== null && visible.length === 0 && (
e.stopPropagation()} style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 14, color: KDS.ink4 }}>
{t('kds.empty')}
)} {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 ( 1} courses={courses} onFocus={id => setFocusId(id === realId ? order.id : id)} onStatus={setOrderStatus} onBumpItem={bumpItem} onPrint={print} onCallWaiter={callWaiter} claimState={canClaim ? claimState(order.items, user?.id) : 'none'} onClaim={(orderId, action) => claim(orderId, action, order.items)} onDecline={orderId => setDialog({ decline: { orderId, itemId: null } })} onItemDecline={(orderId, itemId, itemName) => setDialog({ decline: { orderId, itemId, itemName } })} /> ) })}
{summary === 'floating' && (
)} {summary === 'topbar_button' && showSummary && ( setShowSummary(false)} fontScale={fs} fontWeight={settings.fontWeight} /> )}
{summary === 'right_sidebar' && (
)}
{dialog === 'settings' && ( setDialog(null)} onSaved={() => { setZoom(null); toast(t('kds.toast.settingsSaved')) }} /> )} {dialog === 'call' && ( 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'), 'danger'))} /> )} {dialog?.decline && ( confirmDecline(dialog.decline, note)} onClose={() => setDialog(null)} /> )} {!started && settings.sound && ( )}
) }