import { useEffect, useRef, useState } from 'react' import { useNavigate, useParams, useSearchParams } from 'react-router-dom' import ProductPicker from '../components/ProductPicker' import OrderDrawer from '../components/OrderDrawer' import OrderSummaryModal from '../components/OrderSummaryModal' import client from '../api/client' import { apiError } from '../api/errors' import { getVenueSettings } from '../api/venueSettings' import db from '../db/posdb' import { useProductCache } from '../hooks/useProductCache' import useOrderingSettingsStore from '../store/orderingSettingsStore' import useConnectionStore from '../store/connectionStore' import useAuthStore from '../store/authStore' import { queueOfflineOrder } from '../services/offlineOrders' import { assetUrl } from '../config/server' import { money } from '../i18n' import { LineError, estimate, wireLine } from '@xenia/api' import { useTranslation } from '@xenia/i18n' import { fade } from '../logic/colour' // A cart item whose option is not on the menu any more (4.4: lines go by id) const lineErrorText = (err, t) => t('add.optionGone', { product: err.product, what: err.what }) // ─── Global Course Modal ────────────────────────────────────────────────────── function GlobalCourseModal({ courses, selected, onSelect, onClose }) { const { t } = useTranslation('waiter') return (
e.stopPropagation()}>

{t('add.course.title')}

{t('add.course.sub')}

{courses.map(c => ( ))}
{selected != null && ( )}
) } // ─── Customer count modal ───────────────────────────────────────────────────── function CustomerCountModal({ value, onChange, onClose }) { const { t } = useTranslation('waiter') const [count, setCount] = useState(value ?? 0) const QUICK = [1, 2, 3, 4, 5, 6] return (
e.stopPropagation()}>

{t('detail.guests.title')}

{t('detail.guests.question')}

{/* Quick pick */}
{QUICK.map(n => ( ))}
{/* +/- stepper */}
{count}
) } // ─── The cart's total (4.4) ─────────────────────────────────────────────────── // The server's price (POST /api/orders/quote) when online; offline, or until it answers, the // menu's prices as an estimate. A line the server would refuse shows its reason here. function CartTotal({ priced, estimatedTotal, offline }) { const { t } = useTranslation('waiter') const exact = !!priced?.data return (
{exact ? t('common.total') : offline ? t('add.totalEstimateOffline') : t('add.totalEstimate')} {exact ? money(priced.data.total) : `≈ ${money(estimatedTotal)}`}
{priced?.error &&
{priced.error}
}
) } // ───────────────────────────────────────────────────────────────────────────── const _AI_UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' } function fmtDraftQty(qty, unitType) { const label = _AI_UNIT_LABELS[unitType] if (!label) return `×${qty}` if (unitType === 'kg' || unitType === 'liter') return `${Number(qty).toFixed(1)}${label}` return `${qty}${label}` } export default function AddItemsPage() { const { t } = useTranslation('waiter') const { tableId, orderType } = useParams() const isStandalone = !!orderType // true when on /standalone/:orderType/add const [searchParams] = useSearchParams() const isNewTable = searchParams.get('new') === '1' const navigate = useNavigate() const { products, categories } = useProductCache() const { summaryBeforeSend } = useOrderingSettingsStore() const isOffline = useConnectionStore(s => s.status !== 'online') const { user } = useAuthStore() const [summaryOpen, setSummaryOpen] = useState(false) const [cart, setCart] = useState([]) const [orderId, setOrderId] = useState(null) const [tableLabel, setTableLabel] = useState('') const [sending, setSending] = useState(false) const [error, setError] = useState('') const [printAck, setPrintAck] = useState(null) const [cartOpen, setCartOpen] = useState(false) const [editItem, setEditItem] = useState(null) // { cartKey, product, drawerState } const [viewAllOpen, setViewAllOpen] = useState(false) const [orderNote, setOrderNote] = useState('') const [orderNoteEditing, setOrderNoteEditing] = useState(false) const [searchOpen, setSearchOpen] = useState(false) const [searchQuery, setSearchQuery] = useState('') const [quickToast, setQuickToast] = useState(null) // { product, count } const [customerCount, setCustomerCount] = useState(null) // number of people at table const [customerCountOpen, setCustomerCountOpen] = useState(false) const [courses, setCourses] = useState([]) const [quickNotes, setQuickNotes] = useState(null) // null = not yet fetched; use drawer's fallback const [globalCourseId, setGlobalCourseId] = useState(null) // course pre-selected for quick-add const [globalCourseOpen, setGlobalCourseOpen] = useState(false) const [dealOffers, setDealOffers] = useState([]) // pending deal prompts from server const [activeDealOffer, setActiveDealOffer] = useState(null) // currently shown offer const quickToastTimer = useRef(null) const [quote, setQuote] = useState(null) // { key, data, error } — the server's price of the cart (4.4) useEffect(() => { async function load() { if (isStandalone) { // Standalone orders have no table — set a descriptive label setTableLabel(orderType === 'delivery' ? 'Delivery' : 'Takeaway') // If an existing order ID was passed (adding items to an existing standalone order), seed it const existingOrderId = searchParams.get('orderId') if (existingOrderId) { setOrderId(Number(existingOrderId)) } } else { try { const statusRes = await client.get(`/api/tables/${tableId}/status`) setOrderId(statusRes.data.active_order_id) const tbl = statusRes.data.table if (tbl) setTableLabel(tbl.label || `T${tbl.number}`) // Load existing customer count from the active order if (statusRes.data.active_order_id) { const { data: o } = await client.get(`/api/orders/${statusRes.data.active_order_id}`) if (o.customer_count != null) setCustomerCount(o.customer_count) } } catch { // Offline — read table label from IDB snapshot const tbl = await db.pos_tables.get(Number(tableId)) if (tbl) setTableLabel(tbl.label || `T${tbl.number}`) // orderId stays null — offline orders don't need a pre-existing server order } } // Pre-populate cart from "order again" if present const stored = sessionStorage.getItem('orderAgainItems') if (stored) { sessionStorage.removeItem('orderAgainItems') try { const items = JSON.parse(stored) const initialCart = items.map(it => ({ ...it, _key: Date.now() + Math.random(), })) setCart(initialCart) } catch { /* ignore */ } } } load() }, [tableId, isStandalone, orderType]) useEffect(() => { getVenueSettings().then(r => { const s = r.data if (s?.['orders.courses_enabled']?.value === 'true') { try { setCourses(JSON.parse(s?.['orders.courses']?.value || '[]')) } catch { /* ignore */ } } try { const qn = JSON.parse(s?.['orders.quick_notes']?.value || 'null') if (Array.isArray(qn)) setQuickNotes(qn) } catch { /* ignore */ } }).catch(() => {}) }, []) // Back button: if this was a new table/standalone and nothing was added, go back to tables function handleBack() { if (isStandalone) { navigate('/tables', { replace: true }) } else if (isNewTable && cart.length === 0) { navigate('/tables', { replace: true }) } else { navigate(`/tables/${tableId}`) } } function addToCart(item) { setCart(prev => { // Stack onto an existing cart entry if everything except quantity matches. const { _key: _k, _drawerState: _ds, quantity: _q, ...newCore } = item const matchIdx = prev.findIndex(existing => { const { _key, _drawerState, quantity: _eq, ...existCore } = existing return JSON.stringify(existCore) === JSON.stringify(newCore) }) if (matchIdx !== -1) { const next = [...prev] next[matchIdx] = { ...next[matchIdx], quantity: next[matchIdx].quantity + (item.quantity ?? 1) } return next } return [...prev, { ...item, _key: Date.now() + Math.random() }] }) } function handleQuickAdd(item, product) { const itemWithCourse = globalCourseId != null ? { ...item, course_id: globalCourseId } : item addToCart(itemWithCourse) // Compute new count after adding (cart state updates async, so read current + delta) const existingQty = cart .filter(c => c.product_id === item.product_id) .reduce((s, c) => s + c.quantity, 0) const newCount = existingQty + (item.quantity ?? 1) if (quickToastTimer.current) clearTimeout(quickToastTimer.current) setQuickToast({ product, count: newCount }) quickToastTimer.current = setTimeout(() => setQuickToast(null), 1000) } function removeFromCart(key) { setCart(prev => prev.filter(i => i._key !== key)) } function changeCartQty(key, newQty) { if (newQty <= 0) { removeFromCart(key) } else { setCart(prev => prev.map(i => i._key === key ? { ...i, quantity: newQty } : i)) } } function openEditDrawer(cartItem) { const product = products.find(p => p.id === cartItem.product_id) if (!product) return setCartOpen(false) setEditItem({ cartKey: cartItem._key, product, drawerState: cartItem._drawerState }) } function handleEditSave(updatedItem) { setCart(prev => prev.map(i => i._key === editItem.cartKey ? { ...updatedItem, _key: i._key } : i )) setEditItem(null) } // The cart as the lines the server prices (4.4): what was chosen, by id — never a price function cartLines() { return cart.map(({ _key, _drawerState, ...item }) => wireLine(item, getProduct(item.product_id))) } const estimates = cart.map(item => estimate(item, getProduct(item.product_id))) const estimatedTotal = estimates.reduce((s, v) => s + v, 0) // The server's price of the cart while it's on screen (debounced); offline → the estimate const showPrices = (cartOpen || summaryOpen) && cart.length > 0 && !isOffline const quoteKey = showPrices ? JSON.stringify([orderId, cart.map(({ _key, _drawerState, ...i }) => i)]) : null useEffect(() => { if (!quoteKey) return undefined let lines try { lines = cartLines() } catch (err) { const timer = setTimeout(() => setQuote({ key: quoteKey, data: null, error: err instanceof LineError ? lineErrorText(err, t) : String(err) }), 0) return () => clearTimeout(timer) } const timer = setTimeout(() => { client.post('/api/orders/quote', { lines, order_id: orderId ?? undefined, order_type: isStandalone ? orderType : 'here', }, { noOverride: true }) .then(r => setQuote({ key: quoteKey, data: r.data, error: null })) .catch(err => setQuote({ key: quoteKey, data: null, error: apiError(err, '') })) }, 250) return () => clearTimeout(timer) }, [quoteKey]) // eslint-disable-line react-hooks/exhaustive-deps const priced = quote && quote.key === quoteKey ? quote : null async function sendOrder() { if (cart.length === 0) return setSending(true) setError('') setPrintAck(null) setCartOpen(false) // ── Offline path (not supported for standalone orders) ──────────────────── if (isOffline && !isStandalone) { try { // queued by id; the server prices them when the phone is back (the menu's price is shown as an estimate) const items = cart.map(({ _key, _drawerState, ...item }) => { const product = products.find(p => p.id === item.product_id) return { ...item, _wire: wireLine(item, product), _productSnapshot: product ? { name: product.name } : null, _unitPrice: estimate({ ...item, quantity: 1 }, product), _unitType: product?.unit_type ?? null, } }) await queueOfflineOrder({ tableId: Number(tableId), items, waiterId: user?.id ?? null, }) // Show a brief success state then navigate back setPrintAck({ allOk: true, results: [], _offline: true }) setTimeout(() => navigate('/tables'), 1200) } catch (err) { console.error('[offline order] save failed:', err) setError(err instanceof LineError ? lineErrorText(err, t) : t('add.offlineSaveFailed')) } finally { setSending(false) } return } // ── Online path ─────────────────────────────────────────────────────────── try { let lines try { lines = cartLines() } catch (err) { if (!(err instanceof LineError)) throw err setError(lineErrorText(err, t)) return } let activeOrderId = orderId if (!activeOrderId) { const orderPayload = isStandalone ? { table_id: null, order_type: orderType } : { table_id: Number(tableId), order_type: 'here' } const { data: newOrder } = await client.post('/api/orders/', orderPayload) activeOrderId = newOrder.id setOrderId(activeOrderId) } const res = await client.post(`/api/orders/${activeOrderId}/items`, { lines, order_note: orderNote || null, customer_count: customerCount ?? null, }) const printResults = res.data.print_results ?? [] const printPending = printResults.length > 0 && !printResults.every(r => r.success) // Show deal offers one-by-one before navigating const offers = res.data.deal_offers ?? [] if (offers.length > 0) { const pendingOffers = offers.map(o => ({ ...o, _orderId: activeOrderId })) setDealOffers(pendingOffers.slice(1)) setActiveDealOffer(pendingOffers[0]) setPrintAck({ allOk: true, _pending: printPending }) } else { setPrintAck({ allOk: true, _pending: printPending }) setTimeout(() => navigate('/tables'), 1200) } } catch (err) { setError(apiError(err, t('add.sendFailed'))) } finally { setSending(false) } } function getProduct(id) { return products.find(p => p.id === id) } // Returns structured sections for the expanded cart view function buildItemSections(item, product) { const sections = [] if (item.selected_options?.length) { const prefIds = new Set( (product?.preference_sets || []).flatMap(ps => ps.choices.map(c => c.id)) ) // Build a map: prefChoiceId → preference set name const prefSetByChoiceId = {} ;(product?.preference_sets || []).forEach(ps => { ps.choices.forEach(c => { prefSetByChoiceId[c.id] = ps.name }) }) const quickNames = new Set((product?.quick_options || []).map(o => o.name)) const extraIds = new Set((product?.options || []).map(o => o.id)) // Group prefs: { prefSetName, choiceName, subName } const prefGroups = [] // Group extras: { name, subName, qty } — one entry per unique (id) const extraGroups = [] const quickLines = [] let i = 0 const opts = item.selected_options while (i < opts.length) { const o = opts[i] if (prefIds.has(o.id)) { // Collect sub immediately following (id === null) const setName = prefSetByChoiceId[o.id] ?? '' let subName = null if (i + 1 < opts.length && opts[i + 1].id == null) { subName = opts[i + 1].name i += 2 } else { i++ } // Merge into existing prefGroup for same setName, or create new const existing = prefGroups.find(g => g.setName === setName) if (existing) { // multiple choices from same set (shouldn't normally happen, but handle gracefully) existing.values.push(subName ? `${o.name} · ${subName}` : o.name) } else { prefGroups.push({ setName, values: [subName ? `${o.name} · ${subName}` : o.name] }) } } else if (o.id != null && extraIds.has(o.id)) { // Collect sub immediately following let subName = null if (i + 1 < opts.length && opts[i + 1].id == null) { subName = opts[i + 1].name i += 2 } else { i++ } // Merge duplicates const existing = extraGroups.find(g => g.id === o.id && g.subName === subName) if (existing) existing.qty++ else extraGroups.push({ id: o.id, name: o.name, subName, qty: 1 }) } else if (quickNames.has(o.name)) { quickLines.push(o) i++ } else { i++ } } // Deduplicate quick lines: multiple entries of same name → single entry with qty const quickDeduped = [] quickLines.forEach(o => { const existing = quickDeduped.find(x => x.name === o.name) if (existing) existing._qty = (existing._qty || 1) + 1 else quickDeduped.push({ ...o, _qty: 1 }) }) if (prefGroups.length > 0) sections.push({ type: 'prefs', lines: prefGroups }) if (quickDeduped.length > 0) sections.push({ type: 'quick', lines: quickDeduped }) if (extraGroups.length > 0) sections.push({ type: 'extras', lines: extraGroups }) } if (item.removed_ingredients?.length) { sections.push({ type: 'removed', lines: item.removed_ingredients.map(n => ({ name: n })) }) } if (item.notes) { sections.push({ type: 'note', lines: [{ name: item.notes }] }) } return sections } // Simple flat summary for the collapsed one-liner function buildItemSummary(item) { const lines = [] if (item.selected_options?.length) { item.selected_options.forEach(o => { if (o.price_delta && o.price_delta !== 0) lines.push(`${o.name} (${o.price_delta > 0 ? '+' : ''}${money(o.price_delta)})`) else lines.push(o.name) }) } if (item.removed_ingredients?.length) lines.push(t('add.withoutList', { names: item.removed_ingredients.join(', ') })) if (item.notes) lines.push(item.notes) return lines } // Compact names for the strip preview (max 3 items shown) const stripItems = cart.slice(-3).reverse() const hiddenCount = cart.length > 3 ? cart.length - 3 : 0 return (
{tableLabel || (isNewTable ? t('add.newOrder') : t('add.add'))}
{/* Customer count button */} {/* Course selector button — only when courses are configured */} {courses.length > 0 && ( )} {/* Search button */} {/* Categories button */} {/* Cart button with badge */}
{/* Product picker takes all remaining space */} {/* Quick-add toast */} {quickToast && ( )} {/* ── Bottom bar: floating mini-cart + full-width SEND ─────────────── */}
{/* Floating compact cart — shown only when there are items */} {cart.length > 0 && (
setCartOpen(true)} style={{ background: 'var(--bg3)', border: '1px solid var(--border)', borderRadius: 12, padding: '8px 12px', marginBottom: 10, cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 4, }} > {stripItems.map(item => { const p = getProduct(item.product_id) return (
{p?.name ?? `#${item.product_id}`} {fmtDraftQty(item.quantity, p?.unit_type)}
) })} {hiddenCount > 0 && (
{t('add.moreSeeAll', { count: hiddenCount })}
)}
)} {/* Full-width send button */} {error &&

{error}

}
{/* ── Cart side drawer ────────────────────────────────────────────────── */} <> {/* Backdrop */}
setCartOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgb(var(--x-scrim-rgb) / 0.55)', opacity: cartOpen ? 1 : 0, pointerEvents: cartOpen ? 'auto' : 'none', transition: 'opacity 240ms ease', zIndex: 50, }} /> {/* Panel */}
{/* Drawer header */}
{t('add.order')}
{t('add.products', { count: cart.length })}
{/* Item list */}
{cart.length === 0 ? (

{t('add.empty')}

) : courses.length > 0 ? (() => { // Group by course, ordered by course definition, "no course" last const groups = [] courses.forEach(c => { const items = cart.filter(i => i.course_id === c.id) if (items.length > 0) groups.push({ course: c, items }) }) const noCourse = cart.filter(i => i.course_id == null || !courses.find(c => c.id === i.course_id)) if (noCourse.length > 0) groups.push({ course: null, items: noCourse }) return (
{groups.map((group, _gi) => (
{/* Colored left accent bar */}
{/* Group header */}
{group.course ? group.course.name : t('add.course.none')}
{group.items.map(item => { const product = getProduct(item.product_id) return ( openEditDrawer(item)} onRemove={() => removeFromCart(item._key)} onChangeQty={qty => changeCartQty(item._key, qty)} /> ) })}
))}
) })() : (
{cart.map(item => { const product = getProduct(item.product_id) return ( openEditDrawer(item)} onRemove={() => removeFromCart(item._key)} onChangeQty={qty => changeCartQty(item._key, qty)} /> ) })}
)}
{/* Order note area */} {cart.length > 0 && (
{orderNoteEditing ? (