diff --git a/local_backend/tests/test_kds_device.py b/local_backend/tests/test_kds_device.py index 3ee6ecc..2605f1f 100644 --- a/local_backend/tests/test_kds_device.py +++ b/local_backend/tests/test_kds_device.py @@ -143,3 +143,13 @@ def test_settings_changed_from_the_screen(client, screen, make_user, kitchen): # without a device it's not a screen assert err(client.patch("/api/devices/me/config", headers={"Authorization": h["Authorization"]}, json={"config": {}})) in ("device.not_paired", "device.required") + + +def test_item_back_to_pending_reopens_the_order(client, screen, kitchen): + """Undo on the screen (3.2b): an item done → back to pending puts the order back too.""" + h, oid = screen["h"], kitchen["order"].id + item = client.get("/api/kds/orders", headers=h).json()["orders"][0]["items"][0]["id"] + for status, expected in (("done", "preparing"), ("pending", "pending")): # the Bar item is still to do + assert client.put(f"/api/kds/orders/{oid}/items/{item}/kds_status", headers=h, json={"status": status}).status_code == 200 + order = next(o for o in client.get("/api/kds/orders", headers=h).json()["orders"] if o["id"] == oid) + assert order["kds_status"] == expected diff --git a/packages/i18n/locales/el/terminal.json b/packages/i18n/locales/el/terminal.json index aaff36f..27f0aa4 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -33,5 +33,126 @@ "placeholder": "Αυτή η οθόνη τρέχει: {{app}}. Οι οθόνες της ετοιμάζονται.", "unknownTitle": "Άγνωστη εφαρμογή", "unknown": "Αυτή η οθόνη έχει οριστεί να τρέχει «{{app}}», που αυτό το τερματικό δεν έχει ακόμη. Ενημερώστε τον διακομιστή του καταστήματος." + }, + "kds": { + "loading": "Φόρτωση…", + "empty": "Δεν υπάρχουν παραγγελίες για τα επιλεγμένα φίλτρα", + "cancel": "Ακύρωση", + "close": "Κλείσιμο", + "age": { + "new": "νέα", + "minutes": "{{m}}m", + "hours": "{{h}}h {{m}}m", + "ago": "πριν {{time}}" + }, + "card": { + "items_one": "{{count}} είδος", + "items_other": "{{count}} είδη", + "status": { + "pending": "Αναμονή", + "preparing": "▶ Προετοιμασία", + "done": "✓ Έτοιμη" + }, + "batch": "Παρτίδα {{n}}", + "noCourse": "Χωρίς πιάτο" + }, + "channel": { + "here": "Εδώ", + "takeaway": "Takeaway", + "delivery": "Delivery" + }, + "tabs": { + "all": "Όλα" + }, + "actions": { + "prepare": "Σε εκτέλεση", + "complete": "Ολοκλήρωση", + "reset": "Επαναφορά", + "print": "Εκτύπωση", + "callWaiter": "Κάλεσε σερβιτόρο" + }, + "quick": { + "prep": "Εκτέλεση", + "ready": "Έτοιμη", + "undo": "Αναίρεση", + "decline": "Απόρριψη", + "close": "Κλείσιμο" + }, + "decline": { + "order": "Απόρριψη παραγγελίας", + "item": "Απόρριψη αντικειμένου", + "reasons": { + "out_of_stock": "Εξαντλήθηκε", + "too_many_orders": "Υπερβολικά πολλές παραγγελίες", + "other": "Άλλος λόγος" + }, + "notePlaceholder": "Προσθέστε σημείωση (προαιρετικό)…" + }, + "summary": { + "title": "Σύνοψη αντικειμένων", + "subtitle": "Αναμονή + προετοιμασία · {{count}} είδη", + "empty": "Κανένα αντικείμενο", + "button": "Σύνοψη" + }, + "rail": { + "future": "Αργότερα", + "pending": "Αναμονή", + "preparing": "Εκτέλεση", + "done": "Έτοιμες", + "undo": "Αναίρεση", + "redo": "Επανάληψη", + "call": "Κλήση", + "sound": "Ήχος", + "muted": "Σίγαση", + "settings": "Ρυθμίσεις" + }, + "zoom": { + "smaller": "Μικρότερο", + "larger": "Μεγαλύτερο" + }, + "call": { + "title": "Κάλεσε σερβιτόρο", + "needsHelp": "Η {{zone}} θέλει βοήθεια", + "none": "Κανένας σερβιτόρος σε βάρδια", + "all": "Όλοι οι σερβιτόροι", + "send": "Κάλεσε", + "sendCount": "Κάλεσε ({{count}})", + "sending": "Αποστολή…" + }, + "start": { + "title": "Πατήστε για έναρξη", + "body": "Η οθόνη χρειάζεται ένα πάτημα για να μπορεί να παίζει τον ήχο των νέων παραγγελιών." + }, + "settings": { + "title": "Ρυθμίσεις οθόνης", + "save": "Αποθήκευση", + "seconds": "{{s}}δ", + "noPermission": "Μόνο ένας διαχειριστής μπορεί να αλλάξει τις ρυθμίσεις αυτής της οθόνης. Ζητήστε του να συνδεθεί εδώ.", + "tabs": { + "zone": "Ζώνη", + "behaviour": "Λειτουργία", + "board": "Εμφάνιση", + "age": "Χρόνος αναμονής", + "notifications": "Ειδοποιήσεις" + } + }, + "toast": { + "newOrders_one": "{{count}} νέα παραγγελία", + "newOrders_other": "{{count}} νέες παραγγελίες", + "done": "✓ Ολοκληρώθηκε", + "preparing": "▶ Σε εκτέλεση", + "pending": "↩ Επαναφορά", + "waiterCalled": "Ειδοποίηση σερβιτόρου στάλθηκε", + "called": "Ειδοποίηση στάλθηκε", + "sendFailed": "Αποτυχία αποστολής", + "itemDeclined": "Αντικείμενο απορρίφθηκε", + "orderDeclined": "Παραγγελία απορρίφθηκε", + "declineFailed": "Σφάλμα απόρριψης", + "printSent": "Εκτύπωση εστάλη", + "printFailed": "Σφάλμα εκτύπωσης", + "undone": "Αναίρεση", + "redone": "Επανάληψη", + "settingsSaved": "Οι ρυθμίσεις αποθηκεύτηκαν" + } } } diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index 8521ed0..2c280fe 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -33,5 +33,126 @@ "placeholder": "This screen runs {{app}}. Its screens are being built.", "unknownTitle": "Unknown app", "unknown": "This screen is set to run \"{{app}}\", which this terminal doesn't have yet. Update the venue server." + }, + "kds": { + "loading": "Loading…", + "empty": "No orders for the selected filters", + "cancel": "Cancel", + "close": "Close", + "age": { + "new": "new", + "minutes": "{{m}}m", + "hours": "{{h}}h {{m}}m", + "ago": "{{time}} ago" + }, + "card": { + "items_one": "{{count}} item", + "items_other": "{{count}} items", + "status": { + "pending": "To do", + "preparing": "▶ Prep", + "done": "✓ Done" + }, + "batch": "Round {{n}}", + "noCourse": "No course" + }, + "channel": { + "here": "Here", + "takeaway": "Takeaway", + "delivery": "Delivery" + }, + "tabs": { + "all": "All" + }, + "actions": { + "prepare": "In progress", + "complete": "Done", + "reset": "Back", + "print": "Print", + "callWaiter": "Call waiter" + }, + "quick": { + "prep": "Prep", + "ready": "Ready", + "undo": "Undo", + "decline": "Decline", + "close": "Close" + }, + "decline": { + "order": "Decline order", + "item": "Decline item", + "reasons": { + "out_of_stock": "Out of stock", + "too_many_orders": "Too many orders", + "other": "Other reason" + }, + "notePlaceholder": "Add a note (optional)…" + }, + "summary": { + "title": "Item totals", + "subtitle": "To do + in progress · {{count}} kinds", + "empty": "No items", + "button": "Totals" + }, + "rail": { + "future": "Later", + "pending": "To do", + "preparing": "Prep", + "done": "Done", + "undo": "Undo", + "redo": "Redo", + "call": "Call", + "sound": "Sound", + "muted": "Muted", + "settings": "Settings" + }, + "zoom": { + "smaller": "Smaller text", + "larger": "Larger text" + }, + "call": { + "title": "Call a waiter", + "needsHelp": "{{zone}} needs help", + "none": "No waiter is on shift", + "all": "All waiters", + "send": "Call", + "sendCount": "Call ({{count}})", + "sending": "Sending…" + }, + "start": { + "title": "Tap to start", + "body": "The screen needs one tap before it can play the sound for new orders." + }, + "settings": { + "title": "Screen settings", + "save": "Save", + "seconds": "{{s}}s", + "noPermission": "Only a manager can change this screen's settings. Ask one to sign in here.", + "tabs": { + "zone": "Prep zone", + "behaviour": "Behaviour", + "board": "Board", + "age": "Waiting time", + "notifications": "Notifications" + } + }, + "toast": { + "newOrders_one": "{{count}} new order", + "newOrders_other": "{{count}} new orders", + "done": "✓ Done", + "preparing": "▶ In progress", + "pending": "↩ Back to to do", + "waiterCalled": "Waiter notified", + "called": "Sent", + "sendFailed": "Couldn't send it", + "itemDeclined": "Item declined", + "orderDeclined": "Order declined", + "declineFailed": "Couldn't decline it", + "printSent": "Sent to the printer", + "printFailed": "Couldn't print", + "undone": "Undone", + "redone": "Redone", + "settingsSaved": "Settings saved" + } } } diff --git a/terminal/eslint.config.js b/terminal/eslint.config.js index 8f4d803..3c0e32c 100644 --- a/terminal/eslint.config.js +++ b/terminal/eslint.config.js @@ -25,7 +25,7 @@ export default defineConfig([ }, }, rules: { - 'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }], + 'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]', argsIgnorePattern: '^[A-Z_]' }], // components passed as props (Icon) // Loading data in an effect (`useEffect(() => { load() }, [load])`, setState after the // await) is flagged too; it's what the screens do, so a warning, as in the manager. 'react-hooks/set-state-in-effect': 'warn', diff --git a/terminal/src/apps/kds/KdsApp.jsx b/terminal/src/apps/kds/KdsApp.jsx index 1342955..9fbaec3 100644 --- a/terminal/src/apps/kds/KdsApp.jsx +++ b/terminal/src/apps/kds/KdsApp.jsx @@ -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 + 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 ( +
+ + 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: '#5e6772' }}> + +
{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} + 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')))} /> + )} + {dialog?.decline && ( + confirmDecline(dialog.decline, note)} onClose={() => setDialog(null)} /> + )} + + {!started && settings.sound && ( + + )} + + +
+ ) } diff --git a/terminal/src/apps/kds/chime.js b/terminal/src/apps/kds/chime.js new file mode 100644 index 0000000..aa1344e --- /dev/null +++ b/terminal/src/apps/kds/chime.js @@ -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 */ } +} diff --git a/terminal/src/apps/kds/components/ActionBars.jsx b/terminal/src/apps/kds/components/ActionBars.jsx new file mode 100644 index 0000000..e555761 --- /dev/null +++ b/terminal/src/apps/kds/components/ActionBars.jsx @@ -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 ( +
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} +
+ ) +} + +function BarButton({ bg, label, title, onClick, fs, children, testId }) { + return ( + + ) +} + +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 ( + <> + + onStatus(order.id, isPreparing ? 'pending' : 'preparing')}> + {isPreparing ? : } + + onStatus(order.id, isDone ? 'pending' : 'done')}> + {isDone ? : } + + onPrint(order.id)}> + + + + {hasWaiter && ( + + )} + + ) +} + +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 ( + + { onStatus(order.id, isPreparing ? 'pending' : 'preparing'); onDismiss() }}> + {isPreparing ? : } + + { onStatus(order.id, isDone ? 'pending' : 'done'); onDismiss() }}> + {isDone ? : } + + { onDecline(order.id); onDismiss() }}> + + + + + + + ) +} diff --git a/terminal/src/apps/kds/components/Dialogs.jsx b/terminal/src/apps/kds/components/Dialogs.jsx new file mode 100644 index 0000000..d5232c1 --- /dev/null +++ b/terminal/src/apps/kds/components/Dialogs.jsx @@ -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 ( +
+
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} +
+
+ ) +} + +export function CloseButton({ onClick, label }) { + return ( + + ) +} + +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 ( + +
+
{title}
+ {isItem && itemName &&
{itemName}
} +
+
+ {REASONS.map(r => { + const on = reason === r + return ( + + ) + })} + {reason === 'other' && ( + 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', + }} /> + )} +
+
+ + +
+
+ ) +} + +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 ( + +
+
+
{t('kds.call.title')}
+ {zoneName &&
{t('kds.call.needsHelp', { zone: zoneName })}
} +
+ +
+
+ {waiters === null &&
{t('kds.loading')}
} + {waiters?.length === 0 &&
{t('kds.call.none')}
} + {waiters?.length > 0 && ( + <> + + {waiters.map(w => { + const on = selected.has(w.id) + const name = w.nickname || w.username + return ( + + ) + })} + + )} +
+
+ + +
+
+ ) +} + +export function Toasts({ toasts }) { + return ( +
+ {toasts.map(x => ( +
+ {x.msg} +
+ ))} +
+ ) +} diff --git a/terminal/src/apps/kds/components/ItemBlock.jsx b/terminal/src/apps/kds/components/ItemBlock.jsx new file mode 100644 index 0000000..bd8cede --- /dev/null +++ b/terminal/src/apps/kds/components/ItemBlock.jsx @@ -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 ( +
+ {/* one line tall, so the icon sits on the first line when the text wraps */} + + + + {text} +
+ ) +} + +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 ( +
{ 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' }} + > +
+ + {formatQty(item.quantity, item.unit_type)} + + + {item.product_name} + + {focused && ( + + )} +
+ {hasMods ? ( +
+ {combineModifiers ? ( + <> + {removed.length > 0 && } + {extras.length > 0 && } + {prefs.length > 0 && } + + ) : ( + <> + {removed.map((r, i) => )} + {extras.map((x, i) => )} + {prefs.map((p, i) => )} + + )} + {item.notes && } +
+ ) : null} +
+ ) +} diff --git a/terminal/src/apps/kds/components/MeasureLayer.jsx b/terminal/src/apps/kds/components/MeasureLayer.jsx new file mode 100644 index 0000000..bc06dab --- /dev/null +++ b/terminal/src/apps/kds/components/MeasureLayer.jsx @@ -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 ( + + ) +} diff --git a/terminal/src/apps/kds/components/OrderCard.jsx b/terminal/src/apps/kds/components/OrderCard.jsx new file mode 100644 index 0000000..370d96f --- /dev/null +++ b/terminal/src/apps/kds/components/OrderCard.jsx @@ -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 ( + + + {type === 'here' && tableName ? tableName : t(`kds.channel.${type}`)} + + ) +} + +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 => ( + { resetIdle(); onBumpItem(order.id, x.id) }} + onDecline={focused ? x => { resetIdle(); onItemDecline(order.id, x.id, x.product_name) } : null} /> + ) + const column = (key, children) => ( +
{children}
+ ) + 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 ( + +
+
+ {t('kds.card.batch', { n: bi + 1 })} + + {t('kds.age.minutes', { m: Math.max(0, minutesSince(batch.opened_at, now)) })} + +
+
+ {items.map(item)} + + ) + })) + } 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) => ( +
+
+ {g.course ? g.course.name : t('kds.card.noCourse')} +
+ {g.items.map(item)} +
+ ))) + } + return column(ci, colItems.map(item)) + }) + } + + return ( +
{ 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', + }} + > +
+
+ + {ageText} + + + {t('kds.card.items', { count: itemCount })} + +
+
+
+ +
+ #{order.id} + + {t(`kds.card.status.${order.kds_status === 'done' || order.kds_status === 'preparing' ? order.kds_status : 'pending'}`)} + +
+ +
+ {body} +
+ + {order.notes && ( +
+
+
+ + {order.notes} +
+
+ )} + + {waiter && ( +
+ + {waiter} +
+ )} + + {quick && !focused && ( + setQuick(false)} fs={fs} /> + )} + {focused && ( + + )} +
+ ) +} diff --git a/terminal/src/apps/kds/components/Rails.jsx b/terminal/src/apps/kds/components/Rails.jsx new file mode 100644 index 0000000..e8829cf --- /dev/null +++ b/terminal/src/apps/kds/components/Rails.jsx @@ -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 ( + + ) +} + +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 => {text} + const badgeH = Math.round(22 * fs) + const group = { display: 'flex', flexDirection: 'column', gap: 2, padding: `2px ${Math.round(8 * fs)}px` } + return ( + + ) +} + +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 ( +
+
+ {TABS.map(key => { + const active = tab === key + return ( + + ) + })} +
+
+ {showSummaryButton && ( + + )} +
+
+ {formatDate(now, 'dateLong')} + {formatTime(now)} +
+
+
+ + + {zoomPercent}% + + +
+
+ ) +} diff --git a/terminal/src/apps/kds/components/SettingsPanel.jsx b/terminal/src/apps/kds/components/SettingsPanel.jsx new file mode 100644 index 0000000..4d3de8d --- /dev/null +++ b/terminal/src/apps/kds/components/SettingsPanel.jsx @@ -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 ( +
+ + {display(cur)} + +
+ ) +} + +function Toggle({ on, onToggle, testId }) { + return ( + + ) +} + +function Swatches({ value, onChange, testId }) { + return ( +
+ {PRESETS.map(p => ( +
+ ) +} + +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) => ( +
+
+
{L(key)}
+ {L(key, 'hint') &&
{L(key, 'hint')}
} +
+
{control}
+
+ ) + const toggle = key => row(key, set(key, !local[key])} />) + const select = (key, options) => row(key, ( + + )) + const minutes = (key, min, max) => row(key, ( + 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 ( + + ) + } + + const content = { + zone: ( +
+
{L('prep_zone_id', 'hint')}
+
+ {zoneButton(null, t('modules:kds.config.prep_zone_id.none'))} + {zones.map(z => zoneButton(z.id, z.name))} +
+
+ ), + behaviour: ( +
+ {row('refresh_seconds', 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)} +
+ ), + board: ( +
+ {row('card_width', `${v}px`} onChange={v => set('card_width', v)} />)} + {row('font_scale', `${v}%`} onChange={v => set('font_scale', v)} />)} + {select('font_weight', WEIGHTS)} + {toggle('flash_late')} + {toggle('combine_modifiers')} +
+ ), + age: ( +
+ {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, set(k, v)} />))} +
+ ), + notifications: ( +
+ {toggle('sound')} + {toggle('notify_order_complete')} + {toggle('notify_item_complete')} +
+ ), + } + + 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 ( + +
+

{t('kds.settings.title')}

+ +
+
+ {TABS.map(k => ( + + ))} +
+
{content[tab]}
+ {!canEdit && ( +
+ {t('kds.settings.noPermission')} +
+ )} + {error &&
{error}
} +
+ + +
+
+ ) +} diff --git a/terminal/src/apps/kds/components/SummaryPanel.jsx b/terminal/src/apps/kds/components/SummaryPanel.jsx new file mode 100644 index 0000000..c973a0b --- /dev/null +++ b/terminal/src/apps/kds/components/SummaryPanel.jsx @@ -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 ( +
+ + + + {text} +
+ ) +} + +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 = ( +
+
+
{t('kds.summary.title')}
+
{t('kds.summary.subtitle', { count: groups.length })}
+
+ {mode === 'topbar_button' && ( + + )} +
+ ) + + const list = ( +
+ {groups.length === 0 ? ( +
{t('kds.summary.empty')}
+ ) : groups.map(g => ( +
+
+ + {g.count} + + {g.product_name} +
+ {(g.removed.length || g.extras.length || g.prefs.length || g.notes) ? ( +
+ {g.removed.length > 0 && } + {g.extras.length > 0 && } + {g.prefs.length > 0 && } + {g.notes && } +
+ ) : null} +
+ ))} +
+ ) + + if (mode === 'right_sidebar' || mode === 'left_sidebar') { + return ( +
+ {header}{list} +
+ ) + } + if (mode === 'floating') { + return ( +
+ {header}{list} +
+ ) + } + if (mode === 'topbar_button' && open) { + return ( +
+
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} +
+
+ ) + } + return null +} diff --git a/terminal/src/apps/kds/logic/board.js b/terminal/src/apps/kds/logic/board.js new file mode 100644 index 0000000..d4f554b --- /dev/null +++ b/terminal/src/apps/kds/logic/board.js @@ -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 "_b", _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 +} diff --git a/terminal/src/apps/kds/logic/layout.js b/terminal/src/apps/kds/logic/layout.js new file mode 100644 index 0000000..893faff --- /dev/null +++ b/terminal/src/apps/kds/logic/layout.js @@ -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 } +} diff --git a/terminal/src/apps/kds/logic/settings.js b/terminal/src/apps/kds/logic/settings.js new file mode 100644 index 0000000..8693bc3 --- /dev/null +++ b/terminal/src/apps/kds/logic/settings.js @@ -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 || '' +} diff --git a/terminal/src/apps/kds/theme.js b/terminal/src/apps/kds/theme.js new file mode 100644 index 0000000..1975191 --- /dev/null +++ b/terminal/src/apps/kds/theme.js @@ -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; } +` diff --git a/terminal/src/apps/kds/useKdsData.js b/terminal/src/apps/kds/useKdsData.js new file mode 100644 index 0000000..ea0b5e5 --- /dev/null +++ b/terminal/src/apps/kds/useKdsData.js @@ -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 } +} diff --git a/terminal/src/device/DeviceProvider.jsx b/terminal/src/device/DeviceProvider.jsx index 1ff4f88..ee50830 100644 --- a/terminal/src/device/DeviceProvider.jsx +++ b/terminal/src/device/DeviceProvider.jsx @@ -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 {children} } diff --git a/terminal/src/device/context.js b/terminal/src/device/context.js index 7c14c94..d242c6f 100644 --- a/terminal/src/device/context.js +++ b/terminal/src/device/context.js @@ -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]) +} diff --git a/terminal/src/screens/AppScreen.jsx b/terminal/src/screens/AppScreen.jsx index 60e367e..c4c2b12 100644 --- a/terminal/src/screens/AppScreen.jsx +++ b/terminal/src/screens/AppScreen.jsx @@ -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 ( -
+
{withUser && } -
+
) } diff --git a/terminal/tests/kds.test.mjs b/terminal/tests/kds.test.mjs new file mode 100644 index 0000000..0898b52 --- /dev/null +++ b/terminal/tests/kds.test.mjs @@ -0,0 +1,182 @@ +// The kitchen board's pure logic (plan step 3.2b): layout, age, buckets, rounds, totals, +// status changes and settings. +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { + ageLabel, ageOrderFor, ageState, bucketCounts, buildItemGroups, courseGroups, dedupeModifiers, formatQty, nextItemStatus, + orderStatusFromItems, readyNotice, tabCounts, visibleOrders, withBatches, withItemStatus, withOrderStatus, +} from '../src/apps/kds/logic/board.js' +import { BOARD_PAD, COL_GAP, cardChrome, distribute, layoutBoard, packBoard, sizeCard } from '../src/apps/kds/logic/layout.js' +import { DEFAULT_CONFIG, boardSettings, senderName, zoomStep } from '../src/apps/kds/logic/settings.js' + +const T0 = Date.parse('2026-11-14T12:00:00Z') +const at = min => new Date(T0 + min * 60_000).toISOString().replace('.000Z', '') // backend style: UTC, no offset +const thr = { warning: 5, late: 10, flash: 15 } +const t = (key, o = {}) => `${key}${Object.keys(o).length ? JSON.stringify(o) : ''}` + +// ── layout ────────────────────────────────────────────────────────────────── + +test('distribute: items into columns of at most the given height', () => { + assert.deepEqual(distribute([10, 10, 10], 4, 100), [[0, 1, 2]]) + assert.deepEqual(distribute([50, 50, 50], 4, 100), [[0], [1], [2]]) + assert.deepEqual(distribute([40, 40, 40], 4, 90), [[0, 1], [2]]) + assert.deepEqual(distribute([], 4, 90), [[]]) +}) + +test('sizeCard: one column when it fits, wider until it fits, capped at 3', () => { + const chrome = 100 + const one = sizeCard({ blocks: [30, 30], blockGap: 4, chrome, maxH: 400, base: 272 }) + assert.equal(one.units, 1) + assert.equal(one.cardH, 164) + assert.equal(one.cardW, 272) + const two = sizeCard({ blocks: Array(6).fill(50), blockGap: 4, chrome, maxH: 400, base: 272 }) + assert.equal(two.units, 2) + assert.ok(two.cardH <= 400) + assert.equal(two.cardW, 2 * 272 + COL_GAP) + const huge = sizeCard({ blocks: Array(40).fill(80), blockGap: 4, chrome, maxH: 400, base: 272 }) + assert.equal(huge.units, 3) + assert.equal(huge.cardH, 400) // the only case that overflows +}) + +test('packBoard: cards stack down a column, then a new column to the right', () => { + const cards = [{ id: 'a', units: 1, cardW: 272, cardH: 200 }, { id: 'b', units: 1, cardW: 272, cardH: 150 }, + { id: 'c', units: 1, cardW: 272, cardH: 200 }, { id: 'd', units: 2, cardW: 558, cardH: 100 }] + const { positions, totalW } = packBoard(cards, 272, 400) + assert.deepEqual(positions.a, { x: 0, y: 0 }) + assert.deepEqual(positions.b, { x: 0, y: 214 }) + assert.deepEqual(positions.c, { x: 286, y: 0 }) + assert.deepEqual(positions.d, { x: 572, y: 0 }) // two tracks wide: no room under a+b / c, so a new column + assert.equal(totalW, 572 + 558) +}) + +test('cardChrome scales with the text size; layoutBoard places every card', () => { + assert.equal(cardChrome(1, false, false), 46 + 28 + 18) + assert.equal(cardChrome(2, true, true), 92 + 56 + 64 + 70 + 18) + const orders = [{ id: 1, items: [{ id: 1 }, { id: 2 }], waiters: ['maria'] }, { id: 2, items: [{ id: 3 }] }] + const out = layoutBoard({ orders, measured: { 1: { blocks: [30, 40] } }, boardH: 600, colW: 272, fontScale: 1, batchMode: 'merged' }) + assert.deepEqual(Object.keys(out.map), ['1', '2']) + assert.equal(out.map[1].x, BOARD_PAD) + assert.equal(out.map[1].h, cardChrome(1, true, false) + 30 + 4 + 40) + assert.deepEqual(layoutBoard({ orders, measured: {}, boardH: 0, colW: 272, fontScale: 1 }), { map: {}, totalW: BOARD_PAD * 2 }) +}) + +// ── age ───────────────────────────────────────────────────────────────────── + +test('ageState: new → warning → late → flash; done counts since done; future counts down', () => { + const now = T0 + const o = (min, extra = {}) => ({ kds_status: 'pending', opened_at: at(-min), ...extra }) + assert.deepEqual(ageState(o(0), now, thr), { age: 'green', flash: false, minutes: 0, kind: 'new' }) + assert.equal(ageState(o(4), now, thr).age, 'green') + assert.equal(ageState(o(5), now, thr).age, 'amber') + assert.equal(ageState(o(10), now, thr).age, 'red') + assert.deepEqual(ageState(o(15), now, thr), { age: 'red', flash: true, minutes: 15, kind: 'elapsed' }) + assert.deepEqual(ageState(o(-20), now, thr), { age: 'future', flash: false, minutes: 20, kind: 'until' }) + assert.deepEqual(ageState(o(30, { kds_status: 'done', closed_at: at(-3) }), now, thr), { age: 'done', flash: false, minutes: 3, kind: 'ago' }) + // a timestamp with Z is the same moment + assert.equal(ageState({ kds_status: 'pending', opened_at: `${at(-6)}Z` }, now, thr).age, 'amber') +}) + +test('ageLabel / durationLabel', () => { + assert.equal(ageLabel({ kind: 'new', minutes: 0 }, t), 'kds.age.new') + assert.equal(ageLabel({ kind: 'elapsed', minutes: 7 }, t), 'kds.age.minutes{"m":7}') + assert.equal(ageLabel({ kind: 'elapsed', minutes: 65 }, t), 'kds.age.hours{"h":1,"m":5}') + assert.equal(ageLabel({ kind: 'ago', minutes: 3 }, t), 'kds.age.ago{"time":"kds.age.minutes{\\"m\\":3}"}') +}) + +// ── buckets, tabs, rounds ─────────────────────────────────────────────────── + +const orders = [ + { id: 1, kds_status: 'pending', order_type: 'here', opened_at: at(-10), items: [] }, + { id: 2, kds_status: 'pending', order_type: 'takeaway', opened_at: at(30), items: [] }, // scheduled + { id: 3, kds_status: 'preparing', order_type: 'here', opened_at: at(-20), items: [] }, + { id: 4, kds_status: 'done', order_type: 'delivery', opened_at: at(-40), items: [] }, +] + +test('buckets and tab counts', () => { + assert.deepEqual(bucketCounts(orders, T0), { future: 1, pending: 1, preparing: 1, done: 1 }) + assert.deepEqual(tabCounts(orders, new Set(['pending', 'preparing']), T0), { all: 2, here: 2, takeaway: 0, delivery: 0 }) +}) + +test('visibleOrders: filters, tab, oldest first, zone sorting', () => { + const v = visibleOrders(orders, { filters: new Set(['future', 'pending', 'preparing']), now: T0 }) + assert.deepEqual(v.map(o => o.id), [3, 1, 2]) + assert.deepEqual(visibleOrders(orders, { filters: new Set(['pending', 'preparing']), tab: 'here', now: T0 }).map(o => o.id), [3, 1]) + const one = [{ id: 9, kds_status: 'pending', opened_at: at(-1), order_type: 'here', + items: [{ id: 1, product_name: 'Beta', quantity: 1, added_at: at(-1) }, { id: 2, product_name: 'alpha', quantity: 3, added_at: at(-1) }] }] + assert.deepEqual(visibleOrders(one, { filters: new Set(['pending']), now: T0, sortBy: 'alpha', locale: 'en' })[0].items.map(i => i.id), [2, 1]) + assert.deepEqual(visibleOrders(one, { filters: new Set(['pending']), now: T0, sortBy: 'item_count' })[0].items.map(i => i.id), [2, 1]) +}) + +test('rounds: items more than 2 minutes apart; split = one card per round', () => { + const o = { id: 7, kds_status: 'pending', order_type: 'here', opened_at: at(-20), items: [ + { id: 1, added_at: at(-20), kds_status: 'done' }, { id: 2, added_at: at(-19), kds_status: 'done' }, { id: 3, added_at: at(-5), kds_status: 'pending' }] } + const b = withBatches(o) + assert.equal(b._batches.length, 2) + assert.deepEqual(b.items.map(i => i._batchIndex), [0, 0, 1]) + assert.equal(ageOrderFor(b).opened_at, at(-5)) // the clock runs from the round still being made + const split = visibleOrders([o], { filters: new Set(['pending']), now: T0, batchMode: 'split' }) + assert.deepEqual(split.map(x => [x.id, x._realId, x.items.length]), [['7_b0', 7, 2], ['7_b1', 7, 1]]) +}) + +test('courses: in the venue order, no course last', () => { + const items = [{ id: 1, course_id: 2 }, { id: 2, course_id: null }, { id: 3, course_id: 1 }] + const g = courseGroups(items, [{ id: 1, name: 'Starters' }, { id: 2, name: 'Mains' }]) + assert.deepEqual(g.map(x => [x.course?.name ?? null, x.items.map(i => i.id)]), [['Starters', [3]], ['Mains', [1]], [null, [2]]]) +}) + +test('item totals: same product + same changes count together; done items left out', () => { + const g = buildItemGroups([ + { items: [{ product_name: 'Souvlaki', quantity: 2, removed: ['onion'], kds_status: 'pending' }, + { product_name: 'Souvlaki', quantity: 1, removed: ['onion'], kds_status: 'preparing' }, + { product_name: 'Souvlaki', quantity: 1, kds_status: 'pending' }] }, + { items: [{ product_name: 'Souvlaki', quantity: 5, kds_status: 'done' }, { product_name: 'Fries', quantity: 1, kds_status: 'declined' }] }, + ]) + assert.deepEqual(g.map(x => [x.product_name, x.removed, x.count]), [['Souvlaki', ['onion'], 3], ['Souvlaki', [], 1]]) + assert.deepEqual(dedupeModifiers(['sauce', 'sauce', 'salt']), ['2x sauce', 'salt']) + assert.equal(formatQty(0.5, 'kg'), '0.5kg') + assert.equal(formatQty(2, 'piece'), '2') +}) + +// ── status changes ────────────────────────────────────────────────────────── + +test('a tap on an item: to do → done (→ in progress first with three steps) → to do', () => { + assert.equal(nextItemStatus('pending', false), 'done') + assert.equal(nextItemStatus('pending', true), 'preparing') + assert.equal(nextItemStatus('preparing', true), 'done') + assert.equal(nextItemStatus('done', false), 'pending') +}) + +test('order status follows its items (as the backend does)', () => { + const it = (...s) => s.map((kds_status, id) => ({ id, kds_status })) + assert.equal(orderStatusFromItems(it('done', 'served'), 'x'), 'done') + assert.equal(orderStatusFromItems(it('pending', 'done'), 'x'), 'preparing') + assert.equal(orderStatusFromItems(it('pending'), 'x'), 'pending') + assert.equal(orderStatusFromItems([], 'x'), 'x') + const o = { id: 1, kds_status: 'pending', items: it('pending', 'served').concat({ id: 9, kds_status: 'pending', status: 'cancelled' }) } + assert.deepEqual(withOrderStatus(o, 'done').items.map(i => i.kds_status), ['done', 'served', 'pending']) + assert.equal(withItemStatus(o, 0, 'done').kds_status, 'done') +}) + +test('tell the waiter: the whole order, or how many items are ready', () => { + const o = { items: [{ id: 1, kds_status: 'done' }, { id: 2, kds_status: 'pending' }, { id: 3, kds_status: 'pending' }] } + assert.deepEqual(readyNotice(o, 2, { notifyItemComplete: true }), { kind: 'items', ready_count: 2, total_count: 3 }) + assert.equal(readyNotice(o, 2, { notifyOrderComplete: true }), null) + const last = { items: [{ id: 1, kds_status: 'done' }, { id: 2, kds_status: 'pending' }] } + assert.deepEqual(readyNotice(last, 2, { notifyOrderComplete: true }), { kind: 'order' }) +}) + +// ── settings ──────────────────────────────────────────────────────────────── + +test('device config → board settings; zoom overrides the size for the session', () => { + const s = boardSettings({ ...DEFAULT_CONFIG, font_scale: 120, age_late_minutes: 12, colour_late: '#ff0000' }) + assert.equal(s.fontScale, 1.2) + assert.deepEqual(s.thresholds, { warning: 5, late: 12, flash: 15 }) + assert.equal(s.colours.late, '#ff0000') + assert.equal(boardSettings(null).colW, 272) + assert.equal(boardSettings({ font_scale: 120 }, 90).fontScale, 0.9) + assert.equal(zoomStep(100, 1), 110) + assert.equal(zoomStep(60, -1), 60) + assert.equal(zoomStep(200, 1), 200) + assert.equal(senderName({ zone: { name: 'Grill', notification_name: 'Grill station' }, device: { name: 'Screen' } }), 'Grill station') + assert.equal(senderName({ zone: null, device: { name: 'Screen' } }), 'Screen') +}) diff --git a/tests/e2e/terminal.mjs b/tests/e2e/terminal.mjs index 978283e..d006e1b 100644 --- a/tests/e2e/terminal.mjs +++ b/tests/e2e/terminal.mjs @@ -139,6 +139,84 @@ try { }) r.check('3.2a: what the old page used instead (/api/prep-zones) stays out of its scope', outside === 'device.out_of_scope', outside) + // ── 3.2b: the kitchen board on the screen ──────────────────────────────── + await page.reload() // a fresh start: the browser needs a tap before it plays sound + r.check('3.2b: "Tap to start" first (sound needs a tap)', await shown(page, 'kds-start')) + await page.getByTestId('kds-start').click() + const card = page.locator(`[data-testid="kds-card"][data-order="${opened.id}"]`) + r.check('3.2b: the board shows the order with its Grill item only', await card.waitFor({ timeout: 8000 }).then(() => true).catch(() => false) + && await card.locator('[data-item]').count() === 1 && (await card.textContent()).includes(p1.name), (await card.textContent().catch(() => '')).slice(0, 120)) + await page.screenshot({ path: path.join(OUT, 'terminal-kds-board.png') }) + + // live, without polling: count the screen's order requests while nothing else happens + let polls = 0 + const countPolls = req => { if (req.url().includes('/api/kds/orders')) polls++ } + page.on('request', countPolls) + await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { config: { prep_zone_id: grill.id, font_scale: 120, refresh_seconds: 10 } } }) + await sleep(12_000) + page.off('request', countPolls) + r.check('3.2b: no polling while the live connection is up (refresh 10 s, 12 s quiet)', polls <= 1, `${polls} requests`) // ≤1: the settings change may reload once + + // a new order arrives live, with the chime + const chimes0 = await page.evaluate(() => window.__xeniaChimes || 0) + const table2 = (await api('GET', '/api/tables/', { token: boss })).find(t => !t.open_order_id && !t.current_order_id && t.id !== table.id) + const second = await api('POST', '/api/orders/', { token: maria, body: { table_id: table2.id } }) + await api('POST', `/api/orders/${second.id}/items`, { token: maria, body: { items: [{ product_id: p1.id, quantity: 2 }] } }) + const card2 = page.locator(`[data-testid="kds-card"][data-order="${second.id}"]`) + r.check('3.2b: a new order appears by itself (live) and chimes', await card2.waitFor({ timeout: 5000 }).then(() => true).catch(() => false) + && await page.evaluate(() => window.__xeniaChimes || 0) > chimes0) + + // the zoom is the device's font_scale, changed live from the manager + r.check('3.2b: text size follows the device setting live (120%)', (await page.getByTestId('zoom-level').textContent()) === '120%') + + // tap the card, tap its item → done; the backend agrees + const kdsItem = async (orderId, itemId) => (await api('GET', '/api/kds/orders', { token: boss })).orders + .find(o => o.id === orderId)?.items.find(i => i.id === itemId) + await card2.click({ position: { x: 20, y: 120 } }) + const item2 = card2.locator('[data-item]').first() + const item2Id = Number(await item2.getAttribute('data-item')) + await item2.click() + await sleep(800) + r.check('3.2b: tapping an item on the selected card marks it done', (await kdsItem(second.id, item2Id))?.kds_status === 'done') + + // undo + await page.getByTestId('kds-undo').click() + await sleep(800) + r.check('3.2b: undo puts it back', (await kdsItem(second.id, item2Id))?.kds_status === 'pending') + + // the action bar: in progress + await card2.click({ position: { x: 20, y: 120 } }) + await card2.getByTestId('card-prepare').click() + await sleep(800) + r.check('3.2b: "in progress" from the card\'s buttons', (await api('GET', '/api/kds/orders', { token: boss })).orders.find(o => o.id === second.id)?.kds_status === 'preparing') + + // long press → quick actions → decline with a reason + const box = await card.boundingBox() + await page.mouse.move(box.x + 30, box.y + 120) + await page.mouse.down() + await sleep(800) + await page.mouse.up() + r.check('3.2b: a long press shows the quick actions', await shown(page, 'quick-decline', 3000)) + await page.getByTestId('quick-decline').click() + await page.locator('[data-reason="out_of_stock"]').click() + await page.getByTestId('decline-confirm').click() + await sleep(800) + const declined = (await api('GET', `/api/kds/orders?zone_id=${grill.id}`, { token: boss })).orders.find(o => o.id === opened.id) + r.check('3.2b: declined with the reason', !!declined && declined.items.some(i => i.kds_status === 'declined' && i.decline_note === 'Out of stock'), + JSON.stringify(declined?.items?.map(i => [i.kds_status, i.decline_note]))) + + // settings on the screen: a chef sees them but can't save + await page.getByTestId('kds-settings').click() + r.check('3.2b: the screen\'s settings: a chef sees them, with "only a manager"', await shown(page, 'kds-settings-panel', 3000) + && await page.getByTestId('settings-no-permission').count() === 1 && await page.getByTestId('settings-save').isDisabled()) + await page.keyboard.press('Escape').catch(() => {}) + await page.getByTestId('kds-settings-panel').getByRole('button', { name: 'Close' }).click() + + // a change made elsewhere (another screen, the waiter) reaches this screen live + await api('PUT', `/api/kds/orders/${second.id}/kds_status`, { token: boss, body: { status: 'pending' } }) + await page.waitForFunction(id => document.querySelector(`[data-testid="kds-card"][data-order="${id}"]`)?.dataset.status === 'pending', second.id, { timeout: 5000 }).catch(() => {}) + r.check('3.2b: a change made elsewhere shows on the screen by itself', await card2.getAttribute('data-status') === 'pending') + await page.getByRole('button', { name: 'Sign out' }).click() r.check('sign out → back to the names', await shown(page, 'user-grid')) @@ -203,7 +281,9 @@ try { await page.screenshot({ path: path.join(OUT, 'terminal-removed.png') }) r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | ')) } catch (e) { - r.check(`terminal: ${e.message.split('\n')[0]}`, false) + r.check(`terminal: ${e.message.split('\n').slice(0, 8).join(' | ')}`, false) + const pages = browser.contexts().flatMap(c => c.pages()) + for (const [i, p] of pages.entries()) await p.screenshot({ path: path.join(OUT, `terminal-failure-${i}.png`) }).catch(() => {}) } finally { await browser.close() term.stop()