import { useState, useRef, useCallback, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../api/client'
import { LineError, wireLine } from '@xenia/api'
import ManagerOrderDrawer from './ManagerOrderDrawer'
// ── Constants ─────────────────────────────────────────────────────────────────
const FAV_CAT_ID = '__favorites__'
const SVC_CAT_ID = '__service__'
const DECIMAL_UNITS = new Set(['kg', 'liter', 'gram', 'ml'])
const DECIMAL_UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }
// ── Helpers ───────────────────────────────────────────────────────────────────
function productAllowsQuickAdd(product) {
if (!product.quick_add_enabled) return false
for (const ps of (product.preference_sets || [])) {
if (ps.default_choice_id == null) return false
}
return true
}
function buildQuickAddItem(product) {
const qty = DECIMAL_UNITS.has(product.unit_type) ? 1.0 : 1
const selectedOptions = []
for (const ps of (product.preference_sets || [])) {
const defaultChoice = ps.choices?.find(c => c.id === ps.default_choice_id)
if (defaultChoice) {
selectedOptions.push({ id: defaultChoice.id, name: defaultChoice.name, price_delta: defaultChoice.extra_cost ?? 0 })
}
}
return {
product_id: product.id,
quantity: qty,
unit_type: product.unit_type || 'piece',
unit_price: product.base_price,
notes: '',
selected_options: selectedOptions,
removed_ingredients: [],
}
}
function fmtQty(qty, unitType) {
const label = DECIMAL_UNIT_LABELS[unitType]
if (!label) return `×${qty}`
if (unitType === 'kg' || unitType === 'liter') return `${Number(qty).toFixed(1)}${label}`
return `${qty}${label}`
}
function hexToRgba(hex, alpha) {
if (!hex) return null
const h = hex.replace('#', '')
const r = parseInt(h.substring(0, 2), 16)
const g = parseInt(h.substring(2, 4), 16)
const b = parseInt(h.substring(4, 6), 16)
return `rgba(${r},${g},${b},${alpha})`
}
function buildSections(parent, subcategories, directProducts) {
const sections = []
if (directProducts.length > 0) {
sections.push({ _isGeneral: true, sort_order: parent.general_sort_order, products: directProducts })
}
for (const sub of subcategories) {
sections.push({ ...sub, _isGeneral: false, sort_order: sub.sort_order })
}
return sections.sort((a, b) => a.sort_order - b.sort_order)
}
// ── Product card for the desktop grid ─────────────────────────────────────────
function DesktopProductCard({ product, onOpen, onQuickAdd }) {
const canQuickAdd = productAllowsQuickAdd(product)
const initials = product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
return (
onOpen(product)}
style={{
background: 'white',
border: '1px solid #e2e8f0',
borderRadius: 12,
overflow: 'hidden',
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
transition: 'box-shadow 120ms ease, border-color 120ms ease',
position: 'relative',
}}
onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)'; e.currentTarget.style.borderColor = '#cbd5e1' }}
onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.borderColor = '#e2e8f0' }}
>
{/* Thumbnail */}
{product.image_url
?

:
{initials}
}
{/* Info */}
{product.name}
{product.tags?.length > 0 && (
{product.tags.slice(0, 2).map(tag => (
{tag}
))}
)}
{Number(product.base_price).toFixed(2)} €
{canQuickAdd && (
)}
)
}
// ── Service item widget ───────────────────────────────────────────────────────
function ServiceItemWidget({ product, customerCount, onAdd }) {
const [qty, setQty] = useState(0)
const hasPrice = product.base_price != null && product.base_price > 0
return (
{product.name}
{hasPrice ? `${Number(product.base_price).toFixed(2)} €` : 'no charge'}
{qty}
)
}
// ── Cart item row ─────────────────────────────────────────────────────────────
function CartItemRow({ item, product, onRemove, onChangeQty, onEdit }) {
const isDecimal = DECIMAL_UNITS.has(product?.unit_type)
const optionSummary = item.selected_options?.length
? item.selected_options.map(o => o.name).join(', ')
: null
return (
{product?.name ?? `#${item.product_id}`}
{optionSummary && (
{optionSummary}
)}
{item.notes && (
{item.notes}
)}
{/* Qty controls */}
{isDecimal ? (
) : (
{item.quantity}
)}
{/* Price */}
€{((item.unit_price ?? 0) * item.quantity + (item.price_adjustment ?? 0) * item.quantity).toFixed(2)}
{/* Edit + Remove */}
)
}
// ── Search overlay ────────────────────────────────────────────────────────────
function SearchOverlay({ products, onClose, onOpen }) {
const [query, setQuery] = useState('')
const inputRef = useRef(null)
useEffect(() => {
inputRef.current?.focus()
function onKey(e) { if (e.key === 'Escape') onClose() }
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const activeProducts = products.filter(p => p.lifecycle_status !== 'archived')
const results = query.trim().length === 0
? []
: activeProducts.filter(p => p.name.toLowerCase().includes(query.trim().toLowerCase()))
return (
<>
{/* Input */}
{/* Results */}
{query.trim().length === 0 ? (
Πληκτρολογήστε για αναζήτηση…
) : results.length === 0 ? (
Δεν βρέθηκαν προϊόντα για «{query}»
) : results.map(p => {
const initials = p.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
return (
)
})}
>
)
}
// ── Main component ────────────────────────────────────────────────────────────
export default function DesktopOrderingTab({ orderId, tableId, orderStatus }) {
const qc = useQueryClient()
const { data: productsData, isLoading: productsLoading } = useQuery({
queryKey: ['products-ordering'],
queryFn: async () => {
const [prodRes, catRes] = await Promise.all([
client.get('/api/products/'),
client.get('/api/products/categories'),
])
return { products: prodRes.data, categories: catRes.data }
},
staleTime: 5 * 60 * 1000,
})
const products = productsData?.products ?? []
const categories = productsData?.categories ?? []
const serviceProducts = products.filter(p => p.is_service_item)
const regularProducts = products.filter(p => !p.is_service_item || p.category_id)
const topLevel = categories.filter(c => !c.parent_id).sort((a, b) => a.sort_order - b.sort_order)
const initialCatId = topLevel[0]?.id ?? null
const [activeCat, setActiveCat] = useState(null)
const [viewAllOpen, setViewAllOpen] = useState(false)
const [searchOpen, setSearchOpen] = useState(false)
const [expandedSubs, setExpandedSubs] = useState({})
// Drawer for product customization
const [drawerProduct, setDrawerProduct] = useState(null)
const [editItem, setEditItem] = useState(null) // { cartKey, product, drawerState }
// Cart
const [cart, setCart] = useState([])
const [orderNote, setOrderNote] = useState('')
const [sending, setSending] = useState(false)
// Customer count (loaded from order)
const { data: orderData } = useQuery({
queryKey: ['order', orderId],
queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data),
enabled: !!orderId,
staleTime: 30_000,
})
const customerCount = orderData?.customer_count ?? null
// Courses settings
const { data: posSettings } = useQuery({
queryKey: ['pos-settings-courses'],
queryFn: () => client.get('/api/settings/').then(r => r.data),
staleTime: 60_000,
})
const coursesEnabled = posSettings?.['orders.courses_enabled']?.value === 'true'
const courses = coursesEnabled ? (() => { try { return JSON.parse(posSettings?.['orders.courses']?.value || '[]') } catch { return [] } })() : []
// Set initial category once products load
useEffect(() => {
if (activeCat === null && topLevel.length > 0) {
const firstId = serviceProducts.length > 0 ? SVC_CAT_ID : topLevel[0]?.id
setActiveCat(firstId ?? null)
}
}, [topLevel.length, serviceProducts.length])
function buildDefaultExpanded(catId) {
const subs = categories.filter(c => c.parent_id === catId)
const state = {}
subs.forEach(s => { if (s.auto_expanded) state[String(s.id)] = true })
return state
}
function selectCategory(id) {
setActiveCat(id)
setViewAllOpen(false)
setExpandedSubs(id === FAV_CAT_ID || id === SVC_CAT_ID ? {} : buildDefaultExpanded(id))
}
const isSvcActive = activeCat === SVC_CAT_ID
const activeParent = categories.find(c => c.id === activeCat)
const subcategories = activeParent
? categories.filter(c => c.parent_id === activeCat).sort((a, b) => a.sort_order - b.sort_order)
: []
const hasSubcats = subcategories.length > 0
const directProducts = regularProducts.filter(p => p.category_id === activeCat)
const sections = hasSubcats ? buildSections(activeParent, subcategories, directProducts) : []
// Cart management
function addToCart(item) {
setCart(prev => {
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(product) {
const base = buildQuickAddItem(product)
const item = product.is_service_item ? { ...base, is_service_item: true } : base
addToCart(item)
toast.success(`${product.name} προστέθηκε`, { duration: 800 })
}
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
setEditItem({ cartKey: cartItem._key, product, drawerState: cartItem._drawerState })
setDrawerProduct(null)
}
function handleDrawerAdd(item) {
if (editItem) {
setCart(prev => prev.map(i => i._key === editItem.cartKey ? { ...item, _key: i._key } : i))
setEditItem(null)
} else {
const finalItem = drawerProduct?.is_service_item ? { ...item, is_service_item: true } : item
addToCart(finalItem)
setDrawerProduct(null)
}
}
const cartTotal = cart.reduce((s, i) => s + (i.unit_price ?? 0) * i.quantity + (i.price_adjustment ?? 0) * i.quantity, 0)
const isOpen = ['open', 'partially_paid'].includes(orderStatus)
const addItemsMutation = useMutation({
mutationFn: async () => {
let activeOrderId = orderId
if (!activeOrderId) {
const { data: newOrder } = await client.post('/api/orders/', { table_id: tableId })
activeOrderId = newOrder.id
}
// what was chosen, by id: the server prices it (plan step 4.4)
const res = await client.post(`/api/orders/${activeOrderId}/items`, {
lines: cart.map(({ _key, _drawerState, ...item }) => wireLine(item, products.find(p => p.id === item.product_id))),
order_note: orderNote || null,
})
return res.data
},
onSuccess: (data) => {
const printResults = data.print_results ?? []
const allOk = printResults.length === 0 || printResults.every(r => r.success)
if (!allOk) {
toast.error('Παραγγελία αποθηκεύτηκε αλλά κάποιος εκτυπωτής δεν ανταποκρίθηκε')
} else {
toast.success('Παραγγελία εστάλη επιτυχώς')
}
setCart([])
setOrderNote('')
qc.invalidateQueries({ queryKey: ['order', orderId] })
qc.invalidateQueries({ queryKey: ['orders-active'] })
},
onError: (err) => {
toast.error(err instanceof LineError
? `«${err.product}»: το «${err.what}» δεν υπάρχει πια στο μενού`
: err?.response?.data?.detail || 'Σφάλμα αποστολής παραγγελίας')
},
})
// Keyboard shortcut for search
useEffect(() => {
function onKey(e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'f') { e.preventDefault(); setSearchOpen(true) }
if (e.key === 'Escape') { setDrawerProduct(null); setEditItem(null); setSearchOpen(false) }
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [])
if (productsLoading) {
return (
Φόρτωση προϊόντων…
)
}
if (!isOpen) {
return (
Η παραγγελία δεν είναι ανοιχτή.
)
}
const activeDrawerProduct = editItem ? editItem.product : drawerProduct
const drawerOpen = !!activeDrawerProduct
return (
{/* ── LEFT: Category + Product browser ─────────────────────────────── */}
{/* Toolbar */}
{/* SERVICE chip */}
{serviceProducts.length > 0 && (
)}
{topLevel.map(cat => {
const isActive = activeCat === cat.id
const bg = cat.color
? isActive ? cat.color : hexToRgba(cat.color, 0.15)
: isActive ? '#f59e0b' : '#f8fafc'
const color = cat.color
? isActive ? '#fff' : cat.color
: isActive ? '#fff' : '#64748b'
return (
)
})}
{/* Product area */}
{isSvcActive ? (
{serviceProducts.map(p => (
addToCart(item)} />
))}
) : !hasSubcats ? (
<>
{directProducts.map(p => (
))}
{directProducts.length === 0 && (
Δεν υπάρχουν προϊόντα
)}
>
) : (
{sections.map(section => {
const key = section._isGeneral ? '__general__' : String(section.id)
const isExpanded = !!expandedSubs[key]
const sectionProducts = section._isGeneral
? section.products
: regularProducts.filter(p => p.category_id === section.id)
if (sectionProducts.length === 0) return null
if (section._isGeneral) {
return (
{sectionProducts.map(p => (
))}
)
}
const accentColor = section.color ?? activeParent?.color ?? null
return (
{isExpanded && (
{sectionProducts.map(p => (
))}
)}
)
})}
)}
{/* ── RIGHT: Cart panel or Drawer panel ────────────────────────────── */}
{drawerOpen ? (
{ setDrawerProduct(null); setEditItem(null) }}
onAdd={handleDrawerAdd}
courses={courses}
/>
) : (
/* Cart */
{/* Cart header */}
Νέα Παραγγελία
{cart.length === 0 ? 'Επιλέξτε προϊόντα από τα αριστερά' : `${cart.length} ${cart.length === 1 ? 'προϊόν' : 'προϊόντα'}`}
{/* Item list */}
{cart.length === 0 ? (
) : (
{cart.map(item => {
const product = products.find(p => p.id === item.product_id)
return (
removeFromCart(item._key)}
onChangeQty={qty => changeCartQty(item._key, qty)}
onEdit={() => openEditDrawer(item)}
/>
)
})}
)}
{/* Order note */}
{cart.length > 0 && (
)}
{/* Cart footer */}
{cart.length > 0 && (
Σύνολο
€{cartTotal.toFixed(2)}
)}
{cart.length > 0 && (
)}
)}
{/* View all categories modal */}
{viewAllOpen && (
<>
setViewAllOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 200 }} />
Κατηγορίες
{serviceProducts.length > 0 && (
)}
{topLevel.map(cat => {
const isActive = activeCat === cat.id
return (
)
})}
>
)}
{/* Search modal */}
{searchOpen && (
setSearchOpen(false)}
onOpen={p => { setDrawerProduct(p); setSearchOpen(false) }}
/>
)}
)
}