Files
xenia-pos-local/waiter_pwa/src/pages/AddItemsPage.jsx
T
bonaminandClaude Opus 5.5 0840247768 feat: staff apps show the menu in the reader's language (plan 6R.L)
The waiters' phones and the counter show categories, products and every
choice (quick options, extras and sub-choices, preferences, shared sets,
ingredients, groups) in the signed-in person's language, falling back to
the stored text. Display only: carts, lines, tickets and the kitchen keep
the venue's text (ids, sub-choices by stored name). In the venue's own
language nothing changes.

- @xenia/access: menuText / useMenuText (mt, mt.choice, mt.line, mt.matches)
- /api/pos/menu carries translations for products, categories and choices
- shared ProductDialog takes a text() prop (the counter passes useMenuText)
- search finds a product by its name in any language (counter, waiter)
- waiter: useMenuNames for sent lines; picker, drawer, cart, summary,
  table lines, quantity / price history, favourites setup
- counter: categories, cards, dialog, cart lines, table lines, payment rows
- tests: access menuText, ordering search, test_pos per-language,
  e2e waiter.mjs and terminal.mjs 6R.L blocks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 20:18:10 +02:00

1525 lines
71 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 { useMenuText } from '@xenia/access'
import { fade } from '../logic/colour'
import SeatsHint from '../components/SeatsHint'
// 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 (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-sheet" onClick={e => e.stopPropagation()}>
<div className="modal-handle" />
<h2 className="modal-title">{t('add.course.title')}</h2>
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 16px' }}>
{t('add.course.sub')}
</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
{courses.map(c => (
<button
key={c.id}
onClick={() => { onSelect(c.id === selected ? null : c.id); onClose() }}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '12px 16px',
background: c.id === selected ? `${fade(c.color, 0.13)}` : 'var(--bg3)',
border: `2px solid ${c.id === selected ? c.color : 'var(--border)'}`,
borderRadius: 12, cursor: 'pointer', textAlign: 'left',
}}
>
<span style={{ width: 14, height: 14, borderRadius: '50%', background: c.color, flexShrink: 0, display: 'inline-block' }} />
<span style={{ fontSize: 15, fontWeight: c.id === selected ? 700 : 500, color: 'var(--text)', flex: 1 }}>{c.name}</span>
{c.id === selected && (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="var(--accent)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
)}
</button>
))}
</div>
{selected != null && (
<button
className="btn btn--secondary"
style={{ width: '100%', marginBottom: 8 }}
onClick={() => { onSelect(null); onClose() }}
>
{t('common.clear')}
</button>
)}
<button className="btn btn--secondary" style={{ width: '100%' }} onClick={onClose}>{t('common.cancel')}</button>
</div>
</div>
)
}
// ─── Customer count modal ─────────────────────────────────────────────────────
function CustomerCountModal({ value, seats, onChange, onClose }) {
const { t } = useTranslation('waiter')
const [count, setCount] = useState(value ?? 0)
const QUICK = [1, 2, 3, 4, 5, 6]
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-sheet" onClick={e => e.stopPropagation()}>
<div className="modal-handle" />
<h2 className="modal-title">{t('detail.guests.title')}</h2>
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, margin: '0 0 20px' }}>
{t('detail.guests.question')}
</p>
<SeatsHint seats={seats} count={count} />
{/* Quick pick */}
<div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginBottom: 20 }}>
{QUICK.map(n => (
<button
key={n}
onClick={() => setCount(n)}
style={{
width: 44, height: 44, borderRadius: 12, border: 'none', cursor: 'pointer',
fontWeight: 800, fontSize: 16,
background: count === n ? 'var(--accent)' : 'var(--bg3)',
color: count === n ? 'var(--accent-fg)' : 'var(--text)',
}}
>{n}</button>
))}
</div>
{/* +/- stepper */}
<div className="modal-qty" style={{ marginBottom: 20 }}>
<button className="qty-btn" onClick={() => setCount(c => Math.max(0, c - 1))}>−</button>
<span className="qty-value">{count}</span>
<button className="qty-btn" onClick={() => setCount(c => c + 1)}>+</button>
</div>
<div style={{ display: 'flex', gap: 10 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>{t('common.cancel')}</button>
<button className="btn btn--primary" style={{ flex: 1 }} onClick={() => { onChange(count || null); onClose() }}>
{t('common.apply')}
</button>
</div>
</div>
</div>
)
}
// ─── 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 (
<div data-testid="cart-total" data-estimated={exact ? 'false' : 'true'}
style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
<span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 600 }}>
{exact ? t('common.total') : offline ? t('add.totalEstimateOffline') : t('add.totalEstimate')}
</span>
<span style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>
{exact ? money(priced.data.total) : `≈ ${money(estimatedTotal)}`}
</span>
</div>
{priced?.error && <div data-testid="cart-total-error" style={{ fontSize: 12, color: 'var(--danger)' }}>{priced.error}</div>}
</div>
)
}
// ─────────────────────────────────────────────────────────────────────────────
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 mt = useMenuText() // 6R.L: names in the waiter's language; the cart keeps ids and stored names
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 [seats, setSeats] = useState(null) // the table's seats: a suggestion (4.8)
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}`); setSeats(tbl.seat_count ?? null) }
// 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}`); setSeats(tbl.seat_count ?? null) }
// 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 = []
const c = name => mt.choice(product, name) // 6R.L: shown in the waiter's language
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(ch => { prefSetByChoiceId[ch.id] = mt(ps) })
})
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 = c(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 ? `${c(o.name)} · ${subName}` : c(o.name))
} else {
prefGroups.push({ setName, values: [subName ? `${c(o.name)} · ${subName}` : c(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 = c(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: c(o.name), subName, qty: 1 })
} else if (quickNames.has(o.name)) {
quickLines.push({ ...o, name: c(o.name) })
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: c(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 = []
const c = name => mt.choice(getProduct(item.product_id), name) // 6R.L
if (item.selected_options?.length) {
item.selected_options.forEach(o => {
if (o.price_delta && o.price_delta !== 0)
lines.push(`${c(o.name)} (${o.price_delta > 0 ? '+' : ''}${money(o.price_delta)})`)
else lines.push(c(o.name))
})
}
if (item.removed_ingredients?.length) lines.push(t('add.withoutList', { names: item.removed_ingredients.map(c).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 (
<div className="page" style={{ position: 'relative' }}>
<header className="top-bar">
<button className="icon-btn" onClick={handleBack}>←</button>
<span className="top-bar__title">{tableLabel || (isNewTable ? t('add.newOrder') : t('add.add'))}</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
{/* Customer count button */}
<button
className="icon-btn"
style={{ position: 'relative' }}
onClick={() => setCustomerCountOpen(true)}
title={t('detail.guests.button')}
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
<circle cx="9" cy="7" r="4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
<path d="M23 21v-2a4 4 0 0 0-3-3.87" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
<path d="M16 3.13a4 4 0 0 1 0 7.75" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
{customerCount != null && customerCount > 0 && (
<span style={{
position: 'absolute', top: -2, right: -2,
minWidth: 18, height: 18, borderRadius: 9,
background: 'var(--x-info)', color: 'rgb(var(--x-scrim-rgb) / 1)',
fontSize: 10, fontWeight: 800,
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: '0 4px',
}}>{customerCount}</span>
)}
</button>
{/* Course selector button — only when courses are configured */}
{courses.length > 0 && (
<button
className="icon-btn"
style={{ position: 'relative' }}
onClick={() => setGlobalCourseOpen(true)}
title={t('add.course.title')}
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
<path d="M12 7v5l3 3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
{globalCourseId != null && (() => {
const c = courses.find(c => c.id === globalCourseId)
return c ? (
<span style={{
position: 'absolute', top: -2, right: -2,
minWidth: 18, height: 18, borderRadius: 9,
background: c.color, color: 'var(--x-on-colour)',
fontSize: 10, fontWeight: 800,
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: '0 4px',
}}>{c.id}</span>
) : null
})()}
</button>
)}
{/* Search button */}
<button className="icon-btn" onClick={() => { setSearchQuery(''); setSearchOpen(true) }} title={t('add.search.title')}>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2.2"/>
<path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
</svg>
</button>
{/* Categories button */}
<button className="icon-btn" onClick={() => setViewAllOpen(true)} title={t('add.allCategories')}>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<rect x="3" y="3" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
<rect x="14" y="3" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
<rect x="3" y="14" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
<rect x="14" y="14" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
</svg>
</button>
{/* Cart button with badge */}
<button
className="icon-btn"
data-testid="cart-open"
style={{ position: 'relative' }}
onClick={() => setCartOpen(true)}
>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none">
<path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4zM3 6h18M16 10a4 4 0 01-8 0" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
{cart.length > 0 && (
<span style={{
position: 'absolute', top: -2, right: -2,
minWidth: 18, height: 18, borderRadius: 9,
background: 'var(--accent)', color: 'var(--accent-fg)',
fontSize: 11, fontWeight: 800,
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: '0 4px',
}}>{cart.length}</span>
)}
</button>
</div>
</header>
{/* Product picker takes all remaining space */}
<ProductPicker
categories={categories}
products={products}
onAdd={addToCart}
onQuickAdd={handleQuickAdd}
viewAllOpen={viewAllOpen}
setViewAllOpen={setViewAllOpen}
customerCount={customerCount}
courses={courses}
globalCourseId={globalCourseId}
quickNotes={quickNotes}
/>
{/* Quick-add toast */}
{quickToast && (
<QuickAddToast product={quickToast.product} count={quickToast.count} />
)}
{/* ── Bottom bar: floating mini-cart + full-width SEND ─────────────── */}
<div style={{
background: 'var(--bg2)',
borderTop: '1px solid var(--border)',
padding: '10px 12px 14px',
flexShrink: 0,
}}>
{/* Floating compact cart — shown only when there are items */}
{cart.length > 0 && (
<div
onClick={() => 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 (
<div key={item._key} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ fontSize: 12, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>{p ? mt(p) : `#${item.product_id}`}</span>
<span style={{ fontSize: 12, fontWeight: 700, color: 'var(--x-warning)', fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>{fmtDraftQty(item.quantity, p?.unit_type)}</span>
</div>
)
})}
{hiddenCount > 0 && (
<div style={{ fontSize: 11, color: 'var(--muted)', textAlign: 'right' }}>
{t('add.moreSeeAll', { count: hiddenCount })}
</div>
)}
</div>
)}
{/* Full-width send button */}
<button
className="btn btn--primary btn--lg"
style={{ width: '100%', opacity: cart.length === 0 ? 0.4 : 1 }}
onClick={() => summaryBeforeSend && cart.length > 0 ? setSummaryOpen(true) : sendOrder()}
disabled={cart.length === 0 || sending}
>
{sending ? t('add.sending') : summaryBeforeSend && cart.length > 0 ? t('add.summaryCount', { count: cart.length }) : cart.length > 0 ? t('add.sendCount', { count: cart.length }) : t('add.send')}
</button>
{error && <p className="error-msg" style={{ marginTop: 8 }}>{error}</p>}
</div>
{/* ── Cart side drawer ────────────────────────────────────────────────── */}
<>
{/* Backdrop */}
<div
onClick={() => 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 */}
<div style={{
position: 'fixed', top: 0, right: 0, bottom: 0,
width: 'min(88vw, 380px)',
background: 'var(--bg)',
borderLeft: '1px solid var(--border)',
transform: cartOpen ? 'translateX(0)' : 'translateX(100%)',
transition: 'transform 280ms cubic-bezier(0.32, 0.72, 0, 1)',
zIndex: 51,
display: 'flex', flexDirection: 'column',
boxShadow: cartOpen ? '-8px 0 32px rgb(var(--x-scrim-rgb) / 0.4)' : 'none',
}}>
{/* Drawer header */}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
<div>
<div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)' }}>{t('add.order')}</div>
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{t('add.products', { count: cart.length })}</div>
</div>
<button onClick={() => setCartOpen(false)} style={{ background: 'var(--bg3)', border: 'none', borderRadius: '50%', width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'var(--text)' }}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
</button>
</div>
{/* Item list */}
<div style={{ flex: 1, overflowY: 'auto', padding: 12 }}>
{cart.length === 0 ? (
<p style={{ color: 'var(--muted)', textAlign: 'center', padding: '40px 0', fontSize: 14 }}>{t('add.empty')}</p>
) : 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 (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{groups.map((group, _gi) => (
<div key={group.course?.id ?? '__none__'} style={{ position: 'relative' }}>
{/* Colored left accent bar */}
<div style={{
position: 'absolute', left: 0, top: 0, bottom: 0,
width: 3, borderRadius: 2,
background: group.course ? group.course.color : 'var(--border)',
}} />
<div style={{ paddingLeft: 10 }}>
{/* Group header */}
<div style={{
fontSize: 10, fontWeight: 700,
color: group.course ? group.course.color : 'var(--muted)',
textTransform: 'uppercase', letterSpacing: 0.8,
marginBottom: 6,
}}>
{group.course ? group.course.name : t('add.course.none')}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{group.items.map(item => {
const product = getProduct(item.product_id)
return (
<CartItem
key={item._key}
item={item}
product={product}
summaryLines={buildItemSummary(item)}
sections={buildItemSections(item, product)}
onEdit={() => openEditDrawer(item)}
onRemove={() => removeFromCart(item._key)}
onChangeQty={qty => changeCartQty(item._key, qty)}
/>
)
})}
</div>
</div>
</div>
))}
</div>
)
})() : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{cart.map(item => {
const product = getProduct(item.product_id)
return (
<CartItem
key={item._key}
item={item}
product={product}
summaryLines={buildItemSummary(item)}
sections={buildItemSections(item, product)}
onEdit={() => openEditDrawer(item)}
onRemove={() => removeFromCart(item._key)}
onChangeQty={qty => changeCartQty(item._key, qty)}
/>
)
})}
</div>
)}
</div>
{/* Order note area */}
{cart.length > 0 && (
<div style={{ padding: '0 12px 10px', flexShrink: 0 }}>
{orderNoteEditing ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<textarea
autoFocus
value={orderNote}
onChange={e => setOrderNote(e.target.value)}
placeholder={t('add.note.placeholder')}
rows={3}
style={{
width: '100%', resize: 'none', padding: '10px 12px',
background: 'rgb(var(--x-warning-rgb) / 0.07)', border: '1.5px solid rgb(var(--x-warning-rgb) / 0.35)',
borderRadius: 10, fontSize: 14, color: 'var(--text)', lineHeight: 1.5,
outline: 'none', boxSizing: 'border-box', fontFamily: 'inherit',
}}
/>
<button
onClick={() => setOrderNoteEditing(false)}
style={{ alignSelf: 'flex-end', background: 'none', border: 'none', fontSize: 12, fontWeight: 700, color: 'var(--accent)', cursor: 'pointer', padding: '2px 0' }}
>
{t('common.save')}
</button>
</div>
) : orderNote ? (
<div
onClick={() => setOrderNoteEditing(true)}
style={{ cursor: 'pointer', padding: '9px 12px', background: 'rgb(var(--x-warning-rgb) / 0.09)', border: '1.5px solid rgb(var(--x-warning-rgb) / 0.3)', borderRadius: 10, fontSize: 13, color: 'var(--text)', lineHeight: 1.5, whiteSpace: 'pre-wrap', position: 'relative' }}
>
<span style={{ fontSize: 10, fontWeight: 700, color: 'var(--x-warning)', textTransform: 'uppercase', letterSpacing: 0.6, display: 'block', marginBottom: 3 }}>{t('add.note.title')}</span>
{orderNote}
<span style={{ position: 'absolute', top: 8, right: 10, fontSize: 11, color: 'var(--x-warning)', fontWeight: 700 }}>✎</span>
</div>
) : (
<button
onClick={() => setOrderNoteEditing(true)}
style={{
width: '100%', padding: '9px 12px',
background: 'var(--bg3)', border: '1.5px dashed var(--border)',
borderRadius: 10, fontSize: 13, color: 'var(--muted)',
cursor: 'pointer', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 7,
}}
>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
{t('add.note.add')}
</button>
)}
</div>
)}
{/* Drawer footer */}
<div style={{ padding: '0 12px 20px', borderTop: '1px solid var(--border)', paddingTop: 12, flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
{cart.length > 0 && (
<CartTotal priced={priced} estimatedTotal={estimatedTotal} offline={isOffline} />
)}
<button
className="btn btn--primary btn--lg"
style={{ width: '100%' }}
onClick={() => { setCartOpen(false); if (summaryBeforeSend) setSummaryOpen(true); else sendOrder() }}
disabled={cart.length === 0 || sending}
>
{sending ? t('add.sending') : summaryBeforeSend ? t('add.summaryCount', { count: cart.length }) : t('add.sendCount', { count: cart.length })}
</button>
</div>
</div>
</>
{/* Edit drawer */}
{editItem && (
<OrderDrawer
product={editItem.product}
isOpen={!!editItem}
onClose={() => setEditItem(null)}
onAdd={handleEditSave}
initialState={editItem.drawerState}
courses={courses}
quickNotes={quickNotes}
/>
)}
{/* Order summary modal (shown when summaryBeforeSend is enabled) */}
{summaryOpen && (
<OrderSummaryModal
cart={cart}
products={products}
prices={priced?.data ? priced.data.lines.map(l => l.total) : estimates}
total={priced?.data ? priced.data.total : estimatedTotal}
estimated={!priced?.data}
priceError={priced?.error ?? null}
orderNote={orderNote}
setOrderNote={setOrderNote}
onSend={() => { setSummaryOpen(false); sendOrder() }}
onClose={() => setSummaryOpen(false)}
sending={sending}
/>
)}
{/* ── Search modal ─────────────────────────────────────────────────────── */}
{searchOpen && (
<SearchModal
products={products}
query={searchQuery}
setQuery={setSearchQuery}
onClose={() => setSearchOpen(false)}
onAdd={item => { addToCart(item); setSearchOpen(false) }}
courses={courses}
quickNotes={quickNotes}
/>
)}
{/* Customer count modal */}
{customerCountOpen && (
<CustomerCountModal
value={customerCount}
seats={seats}
onChange={v => setCustomerCount(v)}
onClose={() => setCustomerCountOpen(false)}
/>
)}
{/* Global course modal */}
{globalCourseOpen && courses.length > 0 && (
<GlobalCourseModal
courses={courses}
selected={globalCourseId}
onSelect={setGlobalCourseId}
onClose={() => setGlobalCourseOpen(false)}
/>
)}
{/* Deal offer modal — shown one at a time after order is sent */}
{activeDealOffer && (
<DealOfferModal
offer={activeDealOffer}
products={products}
onAccept={async (freeItems) => {
try {
await client.post('/api/pricing/deals/accept', {
deal_id: activeDealOffer.deal_id,
order_id: activeDealOffer._orderId,
free_items: freeItems,
trigger_item_id: activeDealOffer.target_order_item_id ?? null,
})
} catch { /* log but continue */ }
// Advance to next offer or finish
if (dealOffers.length > 0) {
setActiveDealOffer(dealOffers[0])
setDealOffers(prev => prev.slice(1))
} else {
setActiveDealOffer(null)
if (printAck?.allOk) setTimeout(() => navigate('/tables'), 600)
}
}}
onDismiss={async () => {
try {
await client.post('/api/pricing/deals/dismiss', {
deal_id: activeDealOffer.deal_id,
order_id: activeDealOffer._orderId,
})
} catch { /* ignore */ }
if (dealOffers.length > 0) {
setActiveDealOffer(dealOffers[0])
setDealOffers(prev => prev.slice(1))
} else {
setActiveDealOffer(null)
if (printAck?.allOk) setTimeout(() => navigate('/tables'), 600)
}
}}
/>
)}
{/* Full-screen success overlay — blocks all interaction while navigating */}
{printAck?.allOk && !activeDealOffer && (
<div style={{
position: 'fixed', inset: 0, zIndex: 9999,
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
background: 'rgb(var(--x-scrim-rgb) / 0.72)',
animation: 'fadeInOverlay 180ms ease',
}}>
<div style={{
background: printAck._offline ? 'var(--x-warning-soft)' : printAck._pending ? 'var(--x-canvas)' : 'var(--x-success-soft)',
border: `2px solid ${printAck._offline ? 'var(--x-warning)' : printAck._pending ? 'var(--x-warning)' : 'var(--x-success)'}`,
borderRadius: 20, padding: '36px 48px',
display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,
animation: 'popIn 220ms cubic-bezier(0.34,1.56,0.64,1)',
}}>
<svg width="56" height="56" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="11" stroke={printAck._offline || printAck._pending ? 'var(--x-warning)' : 'var(--x-success)'} strokeWidth="2"/>
{printAck._offline || printAck._pending ? (
<path d="M12 8v5M12 16h.01" stroke="var(--x-warning)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
) : (
<path d="M7 12.5l3.5 3.5 6.5-7" stroke="var(--x-success)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
)}
</svg>
<span style={{ color: printAck._offline || printAck._pending ? 'var(--x-warning)' : 'var(--x-success-ink)', fontWeight: 700, fontSize: 18, letterSpacing: 0.3 }}>
{printAck._offline ? t('add.ack.offline') : printAck._pending ? t('add.ack.printing') : t('add.ack.printed')}
</span>
</div>
<style>{`
@keyframes fadeInOverlay { from { opacity: 0 } to { opacity: 1 } }
@keyframes popIn { from { transform: scale(0.7); opacity: 0 } to { transform: scale(1); opacity: 1 } }
`}</style>
</div>
)}
</div>
)
}
// ── Deal Offer Modal ──────────────────────────────────────────────────────────
function DealOfferModal({ offer, _products, onAccept, onDismiss }) {
const { t } = useTranslation('waiter')
const isFreeItem = offer.action_type === 'free_item'
const isFreeChoice = offer.action_type === 'free_choice'
const isDiscount = ['set_price','add_amount','add_percent','apply_modifier'].includes(offer.action_type)
// For free_choice: track which products are selected
const [selectedChoices, setSelectedChoices] = useState([])
const remaining = (offer.free_quantity ?? 1) - selectedChoices.length
function toggleChoice(productId) {
setSelectedChoices(prev => {
if (prev.includes(productId)) return prev.filter(x => x !== productId)
if (prev.length >= (offer.free_quantity ?? 1)) return prev // at capacity
return [...prev, productId]
})
}
function handleAccept() {
if (isFreeItem) {
onAccept([{ product_id: offer.free_item_id, quantity: offer.free_quantity ?? 1 }])
} else if (isFreeChoice) {
onAccept(selectedChoices.map(id => ({ product_id: id, quantity: 1 })))
} else {
onAccept([]) // discount deal — no free items to add
}
}
const canConfirm = isFreeChoice ? selectedChoices.length > 0 : true
return (
<div className="modal-overlay" style={{ zIndex: 600 }} onClick={onDismiss}>
<div className="modal-sheet" onClick={e => e.stopPropagation()} style={{ gap: 0 }}>
<div className="modal-handle" />
{/* Header */}
<div style={{ textAlign: 'center', padding: '0 8px 16px' }}>
<div style={{
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
width: 48, height: 48, borderRadius: '50%',
background: 'rgb(var(--x-special-rgb) / 0.15)', marginBottom: 10,
}}>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
<path d="M20 12v10H4V12M22 7H2v5h20V7zM12 22V7M12 7H7.5a2.5 2.5 0 010-5C11 2 12 7 12 7zM12 7h4.5a2.5 2.5 0 000-5C13 2 12 7 12 7z"
stroke="var(--x-special-ink)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</div>
<h2 style={{ margin: 0, fontSize: 17, fontWeight: 700, color: 'var(--x-special-ink)' }}>{t('add.deal.title')}</h2>
<p style={{ margin: '6px 0 0', fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{offer.deal_name}</p>
</div>
{/* Free item — single specific product */}
{isFreeItem && offer.free_item_name && (
<div style={{
margin: '0 0 16px', padding: '14px 16px',
background: 'rgb(var(--x-success-rgb) / 0.08)', border: '1.5px solid rgb(var(--x-success-rgb) / 0.3)',
borderRadius: 12,
}}>
<p style={{ margin: 0, fontSize: 13, color: 'var(--muted)', marginBottom: 4 }}>{t('add.deal.freeProduct')}</p>
<p style={{ margin: 0, fontSize: 15, fontWeight: 700, color: 'var(--x-success)' }}>
{offer.free_item_name}
{offer.free_quantity > 1 && <span style={{ color: 'var(--x-warning)', marginLeft: 6 }}>×{offer.free_quantity}</span>}
</p>
</div>
)}
{/* Free choice — pick from pool */}
{isFreeChoice && offer.free_choices?.length > 0 && (
<div style={{ marginBottom: 16 }}>
<p style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 8 }}>
{t('add.deal.pickFree', { count: offer.free_quantity ?? 1 })}
{remaining > 0 && <span style={{ color: 'var(--x-special-ink)', marginLeft: 4 }}>{t('add.deal.remaining', { count: remaining })}</span>}
</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 220, overflowY: 'auto' }}>
{offer.free_choices.map(choice => {
const checked = selectedChoices.includes(choice.id)
const disabled = !checked && remaining === 0
return (
<button key={choice.id} onClick={() => !disabled && toggleChoice(choice.id)}
style={{
display: 'flex', alignItems: 'center', gap: 10,
padding: '10px 12px', borderRadius: 10, border: 'none', cursor: disabled ? 'not-allowed' : 'pointer',
background: checked ? 'rgb(var(--x-special-rgb) / 0.15)' : 'var(--bg3)',
opacity: disabled ? 0.4 : 1, textAlign: 'left',
}}>
<div style={{
width: 20, height: 20, borderRadius: 5, flexShrink: 0,
background: checked ? 'var(--x-special-ink)' : 'var(--border)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{checked && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--x-on-colour)" strokeWidth="3" strokeLinecap="round"><path d="M20 6L9 17l-5-5"/></svg>}
</div>
<span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{choice.name}</span>
</button>
)
})}
</div>
</div>
)}
{/* Discount deal — show before/after */}
{isDiscount && offer.price_before != null && offer.price_after != null && (
<div style={{
margin: '0 0 16px', padding: '14px 16px',
background: 'rgb(var(--x-success-rgb) / 0.08)', border: '1.5px solid rgb(var(--x-success-rgb) / 0.3)',
borderRadius: 12, textAlign: 'center',
}}>
<span style={{ fontSize: 14, color: 'var(--muted)', textDecoration: 'line-through' }}>
{money(offer.price_before)}
</span>
<span style={{ fontSize: 22, fontWeight: 800, color: 'var(--x-success)', margin: '0 12px' }}>
{money(offer.price_after)}
</span>
</div>
)}
<div style={{ display: 'flex', gap: 10 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onDismiss}>
{t('add.deal.skip')}
</button>
<button className="btn btn--primary" style={{ flex: 1, background: 'var(--x-special)', borderColor: 'var(--x-special)' }}
onClick={handleAccept} disabled={!canConfirm}>
{isFreeItem ? t('add.deal.addFree') : isFreeChoice ? t('common.confirm') : t('common.apply')}
</button>
</div>
</div>
</div>
)
}
// ── Quick-Add Toast ───────────────────────────────────────────────────────────
function QuickAddToast({ product, count }) {
const { t } = useTranslation('waiter')
const mt = useMenuText()
const initials = mt(product).trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
return (
<div style={{
position: 'fixed', top: 62, left: '50%',
transform: 'translateX(-50%)',
zIndex: 400,
background: 'var(--bg)',
border: '1px solid var(--border)',
borderRadius: 14,
boxShadow: '0 8px 32px rgb(var(--x-scrim-rgb) / 0.35)',
display: 'flex', alignItems: 'center', gap: 12,
padding: '10px 16px 10px 10px',
minWidth: 220, maxWidth: 'min(88vw, 340px)',
animation: 'qa-toast-in 120ms cubic-bezier(0.34,1.56,0.64,1)',
pointerEvents: 'none',
}}>
{/* Thumb */}
<div style={{
width: 46, height: 46, borderRadius: 10, flexShrink: 0,
background: 'var(--bg3)', overflow: 'hidden',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{product.image_url
? <img src={assetUrl(product.image_url)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: <span style={{ fontSize: 16, fontWeight: 700, color: 'var(--muted)' }}>{initials}</span>
}
</div>
{/* Name */}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{
fontSize: 13, fontWeight: 600, color: 'var(--text)',
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>{mt(product)}</div>
<div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1 }}>{t('add.inCart')}</div>
</div>
{/* Count badge */}
<div style={{
minWidth: 36, height: 36, borderRadius: 10,
background: 'var(--accent)', color: 'var(--accent-fg)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 17, fontWeight: 800, flexShrink: 0,
padding: '0 8px',
}}>×{count}</div>
<style>{`
@keyframes qa-toast-in {
from { opacity: 0; transform: translateX(-50%) scale(0.88); }
to { opacity: 1; transform: translateX(-50%) scale(1); }
}
`}</style>
</div>
)
}
// ── Cart Item (used in the side drawer) ───────────────────────────────────────
const SECTION_META = {
prefs: { icon: '◉', label: null },
quick: { icon: '>', label: null },
extras: { icon: '+', label: null },
removed: { icon: '−', label: null },
note: { icon: 'i', label: null },
}
function SectionIcon({ type }) {
const icons = {
prefs: <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="4" fill="var(--x-warning)"/><circle cx="12" cy="12" r="9" stroke="var(--x-warning)" strokeWidth="2"/></svg>,
quick: <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="var(--x-success)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>,
extras: <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M12 5v14M5 12h14" stroke="var(--x-info)" strokeWidth="2.5" strokeLinecap="round"/></svg>,
removed: <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M5 12h14" stroke="var(--x-danger)" strokeWidth="2.5" strokeLinecap="round"/></svg>,
note: <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="1.5" fill="var(--x-ink-2)"/><path d="M12 7v1M12 16v1" stroke="var(--x-ink-2)" strokeWidth="2" strokeLinecap="round"/><circle cx="12" cy="12" r="9" stroke="var(--x-ink-2)" strokeWidth="1.5"/></svg>,
}
return <span style={{ display: 'inline-flex', alignItems: 'center', flexShrink: 0 }}>{icons[type] ?? null}</span>
}
function CartItem({ item, product, summaryLines, sections, onEdit, onRemove, onChangeQty }) {
const { t } = useTranslation('waiter')
const mt = useMenuText()
const [expanded, setExpanded] = useState(false)
const hasDetails = sections.length > 0
return (
<div style={{ background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
{/* Whole header row is always clickable to expand (qty stepper is always available) */}
<div
onClick={() => setExpanded(e => !e)}
style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', cursor: 'pointer' }}
>
{/* Chevron — always shown */}
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" style={{ transform: `rotate(${expanded ? 180 : 0}deg)`, transition: 'transform 180ms', flexShrink: 0, color: 'var(--muted)' }}>
<path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
</svg>
{/* Name */}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{product ? mt(product) : `#${item.product_id}`}
</div>
{!expanded && hasDetails && (
<div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{summaryLines[0]}{summaryLines.length > 1 ? ` +${summaryLines.length - 1}` : ''}
</div>
)}
</div>
{/* Quantity on the right */}
<span style={{ color: 'var(--x-warning)', fontSize: 13, fontWeight: 700, fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>{fmtDraftQty(item.quantity, product?.unit_type)}</span>
{/* Edit — stop propagation so it doesn't toggle expand */}
<button onClick={e => { e.stopPropagation(); onEdit() }} style={{ background: 'none', border: '1px solid var(--border)', borderRadius: 7, color: 'var(--muted)', cursor: 'pointer', padding: '3px 9px', fontSize: 12, fontWeight: 500, flexShrink: 0 }}>
{t('add.edit')}
</button>
{/* Remove */}
<button onClick={e => { e.stopPropagation(); onRemove() }} style={{ background: 'none', border: 'none', color: 'var(--danger)', cursor: 'pointer', padding: 4, display: 'flex', alignItems: 'center', flexShrink: 0 }}>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
</button>
</div>
{expanded && (
<div style={{ paddingBottom: 10 }}>
{sections.map((sec, si) => (
<div key={si}>
<div style={{ margin: '0 12px', height: 1, background: 'var(--border)' }} />
<div style={{ padding: '6px 12px 2px', display: 'flex', flexDirection: 'column', gap: 4 }}>
{sec.type === 'prefs' && sec.lines.map((line, li) => (
<div key={li} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
<SectionIcon type="prefs" />
<span style={{ fontSize: 12, lineHeight: 1.4, flex: 1 }}>
<span style={{ color: 'var(--muted)', display: 'block', fontSize: 11 }}>{line.setName}</span>
<span style={{ color: 'var(--text)' }}>{line.values.join(' · ')}</span>
</span>
</div>
))}
{sec.type === 'quick' && sec.lines.map((line, li) => (
<div key={li} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
<SectionIcon type="quick" />
<span style={{ fontSize: 12, color: 'var(--text)', flex: 1 }}>
{line.name}
{line._qty > 1 && <span style={{ color: 'var(--x-warning)', marginLeft: 4, fontWeight: 700 }}>×{line._qty}</span>}
</span>
</div>
))}
{sec.type === 'extras' && sec.lines.map((line, li) => (
<div key={li} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
<SectionIcon type="extras" />
<span style={{ fontSize: 12, color: 'var(--text)', flex: 1 }}>
{line.name}
{line.subName && <span> · {line.subName}</span>}
{line.qty > 1 && <span style={{ color: 'var(--x-warning)', marginLeft: 4, fontWeight: 700 }}>×{line.qty}</span>}
</span>
</div>
))}
{sec.type === 'removed' && sec.lines.map((line, li) => (
<div key={li} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
<SectionIcon type="removed" />
<span style={{ fontSize: 12, color: 'var(--text)', flex: 1 }}>{t('drawer.without', { name: line.name })}</span>
</div>
))}
{sec.type === 'note' && sec.lines.map((line, li) => (
<div key={li} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
<SectionIcon type="note" />
<span style={{ fontSize: 12, color: 'var(--text)', lineHeight: 1.4, flex: 1, whiteSpace: 'pre-wrap' }}>{line.name}</span>
</div>
))}
</div>
</div>
))}
{/* ── Quick qty row — hidden for decimal-unit items (edit via modal instead) ── */}
{!_AI_UNIT_LABELS[product?.unit_type] && (<>
<div style={{ margin: '8px 12px 0', height: 1, background: 'var(--border)' }} />
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16,
padding: '10px 12px 2px',
}}>
<button
onClick={e => { e.stopPropagation(); onChangeQty(item.quantity - 1) }}
style={{
width: 36, height: 36, borderRadius: '50%',
background: 'var(--bg3)', border: '1px solid var(--border)',
color: item.quantity <= 1 ? 'var(--muted)' : 'var(--danger)',
fontSize: 20, fontWeight: 700, cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
>
{item.quantity <= 1 ? (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
) : '−'}
</button>
<span style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)', minWidth: 28, textAlign: 'center' }}>
{item.quantity}
</span>
<button
onClick={e => { e.stopPropagation(); onChangeQty(item.quantity + 1) }}
style={{
width: 36, height: 36, borderRadius: '50%',
background: 'var(--bg3)', border: '1px solid var(--border)',
color: 'var(--x-success)',
fontSize: 20, fontWeight: 700, cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
>+</button>
</div>
</>)}
</div>
)}
</div>
)
}
// ── Search Modal ──────────────────────────────────────────────────────────────
function SearchModal({ products, query, setQuery, onClose, onAdd, courses = [], quickNotes }) {
const { t } = useTranslation('waiter')
const mt = useMenuText() // 6R.L: shown in the waiter's language, found by either
const [drawerProduct, setDrawerProduct] = useState(null)
const activeProducts = products.filter(p => p.lifecycle_status !== 'archived')
const results = query.trim().length === 0
? []
: activeProducts.filter(p => mt.matches(p, query.trim().toLowerCase()))
function openProduct(p) {
// Blur the input first so the keyboard dismisses, then open the drawer
document.activeElement?.blur()
setDrawerProduct(p)
}
// The modal is position:fixed anchored to bottom:0.
// When the soft keyboard opens on mobile the browser shrinks the visual
// viewport and fixed elements reposition automatically — the panel sits
// right on top of the keyboard without any JS measurement needed.
return (
<>
{/* Dim backdrop — tap to close */}
<div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgb(var(--x-scrim-rgb) / 0.5)', zIndex: 200 }} />
{/* Panel: fixed to bottom, grows upward, capped at 60vh so results don't
push the input off screen on short viewports */}
<div style={{
position: 'fixed', left: 0, right: 0, bottom: 0,
zIndex: 201,
background: 'var(--bg)',
borderTop: '1px solid var(--border)',
display: 'flex', flexDirection: 'column',
maxHeight: '60vh',
}}>
{/* Results scroll area — flex:1 so it takes space above the input */}
<div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
{query.trim().length === 0 ? (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: '16px 20px', fontSize: 14 }}>
{t('add.search.type')}
</p>
) : results.length === 0 ? (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: '16px 20px', fontSize: 14 }}>
{t('add.search.none', { query })}
</p>
) : results.map(p => {
const initials = mt(p).trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
return (
<button
key={p.id}
onClick={() => openProduct(p)}
style={{
display: 'flex', alignItems: 'center', gap: 12,
width: '100%', padding: '10px 16px',
background: 'none', border: 'none', cursor: 'pointer',
borderBottom: '1px solid var(--border)',
textAlign: 'left',
}}
>
<div style={{
width: 40, height: 40, borderRadius: 10, flexShrink: 0,
background: 'var(--bg3)', overflow: 'hidden',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{p.image_url
? <img src={assetUrl(p.image_url)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--muted)' }}>{initials}</span>
}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{mt(p)}
</div>
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
{money(p.base_price)}
</div>
</div>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" style={{ color: 'var(--muted)', flexShrink: 0 }}>
<path d="M9 18l6-6-6-6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</button>
)
})}
</div>
{/* Search input — pinned at the bottom of the panel, above the keyboard */}
<div style={{
display: 'flex', alignItems: 'center', gap: 8,
padding: '10px 12px 12px',
borderTop: '1px solid var(--border)',
flexShrink: 0,
}}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" style={{ color: 'var(--muted)', flexShrink: 0 }}>
<circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2.2"/>
<path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
</svg>
<input
autoFocus
value={query}
onChange={e => setQuery(e.target.value)}
placeholder={t('add.search.placeholder')}
style={{
flex: 1, height: 44, background: 'var(--bg2)',
border: '1px solid var(--border)', borderRadius: 12,
padding: '0 12px', fontSize: 16, color: 'var(--text)',
fontFamily: 'inherit', outline: 'none',
}}
/>
<button
onClick={onClose}
style={{
background: 'var(--bg3)', border: 'none', borderRadius: '50%',
width: 36, height: 36, flexShrink: 0,
display: 'flex', alignItems: 'center', justifyContent: 'center',
cursor: 'pointer', color: 'var(--text)',
}}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none">
<path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
</svg>
</button>
</div>
</div>
{/* Product drawer — closes search modal when item is added */}
{drawerProduct && (
<OrderDrawer
product={drawerProduct}
isOpen
onClose={() => setDrawerProduct(null)}
onAdd={item => { onAdd(item); setDrawerProduct(null); onClose() }}
courses={courses}
quickNotes={quickNotes}
/>
)}
</>
)
}