feat: tables and orders in the manager on v2 (platform-v2 step 6.9)
- manager: new pages/orders/ (Tables page cards + quick actions, order page with
lines, multi-select pay/discount/cancel/tab, staff + customer, price changes,
history, the menu + cart beside it); a free table opens a new order on first
Send; v1 TablesPage, OrderDetailPage, DesktopOrderingTab, ManagerOrderDrawer
and PaymentMethodModal removed
- ordering by line id like the phones: GET /api/orders/menu (the counter's
product shape, in-store prices); the product dialog, cart rules and quote hook
move to packages/ordering (@xenia/ordering), shared by counter, menu tablet,
manager
- close follows orders.close_with_unpaid (pay first, or write off after saying
so) on the order page and the overview's quick view; paying asks cash or card
- a confirmed booking can keep its table ahead (manager, phones, counter):
POST /api/connect/bookings/{id}/table, reservations create/PATCH; refused with
reservation.table_kept within 2 h of another booking
- tests: test_manager_ordering.py, online bookings +2, manager orders.test.mjs,
@xenia/ordering, e2e manager.mjs (take, change, pay-first close, RESERVED)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -14,8 +14,8 @@ import SetupWizard from './pages/SetupWizard'
|
||||
|
||||
// Operation
|
||||
import OverviewPage from './pages/overview/OverviewPage'
|
||||
import TablesPage from './pages/TablesPage'
|
||||
import OrderDetailPage from './pages/OrderDetailPage'
|
||||
import TablesPage from './pages/orders/TablesPage'
|
||||
import OrderPage from './pages/orders/OrderPage'
|
||||
import OnlineOrdersPage from './pages/online/OnlineOrdersPage'
|
||||
import FeesPage from './pages/online/FeesPage'
|
||||
import QrCodesPage from './pages/online/QrCodesPage'
|
||||
@@ -151,7 +151,7 @@ export default function App() {
|
||||
<Route path="online-orders" element={<OnlineOrdersPage />} />
|
||||
<Route path="online/fees" element={<FeesPage />} />
|
||||
<Route path="online/qr" element={<QrCodesPage />} />
|
||||
<Route path="orders/:orderId" element={<OrderDetailPage />} />
|
||||
<Route path="orders/:orderId" element={<OrderPage />} />
|
||||
|
||||
{/* ── CRM ── */}
|
||||
<Route path="crm/contacts" element={<ContactsPage />} />
|
||||
|
||||
@@ -1,843 +0,0 @@
|
||||
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 (
|
||||
<div
|
||||
onClick={() => 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 */}
|
||||
<div style={{
|
||||
width: '100%', aspectRatio: '16/9', maxHeight: 80,
|
||||
background: '#f1f5f9', overflow: 'hidden',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
flexShrink: 0,
|
||||
}}>
|
||||
{product.image_url
|
||||
? <img src={product.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
|
||||
: <span style={{ fontSize: 22, fontWeight: 700, color: '#94a3b8', letterSpacing: -1 }}>{initials}</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div style={{ padding: '8px 10px 10px', flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', lineHeight: 1.3, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
|
||||
{product.name}
|
||||
</div>
|
||||
{product.tags?.length > 0 && (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 3 }}>
|
||||
{product.tags.slice(0, 2).map(tag => (
|
||||
<span key={tag} style={{ fontSize: 10, fontWeight: 600, padding: '1px 6px', background: '#f1f5f9', borderRadius: 99, color: '#64748b', border: '1px solid #e2e8f0' }}>{tag}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'auto' }}>
|
||||
<span style={{ fontSize: 14, fontWeight: 700, color: '#f59e0b' }}>{Number(product.base_price).toFixed(2)} €</span>
|
||||
{canQuickAdd && (
|
||||
<button
|
||||
onClick={e => { e.stopPropagation(); onQuickAdd(product) }}
|
||||
style={{
|
||||
width: 30, height: 30, borderRadius: '50%',
|
||||
background: '#fff7ed', border: '1.5px solid #fed7aa',
|
||||
cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: '#f59e0b',
|
||||
}}
|
||||
>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2.8" strokeLinecap="round"/>
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Service item widget ───────────────────────────────────────────────────────
|
||||
|
||||
function ServiceItemWidget({ product, customerCount, onAdd }) {
|
||||
const [qty, setQty] = useState(0)
|
||||
const hasPrice = product.base_price != null && product.base_price > 0
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
background: 'white', border: '1px solid #e2e8f0', borderRadius: 12,
|
||||
padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 8,
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<span style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', flex: 1, minWidth: 0 }}>{product.name}</span>
|
||||
<span style={{ fontSize: 12, color: hasPrice ? '#f59e0b' : '#94a3b8', fontWeight: 600, flexShrink: 0 }}>
|
||||
{hasPrice ? `${Number(product.base_price).toFixed(2)} €` : 'no charge'}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<button onClick={() => setQty(q => Math.max(0, q - 1))}
|
||||
style={{ width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0', background: qty === 0 ? '#f8fafc' : 'rgba(245,158,11,0.1)', color: qty === 0 ? '#94a3b8' : '#f59e0b', fontSize: 18, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>−</button>
|
||||
<button onClick={() => setQty(Math.max(1, customerCount ?? 1))} title={`Ορισμός σε ${customerCount ?? 1}`}
|
||||
style={{ width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0', background: 'rgba(245,158,11,0.1)', color: '#f59e0b', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/>
|
||||
<path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button onClick={() => setQty(q => q + 1)}
|
||||
style={{ width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0', background: 'rgba(245,158,11,0.1)', color: '#f59e0b', fontSize: 18, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>+</button>
|
||||
<span style={{ fontSize: 20, fontWeight: 800, color: qty === 0 ? '#94a3b8' : '#1e293b', flex: 1, textAlign: 'center' }}>{qty}</span>
|
||||
<button
|
||||
disabled={qty === 0}
|
||||
onClick={() => {
|
||||
if (qty === 0) return
|
||||
onAdd({
|
||||
product_id: product.id,
|
||||
quantity: qty,
|
||||
unit_type: 'piece',
|
||||
unit_price: product.base_price ?? 0,
|
||||
notes: '',
|
||||
selected_options: [],
|
||||
removed_ingredients: [],
|
||||
is_service_item: true,
|
||||
})
|
||||
setQty(0)
|
||||
}}
|
||||
style={{
|
||||
padding: '6px 14px', borderRadius: 8, border: 'none',
|
||||
background: qty === 0 ? '#f1f5f9' : '#f59e0b',
|
||||
color: qty === 0 ? '#94a3b8' : '#fff',
|
||||
fontSize: 12, fontWeight: 700, cursor: qty === 0 ? 'default' : 'pointer',
|
||||
}}
|
||||
>ADD</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── 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 (
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '8px 0', borderBottom: '1px solid #f1f5f9' }}>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{product?.name ?? `#${item.product_id}`}
|
||||
</div>
|
||||
{optionSummary && (
|
||||
<div style={{ fontSize: 11, color: '#94a3b8', marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{optionSummary}
|
||||
</div>
|
||||
)}
|
||||
{item.notes && (
|
||||
<div style={{ fontSize: 11, color: '#f59e0b', marginTop: 1, fontStyle: 'italic', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{item.notes}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Qty controls */}
|
||||
{isDecimal ? (
|
||||
<button onClick={onEdit} style={{ fontSize: 12, fontWeight: 700, color: '#f59e0b', background: '#fff7ed', border: '1px solid #fed7aa', borderRadius: 6, padding: '2px 8px', cursor: 'pointer', whiteSpace: 'nowrap' }}>
|
||||
{fmtQty(item.quantity, product?.unit_type)}
|
||||
</button>
|
||||
) : (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
|
||||
<button onClick={() => onChangeQty(item.quantity - 1)}
|
||||
style={{ width: 24, height: 24, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f8fafc', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: item.quantity <= 1 ? '#ef4444' : '#475569', fontSize: 14, fontWeight: 700 }}>
|
||||
{item.quantity <= 1
|
||||
? <svg width="10" height="10" 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: 13, fontWeight: 700, color: '#1e293b', minWidth: 16, textAlign: 'center' }}>{item.quantity}</span>
|
||||
<button onClick={() => onChangeQty(item.quantity + 1)}
|
||||
style={{ width: 24, height: 24, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f8fafc', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#16a34a', fontSize: 14, fontWeight: 700 }}>+</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Price */}
|
||||
<span style={{ fontSize: 13, fontWeight: 700, color: '#475569', minWidth: 50, textAlign: 'right', flexShrink: 0 }}>
|
||||
€{((item.unit_price ?? 0) * item.quantity + (item.price_adjustment ?? 0) * item.quantity).toFixed(2)}
|
||||
</span>
|
||||
|
||||
{/* Edit + Remove */}
|
||||
<div style={{ display: 'flex', gap: 3, flexShrink: 0 }}>
|
||||
<button onClick={onEdit}
|
||||
style={{ padding: '2px 7px', borderRadius: 6, border: '1px solid #e2e8f0', background: '#f8fafc', color: '#64748b', fontSize: 11, cursor: 'pointer' }}>
|
||||
Επεξ.
|
||||
</button>
|
||||
<button onClick={onRemove}
|
||||
style={{ width: 24, height: 24, borderRadius: '50%', border: 'none', background: 'none', color: '#94a3b8', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
<svg width="13" height="13" 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>
|
||||
)
|
||||
}
|
||||
|
||||
// ── 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 (
|
||||
<>
|
||||
<div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 200 }} />
|
||||
<div style={{
|
||||
position: 'fixed', top: '15%', left: '50%', transform: 'translateX(-50%)',
|
||||
zIndex: 201, width: 'min(580px, 90vw)',
|
||||
background: 'white', borderRadius: 16,
|
||||
boxShadow: '0 20px 60px rgba(0,0,0,0.18)',
|
||||
overflow: 'hidden', display: 'flex', flexDirection: 'column',
|
||||
maxHeight: '60vh',
|
||||
}}>
|
||||
{/* Input */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderBottom: '1px solid #e2e8f0', flexShrink: 0 }}>
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" style={{ color: '#94a3b8', 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
|
||||
ref={inputRef}
|
||||
value={query}
|
||||
onChange={e => setQuery(e.target.value)}
|
||||
placeholder="Αναζήτηση προϊόντος…"
|
||||
style={{ flex: 1, border: 'none', outline: 'none', fontSize: 16, color: '#1e293b', background: 'transparent', fontFamily: 'inherit' }}
|
||||
/>
|
||||
<button onClick={onClose} style={{ background: '#f1f5f9', border: 'none', borderRadius: '50%', width: 30, height: 30, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: '#64748b' }}>
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Results */}
|
||||
<div style={{ flex: 1, overflowY: 'auto' }}>
|
||||
{query.trim().length === 0 ? (
|
||||
<p style={{ textAlign: 'center', color: '#94a3b8', padding: '20px', fontSize: 14 }}>Πληκτρολογήστε για αναζήτηση…</p>
|
||||
) : results.length === 0 ? (
|
||||
<p style={{ textAlign: 'center', color: '#94a3b8', padding: '20px', fontSize: 14 }}>Δεν βρέθηκαν προϊόντα για «{query}»</p>
|
||||
) : results.map(p => {
|
||||
const initials = p.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
|
||||
return (
|
||||
<button key={p.id} onClick={() => { onOpen(p); onClose() }}
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '10px 16px', background: 'none', border: 'none', cursor: 'pointer', borderBottom: '1px solid #f1f5f9', textAlign: 'left' }}
|
||||
onMouseEnter={e => { e.currentTarget.style.background = '#f8fafc' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.background = 'none' }}
|
||||
>
|
||||
<div style={{ width: 38, height: 38, borderRadius: 8, flexShrink: 0, background: '#f1f5f9', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
{p.image_url
|
||||
? <img src={p.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
|
||||
: <span style={{ fontSize: 12, fontWeight: 700, color: '#94a3b8' }}>{initials}</span>
|
||||
}
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 600, color: '#1e293b', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</div>
|
||||
<div style={{ fontSize: 12, color: '#94a3b8', marginTop: 1 }}>{Number(p.base_price).toFixed(2)} €</div>
|
||||
</div>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ color: '#cbd5e1', flexShrink: 0 }}>
|
||||
<path d="M9 18l6-6-6-6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
|
||||
</svg>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// ── 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 (
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200, color: '#94a3b8', fontSize: 14 }}>
|
||||
Φόρτωση προϊόντων…
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!isOpen) {
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200, color: '#94a3b8', fontSize: 14 }}>
|
||||
Η παραγγελία δεν είναι ανοιχτή.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const activeDrawerProduct = editItem ? editItem.product : drawerProduct
|
||||
const drawerOpen = !!activeDrawerProduct
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', height: '100%', minHeight: 0, gap: 0 }}>
|
||||
|
||||
{/* ── LEFT: Category + Product browser ─────────────────────────────── */}
|
||||
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, borderRight: '1px solid #e2e8f0' }}>
|
||||
|
||||
{/* Toolbar */}
|
||||
<div style={{ padding: '10px 12px', borderBottom: '1px solid #e2e8f0', display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0, background: '#f8fafc' }}>
|
||||
<div style={{ flex: 1, display: 'flex', gap: 6, overflowX: 'auto', scrollbarWidth: 'none' }}>
|
||||
{/* SERVICE chip */}
|
||||
{serviceProducts.length > 0 && (
|
||||
<button onClick={() => selectCategory(SVC_CAT_ID)}
|
||||
style={{
|
||||
height: 32, padding: '0 14px', borderRadius: 16, border: isSvcActive ? '2px solid #f59e0b' : '1px solid #e2e8f0',
|
||||
background: isSvcActive ? '#f59e0b' : '#fff7ed', color: isSvcActive ? '#fff' : '#d97706',
|
||||
fontSize: 12, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap',
|
||||
display: 'flex', alignItems: 'center', gap: 4,
|
||||
}}
|
||||
>
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M3 11l19-9-9 19-2-8-8-2z"/>
|
||||
</svg>
|
||||
Service
|
||||
</button>
|
||||
)}
|
||||
{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 (
|
||||
<button key={cat.id} onClick={() => selectCategory(cat.id)}
|
||||
style={{
|
||||
height: 32, padding: '0 14px', borderRadius: 16,
|
||||
border: isActive && cat.color ? `2px solid ${cat.color}` : isActive ? '2px solid #f59e0b' : '1px solid #e2e8f0',
|
||||
background: bg, color,
|
||||
fontSize: 12, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap',
|
||||
}}
|
||||
>{cat.name}</button>
|
||||
)
|
||||
})}
|
||||
<button onClick={() => setViewAllOpen(true)}
|
||||
style={{ height: 32, padding: '0 12px', borderRadius: 16, border: '1px solid #e2e8f0', background: '#f8fafc', color: '#64748b', fontSize: 12, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0 }}>
|
||||
Όλες →
|
||||
</button>
|
||||
</div>
|
||||
<button onClick={() => setSearchOpen(true)}
|
||||
style={{ height: 32, padding: '0 12px', borderRadius: 16, border: '1px solid #e2e8f0', background: '#f8fafc', color: '#64748b', fontSize: 12, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0 }}>
|
||||
<svg width="13" height="13" 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>
|
||||
</div>
|
||||
|
||||
{/* Product area */}
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: '12px 14px' }}>
|
||||
|
||||
{isSvcActive ? (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 10 }}>
|
||||
{serviceProducts.map(p => (
|
||||
<ServiceItemWidget key={p.id} product={p} customerCount={customerCount} onAdd={item => addToCart(item)} />
|
||||
))}
|
||||
</div>
|
||||
) : !hasSubcats ? (
|
||||
<>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
|
||||
{directProducts.map(p => (
|
||||
<DesktopProductCard key={p.id} product={p} onOpen={setDrawerProduct} onQuickAdd={handleQuickAdd} />
|
||||
))}
|
||||
</div>
|
||||
{directProducts.length === 0 && (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0', fontSize: 14 }}>Δεν υπάρχουν προϊόντα</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{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 (
|
||||
<div key={key}>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
|
||||
{sectionProducts.map(p => (
|
||||
<DesktopProductCard key={p.id} product={p} onOpen={setDrawerProduct} onQuickAdd={handleQuickAdd} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const accentColor = section.color ?? activeParent?.color ?? null
|
||||
return (
|
||||
<div key={key} style={{ border: '1px solid #e2e8f0', borderRadius: 12, overflow: 'hidden' }}>
|
||||
<button
|
||||
onClick={() => setExpandedSubs(prev => ({ ...prev, [key]: !prev[key] }))}
|
||||
style={{
|
||||
width: '100%', padding: '10px 14px', background: isExpanded ? '#f8fafc' : 'white',
|
||||
border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8, textAlign: 'left',
|
||||
}}
|
||||
>
|
||||
{accentColor && <span style={{ width: 10, height: 10, borderRadius: '50%', background: accentColor, flexShrink: 0 }} />}
|
||||
<span style={{ flex: 1, fontSize: 13, fontWeight: 700, color: '#1e293b' }}>{section.name}</span>
|
||||
<span style={{ fontSize: 11, color: '#94a3b8', marginRight: 4 }}>{sectionProducts.length}</span>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ transform: `rotate(${isExpanded ? 180 : 0}deg)`, transition: 'transform 180ms', color: '#94a3b8', flexShrink: 0 }}>
|
||||
<path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
|
||||
</svg>
|
||||
</button>
|
||||
{isExpanded && (
|
||||
<div style={{ padding: '10px 12px 12px', background: '#fafbfc', borderTop: '1px solid #f1f5f9' }}>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
|
||||
{sectionProducts.map(p => (
|
||||
<DesktopProductCard key={p.id} product={p} onOpen={setDrawerProduct} onQuickAdd={handleQuickAdd} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── RIGHT: Cart panel or Drawer panel ────────────────────────────── */}
|
||||
<div style={{ width: 320, flexShrink: 0, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
|
||||
{drawerOpen ? (
|
||||
<ManagerOrderDrawer
|
||||
key={activeDrawerProduct.id}
|
||||
product={activeDrawerProduct}
|
||||
initialState={editItem?.drawerState}
|
||||
onClose={() => { setDrawerProduct(null); setEditItem(null) }}
|
||||
onAdd={handleDrawerAdd}
|
||||
courses={courses}
|
||||
/>
|
||||
) : (
|
||||
/* Cart */
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#f8fafc' }}>
|
||||
{/* Cart header */}
|
||||
<div style={{ padding: '12px 16px', borderBottom: '1px solid #e2e8f0', flexShrink: 0 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 700, color: '#1e293b' }}>Νέα Παραγγελία</div>
|
||||
<div style={{ fontSize: 12, color: '#94a3b8', marginTop: 1 }}>
|
||||
{cart.length === 0 ? 'Επιλέξτε προϊόντα από τα αριστερά' : `${cart.length} ${cart.length === 1 ? 'προϊόν' : 'προϊόντα'}`}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Item list */}
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: '0 16px' }}>
|
||||
{cart.length === 0 ? (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: 12, padding: '40px 0' }}>
|
||||
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" style={{ color: '#e2e8f0' }}>
|
||||
<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="1.5" strokeLinecap="round" strokeLinejoin="round"/>
|
||||
</svg>
|
||||
<p style={{ color: '#cbd5e1', fontSize: 13, textAlign: 'center' }}>Το καλάθι είναι άδειο</p>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{cart.map(item => {
|
||||
const product = products.find(p => p.id === item.product_id)
|
||||
return (
|
||||
<CartItemRow
|
||||
key={item._key}
|
||||
item={item}
|
||||
product={product}
|
||||
onRemove={() => removeFromCart(item._key)}
|
||||
onChangeQty={qty => changeCartQty(item._key, qty)}
|
||||
onEdit={() => openEditDrawer(item)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Order note */}
|
||||
{cart.length > 0 && (
|
||||
<div style={{ padding: '8px 16px', flexShrink: 0 }}>
|
||||
<textarea
|
||||
value={orderNote}
|
||||
onChange={e => setOrderNote(e.target.value)}
|
||||
placeholder="Σημείωση παραγγελίας (προαιρετικό)…"
|
||||
rows={2}
|
||||
style={{
|
||||
width: '100%', resize: 'none', padding: '8px 10px',
|
||||
background: 'white', border: '1px solid #e2e8f0',
|
||||
borderRadius: 8, fontSize: 12, color: '#1e293b', lineHeight: 1.5,
|
||||
outline: 'none', boxSizing: 'border-box', fontFamily: 'inherit',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Cart footer */}
|
||||
<div style={{ padding: '10px 16px 16px', borderTop: '1px solid #e2e8f0', flexShrink: 0, background: 'white' }}>
|
||||
{cart.length > 0 && (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
|
||||
<span style={{ fontSize: 13, color: '#64748b', fontWeight: 600 }}>Σύνολο</span>
|
||||
<span style={{ fontSize: 18, fontWeight: 800, color: '#1e293b' }}>€{cartTotal.toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
onClick={() => addItemsMutation.mutate()}
|
||||
disabled={cart.length === 0 || addItemsMutation.isPending}
|
||||
style={{
|
||||
width: '100%', height: 44, borderRadius: 22,
|
||||
background: cart.length === 0 ? '#e2e8f0' : '#f59e0b',
|
||||
border: 'none', color: cart.length === 0 ? '#94a3b8' : '#fff',
|
||||
fontSize: 15, fontWeight: 700, fontFamily: 'inherit',
|
||||
cursor: cart.length === 0 ? 'default' : 'pointer',
|
||||
transition: 'background 150ms ease',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
|
||||
}}
|
||||
>
|
||||
{addItemsMutation.isPending ? 'Αποστολή…' : `ΑΠΟΣΤΟΛΗ${cart.length > 0 ? ` (${cart.length})` : ''}`}
|
||||
</button>
|
||||
{cart.length > 0 && (
|
||||
<button onClick={() => setCart([])}
|
||||
style={{ width: '100%', marginTop: 6, padding: '6px 0', background: 'none', border: 'none', color: '#94a3b8', fontSize: 12, cursor: 'pointer' }}>
|
||||
Εκκαθάριση καλαθιού
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* View all categories modal */}
|
||||
{viewAllOpen && (
|
||||
<>
|
||||
<div onClick={() => setViewAllOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 200 }} />
|
||||
<div style={{
|
||||
position: 'fixed', top: '15%', left: '50%', transform: 'translateX(-50%)',
|
||||
zIndex: 201, width: 'min(500px, 90vw)',
|
||||
background: 'white', borderRadius: 16,
|
||||
boxShadow: '0 20px 60px rgba(0,0,0,0.18)',
|
||||
overflow: 'hidden',
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 18px', borderBottom: '1px solid #e2e8f0' }}>
|
||||
<span style={{ fontSize: 15, fontWeight: 700, color: '#1e293b' }}>Κατηγορίες</span>
|
||||
<button onClick={() => setViewAllOpen(false)} style={{ background: 'none', border: 'none', color: '#94a3b8', cursor: 'pointer', fontSize: 18 }}>✕</button>
|
||||
</div>
|
||||
<div style={{ padding: '14px 16px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, maxHeight: '60vh', overflowY: 'auto' }}>
|
||||
{serviceProducts.length > 0 && (
|
||||
<button onClick={() => { selectCategory(SVC_CAT_ID); setViewAllOpen(false) }}
|
||||
style={{ padding: '14px 10px', borderRadius: 12, background: '#fff7ed', border: isSvcActive ? '2px solid #f59e0b' : '1px solid #fed7aa', cursor: 'pointer', fontSize: 13, fontWeight: 700, color: '#d97706', textAlign: 'center' }}>
|
||||
Service
|
||||
</button>
|
||||
)}
|
||||
{topLevel.map(cat => {
|
||||
const isActive = activeCat === cat.id
|
||||
return (
|
||||
<button key={cat.id} onClick={() => { selectCategory(cat.id); setViewAllOpen(false) }}
|
||||
style={{
|
||||
padding: '14px 10px', borderRadius: 12, cursor: 'pointer', fontSize: 13, fontWeight: 700, textAlign: 'center',
|
||||
background: cat.color || '#f1f5f9',
|
||||
color: cat.color ? '#fff' : '#475569',
|
||||
border: isActive ? '2px solid #f59e0b' : '1px solid transparent',
|
||||
boxShadow: cat.color ? 'inset 0 0 0 100px rgba(0,0,0,0.15)' : 'none',
|
||||
}}>
|
||||
{cat.name}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Search modal */}
|
||||
{searchOpen && (
|
||||
<SearchOverlay
|
||||
products={products}
|
||||
onClose={() => setSearchOpen(false)}
|
||||
onOpen={p => { setDrawerProduct(p); setSearchOpen(false) }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,854 +0,0 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const DECIMAL_UNIT_CONFIG = {
|
||||
kg: { step: 0.05, min: 0.05, presets: [0.10, 0.20, 0.25, 0.50, 0.70, 1.00, 1.50, 2.00, 2.50, 3.00, 4.00, 5.00], offsets: [0.1, 0.2, 0.5, 1.0], label: 'kg' },
|
||||
liter: { step: 0.05, min: 0.05, presets: [0.10, 0.20, 0.25, 0.50, 0.70, 1.00, 1.50, 2.00, 2.50, 3.00, 4.00, 5.00], offsets: [0.1, 0.2, 0.5, 1.0], label: 'L' },
|
||||
gram: { step: 10, min: 10, presets: [50, 100, 150, 200, 250, 300, 400, 500], offsets: [10, 50, 100, 200], label: 'g' },
|
||||
ml: { step: 5, min: 5, presets: [25, 50, 100, 150, 200, 250, 300, 500], offsets: [25, 50, 100, 200], label: 'mL' },
|
||||
}
|
||||
|
||||
function fmtDecimalQty(qty, cfg) {
|
||||
if (!cfg) return String(qty)
|
||||
if (cfg.label === 'kg' || cfg.label === 'L') {
|
||||
const n = Number(qty)
|
||||
return n % 1 === 0 ? n.toFixed(1) : (Math.round(n * 100) / 100).toFixed(2).replace(/0$/, '')
|
||||
}
|
||||
return String(qty)
|
||||
}
|
||||
|
||||
function buildInitialState(product) {
|
||||
const preferenceSets = product.preference_sets || []
|
||||
const prefs = {}
|
||||
const subChoices = {}
|
||||
const sharedSubs = {}
|
||||
|
||||
preferenceSets.forEach(ps => {
|
||||
const def = ps.default_choice_id != null
|
||||
? ps.choices.find(c => c.id === ps.default_choice_id) ?? null
|
||||
: null
|
||||
prefs[ps.id] = def
|
||||
if (def) {
|
||||
if (def.sub_choices?.length > 0) {
|
||||
subChoices[def.id] = def.sub_choices.find(s => s.is_default) ?? def.sub_choices[0]
|
||||
}
|
||||
if (ps.shared_subset?.choices?.length > 0 && !def.disables_subset) {
|
||||
sharedSubs[ps.id] = ps.shared_subset.choices.find(s => s.is_default) ?? ps.shared_subset.choices[0]
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return { prefs, subChoices, sharedSubs }
|
||||
}
|
||||
|
||||
const QUICK_NOTES = ['Χωρίς αλάτι', 'Βγάλτε γρήγορα', 'Αλλεργία!', 'Κόψτε σε μικρά κομμάτια', 'Έξτρα χαρτοπετσέτες']
|
||||
const PRICE_DELTAS = [-5, -3, -2, -1, -0.5, -0.2, +0.2, +0.5, +1, +2, +3, +5]
|
||||
|
||||
// ── Primitive UI ──────────────────────────────────────────────────────────────
|
||||
|
||||
function CheckCircle({ selected }) {
|
||||
return (
|
||||
<div style={{
|
||||
width: 22, height: 22, borderRadius: '50%', flexShrink: 0,
|
||||
border: `2px solid ${selected ? '#f59e0b' : '#d1d5db'}`,
|
||||
background: selected ? '#f59e0b' : 'transparent',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
transition: 'all 120ms ease',
|
||||
}}>
|
||||
{selected && <svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M5 12.5L10 17.5L19 7.5" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RadioDot({ selected }) {
|
||||
return (
|
||||
<div style={{
|
||||
width: 20, height: 20, borderRadius: '50%', flexShrink: 0,
|
||||
border: `2px solid ${selected ? '#f59e0b' : '#d1d5db'}`,
|
||||
background: 'transparent',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
{selected && <div style={{ width: 9, height: 9, borderRadius: '50%', background: '#f59e0b' }} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Row({ selected, onClick, children, right, left }) {
|
||||
return (
|
||||
<div onClick={onClick} style={{
|
||||
padding: '10px 12px',
|
||||
background: selected ? 'rgba(245,158,11,0.08)' : '#f8fafc',
|
||||
border: `1px solid ${selected ? 'rgba(245,158,11,0.4)' : '#e2e8f0'}`,
|
||||
borderRadius: 10,
|
||||
display: 'flex', alignItems: 'center', gap: 10,
|
||||
cursor: onClick ? 'pointer' : 'default',
|
||||
transition: 'background 120ms ease, border-color 120ms ease',
|
||||
minHeight: 50,
|
||||
}}>
|
||||
{left && <div style={{ flexShrink: 0 }}>{left}</div>}
|
||||
<div style={{ flex: 1, minWidth: 0 }}>{children}</div>
|
||||
{right && <div style={{ flexShrink: 0 }}>{right}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Stepper({ value, onChange, min = 0, max = 99 }) {
|
||||
return (
|
||||
<div style={{ display: 'inline-flex', alignItems: 'center', height: 36, borderRadius: 18, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden' }}
|
||||
onClick={e => e.stopPropagation()}>
|
||||
<button onClick={() => onChange(Math.max(min, value - 1))} disabled={value <= min}
|
||||
style={{ width: 36, height: 36, border: 'none', background: 'transparent', fontSize: 16, fontWeight: 500, cursor: value <= min ? 'default' : 'pointer', color: value <= min ? '#94a3b8' : '#1e293b' }}>−</button>
|
||||
<div style={{ minWidth: 26, textAlign: 'center', fontSize: 14, fontWeight: 700, color: '#1e293b' }}>{value}</div>
|
||||
<button onClick={() => onChange(Math.min(max, value + 1))} disabled={value >= max}
|
||||
style={{ width: 36, height: 36, border: 'none', background: 'transparent', fontSize: 16, fontWeight: 500, cursor: value >= max ? 'default' : 'pointer', color: value >= max ? '#94a3b8' : '#1e293b' }}>+</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Option rows ───────────────────────────────────────────────────────────────
|
||||
|
||||
function QuickOptionRow({ opt, quickState, setQuickState }) {
|
||||
const qty = quickState[opt.id] || 0
|
||||
const selected = qty > 0
|
||||
return (
|
||||
<Row selected={selected} onClick={() => setQuickState(s => ({ ...s, [opt.id]: selected ? 0 : 1 }))}
|
||||
left={<CheckCircle selected={selected} />}
|
||||
right={opt.allow_multiple ? (
|
||||
<div onClick={e => e.stopPropagation()}>
|
||||
{selected
|
||||
? <Stepper value={qty} onChange={v => setQuickState(s => ({ ...s, [opt.id]: v }))} />
|
||||
: <button onClick={e => { e.stopPropagation(); setQuickState(s => ({ ...s, [opt.id]: 1 })) }}
|
||||
style={{ width: 30, height: 30, borderRadius: '50%', background: '#f1f5f9', border: '1px solid #e2e8f0', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/></svg>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
) : null}
|
||||
>
|
||||
<div style={{ fontSize: 14, fontWeight: 500, color: '#1e293b' }}>{opt.name}</div>
|
||||
{opt.price > 0 && <div style={{ fontSize: 12, color: '#64748b', marginTop: 1 }}>+{opt.price.toFixed(2)} €</div>}
|
||||
</Row>
|
||||
)
|
||||
}
|
||||
|
||||
function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) {
|
||||
const sel = extrasState[opt.id]
|
||||
const selected = !!sel
|
||||
const open = expandedExtra === opt.id
|
||||
const hasSubs = opt.sub_choices?.length > 0
|
||||
const subLabel = sel ? opt.sub_choices?.find(s => s.name === sel.subName)?.name : null
|
||||
|
||||
const toggle = () => {
|
||||
if (selected) {
|
||||
setExtrasState(s => { const n = { ...s }; delete n[opt.id]; return n })
|
||||
if (open) setExpandedExtra(null)
|
||||
} else {
|
||||
const firstSub = hasSubs ? opt.sub_choices[0] : null
|
||||
setExtrasState(s => ({ ...s, [opt.id]: { qty: 1, subName: firstSub?.name ?? null } }))
|
||||
if (hasSubs) setExpandedExtra(opt.id)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Row selected={selected} onClick={toggle}
|
||||
left={<CheckCircle selected={selected} />}
|
||||
right={
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }} onClick={e => e.stopPropagation()}>
|
||||
{selected && opt.allow_multiple && (
|
||||
<Stepper value={sel.qty} onChange={v => {
|
||||
if (v === 0) { setExtrasState(s => { const n = { ...s }; delete n[opt.id]; return n }); return }
|
||||
setExtrasState(s => ({ ...s, [opt.id]: { ...sel, qty: v } }))
|
||||
}} />
|
||||
)}
|
||||
{selected && hasSubs && (
|
||||
<button onClick={e => { e.stopPropagation(); setExpandedExtra(open ? null : opt.id) }}
|
||||
style={{ width: 30, height: 30, borderRadius: '50%', background: '#f1f5f9', border: '1px solid #e2e8f0', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" style={{ transform: `rotate(${open ? 180 : 0}deg)`, transition: 'transform 180ms' }}>
|
||||
<path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div style={{ fontSize: 14, fontWeight: 500, color: '#1e293b' }}>{opt.name}</div>
|
||||
<div style={{ fontSize: 12, color: '#64748b', marginTop: 1 }}>
|
||||
{(opt.extra_cost ?? 0) !== 0 ? `+${opt.extra_cost.toFixed(2)} €` : 'Included'}
|
||||
{subLabel && <span style={{ color: '#f59e0b', fontWeight: 600 }}> · {subLabel}</span>}
|
||||
</div>
|
||||
</Row>
|
||||
{selected && open && hasSubs && (
|
||||
<div style={{ margin: '5px 0 2px 14px', paddingLeft: 12, borderLeft: '2px solid rgba(245,158,11,0.35)', display: 'flex', flexDirection: 'column', gap: 5 }}>
|
||||
<div style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 0.6, padding: '4px 2px 2px' }}>Επιλογή</div>
|
||||
{opt.sub_choices.map((sub, si) => {
|
||||
const isSel = sel.subName === sub.name
|
||||
return (
|
||||
<Row key={si} selected={isSel} onClick={() => setExtrasState(s => ({ ...s, [opt.id]: { ...sel, subName: sub.name } }))} left={<RadioDot selected={isSel} />}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<div style={{ fontSize: 13, color: '#1e293b' }}>{sub.name}</div>
|
||||
{(sub.extra_cost ?? 0) !== 0 && <div style={{ fontSize: 12, color: '#64748b' }}>+{sub.extra_cost.toFixed(2)} €</div>}
|
||||
</div>
|
||||
</Row>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function IngredientRow({ ing, removedState, setRemovedState }) {
|
||||
const removed = !!removedState[ing.id]
|
||||
return (
|
||||
<Row selected={false} onClick={() => setRemovedState(s => ({ ...s, [ing.id]: !s[ing.id] }))}
|
||||
right={
|
||||
<div style={{
|
||||
height: 30, padding: '0 12px', borderRadius: 15,
|
||||
background: removed ? '#ef4444' : '#f1f5f9',
|
||||
border: `1px solid ${removed ? '#ef4444' : '#e2e8f0'}`,
|
||||
color: removed ? '#fff' : '#475569',
|
||||
fontSize: 12, fontWeight: 600,
|
||||
display: 'inline-flex', alignItems: 'center',
|
||||
}}>
|
||||
{removed ? 'Αφαιρέθηκε' : 'Αφαίρεση'}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div style={{ fontSize: 14, fontWeight: 500, color: removed ? '#94a3b8' : '#1e293b', textDecoration: removed ? 'line-through' : 'none' }}>{ing.name}</div>
|
||||
</Row>
|
||||
)
|
||||
}
|
||||
|
||||
function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
|
||||
const selChoice = prefs[ps.id] ?? null
|
||||
const complete = selChoice != null
|
||||
&& !(selChoice.sub_choices?.length > 0 && subChoices[selChoice.id] == null)
|
||||
&& !(ps.shared_subset?.choices?.length > 0 && !selChoice.disables_subset && sharedSubs[ps.id] == null)
|
||||
const showShared = ps.shared_subset?.choices?.length > 0 && selChoice != null && !selChoice.disables_subset
|
||||
|
||||
function selectPref(choice) {
|
||||
setPrefs(p => ({ ...p, [ps.id]: choice }))
|
||||
if (choice?.sub_choices?.length > 0) {
|
||||
setSubChoices(s => ({ ...s, [choice.id]: s[choice.id] ?? (choice.sub_choices.find(x => x.is_default) ?? choice.sub_choices[0]) }))
|
||||
}
|
||||
if (ps.shared_subset?.choices?.length > 0 && !choice?.disables_subset) {
|
||||
setSharedSubs(s => s[ps.id] != null ? s : { ...s, [ps.id]: ps.shared_subset.choices.find(x => x.is_default) ?? ps.shared_subset.choices[0] })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', gap: 8, padding: '0 2px 8px' }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 700, color: complete ? '#1e293b' : '#ef4444' }}>{ps.name}</div>
|
||||
{!complete && <div style={{ fontSize: 11, fontWeight: 700, color: '#ef4444', textTransform: 'uppercase', letterSpacing: 0.6 }}>Απαιτείται</div>}
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
{ps.choices.map(ch => {
|
||||
const isSel = selChoice?.id === ch.id
|
||||
const hasSubs = ch.sub_choices?.length > 0
|
||||
return (
|
||||
<div key={ch.id}>
|
||||
<Row selected={isSel} onClick={() => selectPref(ch)} left={<RadioDot selected={isSel} />}
|
||||
right={(ch.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 13, color: '#64748b' }}>{ch.extra_cost > 0 ? '+' : ''}{ch.extra_cost.toFixed(2)} €</div> : null}>
|
||||
<div style={{ fontSize: 14, fontWeight: 500, color: '#1e293b' }}>{ch.name}</div>
|
||||
</Row>
|
||||
{isSel && hasSubs && (
|
||||
<div style={{ margin: '5px 0 2px 14px', paddingLeft: 12, borderLeft: `2px solid ${subChoices[ch.id] == null ? '#ef4444' : 'rgba(245,158,11,0.35)'}`, display: 'flex', flexDirection: 'column', gap: 5 }}>
|
||||
{ch.sub_choices.map((sub, si) => {
|
||||
const subSel = subChoices[ch.id]?.name === sub.name
|
||||
return (
|
||||
<Row key={si} selected={subSel} onClick={() => setSubChoices(s => ({ ...s, [ch.id]: sub }))} left={<RadioDot selected={subSel} />}
|
||||
right={(sub.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 12, color: '#64748b' }}>+{sub.extra_cost.toFixed(2)} €</div> : null}>
|
||||
<div style={{ fontSize: 13, color: '#1e293b' }}>{sub.name}</div>
|
||||
</Row>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{showShared && (
|
||||
<div style={{ marginTop: 4, marginLeft: 8, paddingLeft: 12, borderLeft: '2px solid rgba(245,158,11,0.35)', display: 'flex', flexDirection: 'column', gap: 5 }}>
|
||||
<div style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 0.6, padding: '4px 2px 2px' }}>{ps.shared_subset.name}</div>
|
||||
{ps.shared_subset.choices.map((sub, si) => {
|
||||
const subSel = sharedSubs[ps.id]?.name === sub.name
|
||||
return (
|
||||
<Row key={si} selected={subSel} onClick={() => setSharedSubs(s => ({ ...s, [ps.id]: sub }))} left={<RadioDot selected={subSel} />}
|
||||
right={(sub.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 12, color: '#64748b' }}>+{sub.extra_cost.toFixed(2)} €</div> : null}>
|
||||
<div style={{ fontSize: 13, color: '#1e293b' }}>{sub.name}</div>
|
||||
</Row>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Tab content ───────────────────────────────────────────────────────────────
|
||||
|
||||
function QuickTab({ product, quickState, setQuickState }) {
|
||||
const quickOptions = product.quick_options || []
|
||||
if (quickOptions.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν γρήγορες επιλογές.</p>
|
||||
return (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
|
||||
{quickOptions.map(opt => (
|
||||
<div key={opt.id} style={{ width: opt.is_compact ? 'calc(50% - 4px)' : '100%', minWidth: 0 }}>
|
||||
<QuickOptionRow opt={opt} quickState={quickState} setQuickState={setQuickState} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) {
|
||||
const options = product.options || []
|
||||
if (options.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν extras.</p>
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
{options.map(opt => (
|
||||
<ExtraOptionRow key={opt.id} opt={opt} extrasState={extrasState} setExtrasState={setExtrasState} expandedExtra={expandedExtra} setExpandedExtra={setExpandedExtra} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function IngredientsTab({ product, removedState, setRemovedState }) {
|
||||
const ingredients = product.ingredients || []
|
||||
if (ingredients.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν υλικά.</p>
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
<div style={{ padding: '8px 12px', background: '#f1f5f9', borderRadius: 8, fontSize: 12, color: '#64748b', marginBottom: 2 }}>
|
||||
Κάντε κλικ για να αφαιρέσετε υλικό.
|
||||
</div>
|
||||
{ingredients.map(ing => (
|
||||
<IngredientRow key={ing.id} ing={ing} removedState={removedState} setRemovedState={setRemovedState} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
|
||||
const preferenceSets = product.preference_sets || []
|
||||
if (preferenceSets.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν προτιμήσεις.</p>
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
|
||||
{preferenceSets.map(ps => (
|
||||
<PrefSetBlock key={ps.id} ps={ps}
|
||||
prefs={prefs} setPrefs={setPrefs}
|
||||
subChoices={subChoices} setSubChoices={setSubChoices}
|
||||
sharedSubs={sharedSubs} setSharedSubs={setSharedSubs}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function QuantityTab({ unitCfg, qty, setQty }) {
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [qtyInput, setQtyInput] = useState('')
|
||||
const inputRef = useRef(null)
|
||||
|
||||
function clamp(v) { return Math.max(unitCfg.min, Math.round(v * 1000) / 1000) }
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 0 }}>
|
||||
<div style={{ display: 'inline-flex', alignItems: 'center', height: 48, borderRadius: 24, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden' }}>
|
||||
<button onClick={() => setQty(q => clamp(q - unitCfg.step))}
|
||||
style={{ width: 48, height: 48, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>−</button>
|
||||
{editing ? (
|
||||
<input ref={inputRef} type="number" inputMode="decimal" value={qtyInput}
|
||||
onChange={e => setQtyInput(e.target.value)}
|
||||
onBlur={() => { const v = parseFloat(qtyInput); if (!isNaN(v)) setQty(clamp(v)); setEditing(false) }}
|
||||
onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }}
|
||||
autoFocus
|
||||
style={{ width: 70, height: 48, border: 'none', background: 'transparent', textAlign: 'center', fontSize: 16, fontWeight: 700, color: '#1e293b', outline: 'none', fontFamily: 'inherit' }}
|
||||
/>
|
||||
) : (
|
||||
<div onClick={() => { setQtyInput(String(qty)); setEditing(true) }}
|
||||
style={{ minWidth: 70, textAlign: 'center', fontSize: 16, fontWeight: 700, color: '#1e293b', cursor: 'text', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 3 }}>
|
||||
{fmtDecimalQty(qty, unitCfg)}
|
||||
<span style={{ fontSize: 12, fontWeight: 500, opacity: 0.65 }}>{unitCfg.label}</span>
|
||||
</div>
|
||||
)}
|
||||
<button onClick={() => setQty(q => clamp(q + unitCfg.step))}
|
||||
style={{ width: 48, height: 48, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>+</button>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<p style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', letterSpacing: 0.8, marginBottom: 6, textAlign: 'center' }}>ΓΡΗΓΟΡΗ ΕΠΙΛΟΓΗ</p>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
|
||||
{unitCfg.presets.map(v => (
|
||||
<button key={v} onClick={() => setQty(v)} style={{
|
||||
padding: '8px 4px', borderRadius: 10, border: 'none',
|
||||
background: qty === v ? '#f59e0b' : '#f1f5f9',
|
||||
color: qty === v ? '#fff' : '#1e293b',
|
||||
fontSize: 12, fontWeight: 700, cursor: 'pointer',
|
||||
}}>
|
||||
{fmtDecimalQty(v, unitCfg)}{unitCfg.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<p style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', letterSpacing: 0.8, marginBottom: 6, textAlign: 'center' }}>ΓΡΗΓΟΡΗ ΠΡΟΣΘΗΚΗ</p>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
|
||||
{unitCfg.offsets.map(off => (
|
||||
<button key={`+${off}`} onClick={() => setQty(q => clamp(q + off))} style={{
|
||||
padding: '8px 4px', borderRadius: 10, border: 'none',
|
||||
background: 'rgba(34,197,94,0.1)', color: '#16a34a',
|
||||
fontSize: 12, fontWeight: 700, cursor: 'pointer',
|
||||
}}>+{fmtDecimalQty(off, unitCfg)}{unitCfg.label}</button>
|
||||
))}
|
||||
{unitCfg.offsets.map(off => (
|
||||
<button key={`-${off}`} onClick={() => setQty(q => clamp(q - off))} style={{
|
||||
padding: '8px 4px', borderRadius: 10, border: 'none',
|
||||
background: 'rgba(239,68,68,0.08)', color: '#dc2626',
|
||||
fontSize: 12, fontWeight: 700, cursor: 'pointer',
|
||||
}}>−{fmtDecimalQty(off, unitCfg)}{unitCfg.label}</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj }) {
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [rawInput, setRawInput] = useState('')
|
||||
const inputRef = useRef(null)
|
||||
const effectivePrice = basePrice + priceAdj
|
||||
|
||||
function applyDelta(d) {
|
||||
setPriceAdj(a => {
|
||||
const next = Math.round((a + d) * 100) / 100
|
||||
return Math.max(-(basePrice - 0.01), next)
|
||||
})
|
||||
}
|
||||
|
||||
function commitInput() {
|
||||
const v = parseFloat(rawInput.replace(',', '.'))
|
||||
if (!isNaN(v) && v >= 0.01) setPriceAdj(Math.round((v - basePrice) * 100) / 100)
|
||||
setEditing(false)
|
||||
}
|
||||
|
||||
useEffect(() => { if (editing && inputRef.current) inputRef.current.focus() }, [editing])
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
<div style={{ padding: '8px 12px', background: 'rgba(245,158,11,0.08)', border: '1px solid rgba(245,158,11,0.2)', borderRadius: 8, fontSize: 12, color: '#d97706' }}>
|
||||
Αλλαγή τιμής μόνο για αυτό το αντικείμενο.
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10 }}>
|
||||
<button onClick={() => applyDelta(-0.1)} style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f1f5f9', fontSize: 18, fontWeight: 700, color: '#1e293b', cursor: 'pointer' }}>−</button>
|
||||
{editing ? (
|
||||
<input ref={inputRef} type="number" inputMode="decimal" value={rawInput}
|
||||
onChange={e => setRawInput(e.target.value)}
|
||||
onBlur={commitInput}
|
||||
onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }}
|
||||
style={{ width: 100, height: 48, border: '2px solid #f59e0b', borderRadius: 12, background: 'white', textAlign: 'center', fontSize: 20, fontWeight: 800, color: '#f59e0b', outline: 'none', fontFamily: 'inherit' }}
|
||||
/>
|
||||
) : (
|
||||
<button onClick={() => { setRawInput(effectivePrice.toFixed(2)); setEditing(true) }} style={{
|
||||
minWidth: 100, height: 48, borderRadius: 12,
|
||||
border: `2px solid ${priceAdj !== 0 ? '#f59e0b' : '#e2e8f0'}`,
|
||||
background: priceAdj !== 0 ? 'rgba(245,158,11,0.08)' : '#f8fafc',
|
||||
color: priceAdj !== 0 ? '#f59e0b' : '#1e293b',
|
||||
fontSize: 20, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit',
|
||||
}}>
|
||||
{effectivePrice.toFixed(2)} €
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => applyDelta(+0.1)} style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f1f5f9', fontSize: 18, fontWeight: 700, color: '#1e293b', cursor: 'pointer' }}>+</button>
|
||||
</div>
|
||||
{priceAdj !== 0 && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
|
||||
<span style={{ fontSize: 12, color: '#64748b' }}>Βάση: {basePrice.toFixed(2)} €</span>
|
||||
<span style={{ fontSize: 12, fontWeight: 700, color: priceAdj > 0 ? '#16a34a' : '#dc2626' }}>{priceAdj > 0 ? '+' : ''}{priceAdj.toFixed(2)} €</span>
|
||||
<button onClick={() => setPriceAdj(0)} style={{ padding: '2px 8px', borderRadius: 6, border: '1px solid #e2e8f0', background: '#f1f5f9', color: '#64748b', fontSize: 11, cursor: 'pointer' }}>Επαναφορά</button>
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
|
||||
{PRICE_DELTAS.map(d => (
|
||||
<button key={d} onClick={() => applyDelta(d)} style={{
|
||||
padding: '9px 4px', borderRadius: 10, border: 'none',
|
||||
background: d < 0 ? 'rgba(239,68,68,0.08)' : 'rgba(34,197,94,0.08)',
|
||||
color: d < 0 ? '#dc2626' : '#16a34a',
|
||||
fontSize: 13, fontWeight: 700, cursor: 'pointer',
|
||||
}}>
|
||||
{d > 0 ? '+' : ''}{d.toFixed(2 - (Number.isInteger(d) ? 2 : 0))} €
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function NotesTab({ note, setNote }) {
|
||||
return (
|
||||
<div>
|
||||
<textarea
|
||||
value={note}
|
||||
onChange={e => setNote(e.target.value)}
|
||||
placeholder="π.χ. Χωρίς αλάτι, κόψτε στη μέση..."
|
||||
rows={4}
|
||||
style={{ width: '100%', padding: 12, fontSize: 14, fontFamily: 'inherit', color: '#1e293b', background: 'white', border: '1px solid #e2e8f0', borderRadius: 10, resize: 'none', outline: 'none', boxSizing: 'border-box' }}
|
||||
/>
|
||||
<div style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 0.6, marginTop: 14, marginBottom: 6 }}>Γρήγορες σημειώσεις</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
{QUICK_NOTES.map(q => (
|
||||
<button key={q} onClick={() => setNote(n => n ? `${n}\n${q}` : q)}
|
||||
style={{ height: 32, padding: '0 12px', borderRadius: 16, background: '#f1f5f9', border: '1px solid #e2e8f0', color: '#475569', fontSize: 12, fontWeight: 500, cursor: 'pointer' }}>
|
||||
+ {q}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Courses tab ───────────────────────────────────────────────────────────────
|
||||
|
||||
function CoursesTab({ courses, courseId, setCourseId }) {
|
||||
return (
|
||||
<div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
<button
|
||||
onClick={() => setCourseId(null)}
|
||||
style={{
|
||||
padding: '10px 14px', borderRadius: 10, textAlign: 'left',
|
||||
background: courseId === null ? '#2563eb' : '#f8fafc',
|
||||
color: courseId === null ? '#fff' : '#1e293b',
|
||||
border: `2px solid ${courseId === null ? '#2563eb' : '#e2e8f0'}`,
|
||||
fontWeight: 600, fontSize: 14, cursor: 'pointer', fontFamily: 'inherit',
|
||||
}}
|
||||
>
|
||||
No course (fire immediately)
|
||||
</button>
|
||||
{courses.map(c => (
|
||||
<button
|
||||
key={c.id}
|
||||
onClick={() => setCourseId(courseId === c.id ? null : c.id)}
|
||||
style={{
|
||||
padding: '10px 14px', borderRadius: 10, textAlign: 'left',
|
||||
background: courseId === c.id ? c.color : '#f8fafc',
|
||||
color: courseId === c.id ? '#fff' : '#1e293b',
|
||||
border: `2px solid ${courseId === c.id ? c.color : '#e2e8f0'}`,
|
||||
fontWeight: 600, fontSize: 14, cursor: 'pointer', fontFamily: 'inherit',
|
||||
display: 'flex', alignItems: 'center', gap: 10,
|
||||
}}
|
||||
>
|
||||
<span style={{
|
||||
width: 12, height: 12, borderRadius: '50%',
|
||||
background: courseId === c.id ? 'rgba(255,255,255,0.5)' : c.color,
|
||||
flexShrink: 0,
|
||||
}} />
|
||||
{c.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Main component ────────────────────────────────────────────────────────────
|
||||
|
||||
export default function ManagerOrderDrawer({ product, onClose, onAdd, initialState, courses }) {
|
||||
const preferenceSets = product?.preference_sets || []
|
||||
const quickOptions = product?.quick_options || []
|
||||
const options = product?.options || []
|
||||
const ingredients = product?.ingredients || []
|
||||
|
||||
const unitCfg = product ? (DECIMAL_UNIT_CONFIG[product.unit_type] ?? null) : null
|
||||
const isDecimal = !!unitCfg
|
||||
|
||||
const hasTabs = {
|
||||
quick: quickOptions.length > 0,
|
||||
extras: options.length > 0,
|
||||
ingredients: ingredients.length > 0,
|
||||
prefs: preferenceSets.length > 0,
|
||||
quantity: isDecimal,
|
||||
}
|
||||
|
||||
const firstTab = hasTabs.quick ? 'quick'
|
||||
: hasTabs.extras ? 'extras'
|
||||
: hasTabs.ingredients ? 'ingredients'
|
||||
: hasTabs.prefs ? 'prefs'
|
||||
: hasTabs.quantity ? 'quantity'
|
||||
: 'notes'
|
||||
|
||||
const [activeTab, setActiveTab] = useState(firstTab)
|
||||
const [qty, setQty] = useState(isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1)
|
||||
const [quickState, setQuickState] = useState({})
|
||||
const [extrasState, setExtrasState] = useState({})
|
||||
const [expandedExtra, setExpandedExtra] = useState(null)
|
||||
const [removedState, setRemovedState] = useState({})
|
||||
const [prefs, setPrefs] = useState({})
|
||||
const [subChoices, setSubChoices] = useState({})
|
||||
const [sharedSubs, setSharedSubs] = useState({})
|
||||
const [note, setNote] = useState('')
|
||||
const [priceAdj, setPriceAdj] = useState(0)
|
||||
const [addAttempted, setAddAttempted] = useState(false)
|
||||
const [courseId, setCourseId] = useState(initialState?.courseId ?? null)
|
||||
|
||||
// Reset when product changes
|
||||
useEffect(() => {
|
||||
if (!product) return
|
||||
const base = buildInitialState(product)
|
||||
if (initialState) {
|
||||
setQty(initialState.qty ?? (isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1))
|
||||
setQuickState(initialState.quickState ?? {})
|
||||
setExtrasState(initialState.extrasState ?? {})
|
||||
setRemovedState(initialState.removedState ?? {})
|
||||
setPrefs(initialState.prefs ?? base.prefs)
|
||||
setSubChoices(initialState.subChoices ?? base.subChoices)
|
||||
setSharedSubs(initialState.sharedSubs ?? base.sharedSubs)
|
||||
setNote(initialState.note ?? '')
|
||||
setPriceAdj(initialState.priceAdj ?? 0)
|
||||
setCourseId(initialState.courseId ?? null)
|
||||
setActiveTab(initialState.activeTab ?? firstTab)
|
||||
} else {
|
||||
setQty(isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1)
|
||||
setQuickState({})
|
||||
setExtrasState({})
|
||||
setRemovedState({})
|
||||
setPrefs(base.prefs)
|
||||
setSubChoices(base.subChoices)
|
||||
setSharedSubs(base.sharedSubs)
|
||||
setNote('')
|
||||
setPriceAdj(0)
|
||||
setCourseId(null)
|
||||
setActiveTab(firstTab)
|
||||
}
|
||||
setExpandedExtra(null)
|
||||
setAddAttempted(false)
|
||||
}, [product?.id])
|
||||
|
||||
// Derived total price
|
||||
const totalPrice = (() => {
|
||||
if (!product) return 0
|
||||
let price = product.base_price
|
||||
preferenceSets.forEach(ps => {
|
||||
const choice = prefs[ps.id]
|
||||
if (!choice) return
|
||||
const inlineSub = choice.sub_choices?.length > 0 ? (subChoices[choice.id] ?? null) : null
|
||||
const sharedSub = (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset) ? (sharedSubs[ps.id] ?? null) : null
|
||||
price += (choice.extra_cost ?? 0) + (inlineSub?.extra_cost ?? 0) + (sharedSub?.extra_cost ?? 0)
|
||||
})
|
||||
quickOptions.forEach(opt => { price += (quickState[opt.id] || 0) * (opt.price ?? 0) })
|
||||
options.forEach(opt => {
|
||||
const sel = extrasState[opt.id]
|
||||
if (!sel) return
|
||||
const sub = opt.sub_choices?.find(s => s.name === sel.subName)
|
||||
price += ((opt.extra_cost ?? 0) + (sub?.extra_cost ?? 0)) * sel.qty
|
||||
})
|
||||
return (price + priceAdj) * qty
|
||||
})()
|
||||
|
||||
function isPrefComplete(ps) {
|
||||
const choice = prefs[ps.id]
|
||||
if (!choice) return false
|
||||
if (choice.sub_choices?.length > 0 && subChoices[choice.id] == null) return false
|
||||
if (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset && sharedSubs[ps.id] == null) return false
|
||||
return true
|
||||
}
|
||||
const allPrefsOk = preferenceSets.every(isPrefComplete)
|
||||
const extrasSubsMissing = options.some(opt => {
|
||||
const sel = extrasState[opt.id]
|
||||
return sel && opt.sub_choices?.length > 0 && sel.subName == null
|
||||
})
|
||||
const canAdd = allPrefsOk && !extrasSubsMissing
|
||||
|
||||
function handleAdd() {
|
||||
if (!canAdd) {
|
||||
setAddAttempted(true)
|
||||
if (!allPrefsOk && hasTabs.prefs) setActiveTab('prefs')
|
||||
return
|
||||
}
|
||||
|
||||
const prefChoices = preferenceSets.flatMap(ps => {
|
||||
const choice = prefs[ps.id]
|
||||
if (!choice) return []
|
||||
const inlineSub = choice.sub_choices?.length > 0 ? (subChoices[choice.id] ?? null) : null
|
||||
const sharedSub = ps.shared_subset?.choices?.length > 0 && !choice.disables_subset ? (sharedSubs[ps.id] ?? null) : null
|
||||
const defaultChoice = ps.default_choice_id != null ? ps.choices.find(c => c.id === ps.default_choice_id) : null
|
||||
const isDefaultChoice = defaultChoice && choice.id === defaultChoice.id
|
||||
const defaultInlineSub = isDefaultChoice && defaultChoice.sub_choices?.length > 0
|
||||
? (defaultChoice.sub_choices.find(s => s.is_default) ?? defaultChoice.sub_choices[0]) : null
|
||||
const defaultSharedSub = isDefaultChoice && ps.shared_subset?.choices?.length > 0 && !choice.disables_subset
|
||||
? (ps.shared_subset.choices.find(s => s.is_default) ?? ps.shared_subset.choices[0]) : null
|
||||
const isFullyDefault = isDefaultChoice
|
||||
&& (!inlineSub || inlineSub.name === defaultInlineSub?.name)
|
||||
&& (!sharedSub || sharedSub.name === defaultSharedSub?.name)
|
||||
if (isFullyDefault) return []
|
||||
const entries = [{ id: choice.id, name: choice.name, price_delta: choice.extra_cost ?? 0, type: 'pref' }]
|
||||
if (inlineSub) entries.push({ id: null, name: inlineSub.name, price_delta: inlineSub.extra_cost ?? 0, type: 'pref_sub' })
|
||||
if (sharedSub) entries.push({ id: null, name: sharedSub.name, price_delta: sharedSub.extra_cost ?? 0, type: 'pref_sub' })
|
||||
return entries
|
||||
})
|
||||
|
||||
const optionEntries = options.flatMap(opt => {
|
||||
const sel = extrasState[opt.id]
|
||||
if (!sel) return []
|
||||
const sub = opt.sub_choices?.find(s => s.name === sel.subName)
|
||||
const entries = []
|
||||
for (let i = 0; i < sel.qty; i++) {
|
||||
entries.push({ id: opt.id, name: opt.name, price_delta: opt.extra_cost ?? 0, type: 'extra' })
|
||||
if (sub) entries.push({ id: null, name: sub.name, price_delta: sub.extra_cost ?? 0, type: 'extra_sub' })
|
||||
}
|
||||
return entries
|
||||
})
|
||||
|
||||
const quickEntries = quickOptions.flatMap(opt => {
|
||||
const q = quickState[opt.id] || 0
|
||||
if (q === 0) return []
|
||||
return Array.from({ length: q }, () => ({ id: null, name: opt.name, price_delta: opt.price ?? 0, type: 'quick' }))
|
||||
})
|
||||
|
||||
const removedNames = ingredients.filter(ing => removedState[ing.id]).map(ing => ing.name)
|
||||
|
||||
onAdd({
|
||||
product_id: product.id,
|
||||
quantity: qty,
|
||||
unit_price: product.base_price,
|
||||
selected_options: [...prefChoices, ...quickEntries, ...optionEntries],
|
||||
removed_ingredients: removedNames,
|
||||
notes: note,
|
||||
price_adjustment: priceAdj !== 0 ? priceAdj : undefined,
|
||||
course_id: courseId ?? undefined,
|
||||
_drawerState: { qty, quickState, extrasState, removedState, prefs, subChoices, sharedSubs, note, priceAdj, courseId },
|
||||
})
|
||||
}
|
||||
|
||||
const tabs = [
|
||||
hasTabs.quick && { id: 'quick', label: 'Quick' },
|
||||
hasTabs.extras && { id: 'extras', label: 'Extras' },
|
||||
hasTabs.ingredients && { id: 'ingredients', label: 'Υλικά' },
|
||||
hasTabs.prefs && { id: 'prefs', label: 'Προτιμήσεις' },
|
||||
hasTabs.quantity && { id: 'quantity', label: `Ποσότητα (${unitCfg?.label})` },
|
||||
(courses?.length > 0) && { id: 'courses', label: 'Courses' },
|
||||
{ id: 'notes', label: 'Σημείωση' },
|
||||
{ id: 'price_adjust', label: '€ Τιμή' },
|
||||
].filter(Boolean)
|
||||
|
||||
if (!product) return null
|
||||
|
||||
const initials = product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex', flexDirection: 'column', height: '100%',
|
||||
background: 'white', borderLeft: '1px solid #e2e8f0',
|
||||
}}>
|
||||
{/* Header */}
|
||||
<div style={{
|
||||
padding: '16px 16px 12px',
|
||||
borderBottom: '1px solid #e2e8f0',
|
||||
flexShrink: 0,
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
|
||||
<div style={{
|
||||
width: 52, height: 52, borderRadius: 12, flexShrink: 0,
|
||||
background: '#f1f5f9', overflow: 'hidden',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
{product.image_url
|
||||
? <img src={product.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
|
||||
: <span style={{ fontSize: 18, fontWeight: 700, color: '#94a3b8' }}>{initials}</span>
|
||||
}
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontSize: 16, fontWeight: 700, color: '#1e293b', lineHeight: 1.2, marginBottom: 3 }}>{product.name}</div>
|
||||
<div style={{ fontSize: 13, color: priceAdj !== 0 ? '#f59e0b' : '#64748b' }}>
|
||||
{priceAdj !== 0
|
||||
? <><span style={{ textDecoration: 'line-through', opacity: 0.5, marginRight: 4 }}>{product.base_price.toFixed(2)}</span>→ {(product.base_price + priceAdj).toFixed(2)} €</>
|
||||
: <>{product.base_price.toFixed(2)} €</>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={onClose} style={{
|
||||
width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0',
|
||||
background: '#f8fafc', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
cursor: 'pointer', flexShrink: 0, color: '#64748b',
|
||||
}}>
|
||||
<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>
|
||||
|
||||
{/* Tabs bar */}
|
||||
{tabs.length > 0 && (
|
||||
<div style={{ display: 'flex', gap: 2, overflowX: 'auto', scrollbarWidth: 'none' }}>
|
||||
{tabs.map(t => {
|
||||
const active = activeTab === t.id
|
||||
const isAlert = t.id === 'prefs' && !allPrefsOk && addAttempted
|
||||
return (
|
||||
<button key={t.id} onClick={() => setActiveTab(t.id)} style={{
|
||||
padding: '6px 10px',
|
||||
background: 'none', border: 'none',
|
||||
borderBottom: `2px solid ${active ? '#f59e0b' : 'transparent'}`,
|
||||
color: isAlert ? '#ef4444' : active ? '#f59e0b' : '#64748b',
|
||||
fontSize: 12, fontWeight: active ? 700 : 500,
|
||||
fontFamily: 'inherit', cursor: 'pointer',
|
||||
whiteSpace: 'nowrap',
|
||||
transition: 'color 100ms, border-color 100ms',
|
||||
}}>
|
||||
{t.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Scrollable content */}
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: '14px 14px 10px' }}>
|
||||
{activeTab === 'quick' && <QuickTab product={product} quickState={quickState} setQuickState={setQuickState} />}
|
||||
{activeTab === 'extras' && <ExtrasTab product={product} extrasState={extrasState} setExtrasState={setExtrasState} expandedExtra={expandedExtra} setExpandedExtra={setExpandedExtra} />}
|
||||
{activeTab === 'ingredients' && <IngredientsTab product={product} removedState={removedState} setRemovedState={setRemovedState} />}
|
||||
{activeTab === 'prefs' && <PrefsTab product={product} prefs={prefs} setPrefs={setPrefs} subChoices={subChoices} setSubChoices={setSubChoices} sharedSubs={sharedSubs} setSharedSubs={setSharedSubs} />}
|
||||
{activeTab === 'quantity' && isDecimal && <QuantityTab unitCfg={unitCfg} qty={qty} setQty={setQty} />}
|
||||
{activeTab === 'courses' && courses?.length > 0 && <CoursesTab courses={courses} courseId={courseId} setCourseId={setCourseId} />}
|
||||
{activeTab === 'notes' && <NotesTab note={note} setNote={setNote} />}
|
||||
{activeTab === 'price_adjust' && <PriceAdjustTab basePrice={product.base_price} priceAdj={priceAdj} setPriceAdj={setPriceAdj} />}
|
||||
</div>
|
||||
|
||||
{/* Footer: qty stepper + ADD button */}
|
||||
<div style={{
|
||||
padding: '12px 14px',
|
||||
borderTop: '1px solid #e2e8f0',
|
||||
background: '#f8fafc',
|
||||
display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0,
|
||||
}}>
|
||||
{isDecimal ? (
|
||||
<div onClick={() => setActiveTab('quantity')}
|
||||
style={{ display: 'inline-flex', alignItems: 'center', height: 44, borderRadius: 22, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden', flexShrink: 0, cursor: 'pointer', padding: '0 14px', gap: 4 }}>
|
||||
<span style={{ fontSize: 16, fontWeight: 700, color: '#1e293b' }}>{fmtDecimalQty(qty, unitCfg)}</span>
|
||||
<span style={{ fontSize: 12, color: '#64748b' }}>{unitCfg.label}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'inline-flex', alignItems: 'center', height: 44, borderRadius: 22, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden', flexShrink: 0 }}>
|
||||
<button onClick={() => setQty(q => Math.max(1, q - 1))} style={{ width: 44, height: 44, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: qty <= 1 ? 'default' : 'pointer', color: qty <= 1 ? '#94a3b8' : '#1e293b' }}>−</button>
|
||||
<div style={{ minWidth: 28, textAlign: 'center', fontSize: 16, fontWeight: 700, color: '#1e293b' }}>{qty}</div>
|
||||
<button onClick={() => setQty(q => q + 1)} style={{ width: 44, height: 44, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>+</button>
|
||||
</div>
|
||||
)}
|
||||
<button onClick={handleAdd} style={{
|
||||
flex: 1, height: 44, borderRadius: 22,
|
||||
background: canAdd ? '#f59e0b' : '#e2e8f0',
|
||||
border: 'none', color: canAdd ? '#fff' : '#94a3b8',
|
||||
fontSize: 14, fontWeight: 700, fontFamily: 'inherit',
|
||||
cursor: canAdd ? 'pointer' : 'not-allowed',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||
padding: '0 18px',
|
||||
transition: 'background 150ms ease',
|
||||
}}>
|
||||
<span>ΠΡΟΣΘΗΚΗ</span>
|
||||
<span>{totalPrice.toFixed(2)} €</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,757 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { useParams, useNavigate } from 'react-router-dom'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import toast from 'react-hot-toast'
|
||||
import client from '../api/client'
|
||||
import { Percent } from 'lucide-react'
|
||||
import Badge from '../ui/Badge'
|
||||
import { ConfirmModal } from '../ui/Modal'
|
||||
import PaymentMethodModal from '../ui/PaymentMethodModal'
|
||||
import DesktopOrderingTab from './DesktopOrderingTab'
|
||||
|
||||
function PrintOrderModal({ onClose, onPrint, printers }) {
|
||||
const [printerId, setPrinterId] = useState(printers[0]?.id ?? '')
|
||||
function submit() {
|
||||
if (!printerId) { toast.error('Επιλέξτε εκτυπωτή'); return }
|
||||
onPrint(Number(printerId))
|
||||
onClose()
|
||||
}
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 space-y-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-bold text-gray-800">Εκτύπωση παραγγελίας</h2>
|
||||
<button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl leading-none">✕</button>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Εκτυπωτής</label>
|
||||
<select className="input w-full" value={printerId} onChange={e => setPrinterId(e.target.value)}>
|
||||
<option value="">— Επιλέξτε —</option>
|
||||
{printers.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<button onClick={onClose} className="btn btn-secondary flex-1">Ακύρωση</button>
|
||||
<button onClick={submit} className="btn btn-primary flex-1">Εκτύπωση</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function effPrice(item) { return (item.unit_price ?? 0) + (item.price_adjustment ?? 0) }
|
||||
function itemTotal(item) {
|
||||
return (effPrice(item) * item.quantity).toFixed(2)
|
||||
}
|
||||
|
||||
const PAYMENT_METHOD_STYLES = {
|
||||
cash: { label: 'ΜΕΤΡΗΤΑ', color: '#15803d', bg: '#f0fdf4', border: '#86efac' },
|
||||
card: { label: 'ΚΑΡΤΑ', color: '#1d4ed8', bg: '#eff6ff', border: '#93c5fd' },
|
||||
transfer: { label: 'ΤΡΑΠΕΖΙΚΗ', color: '#6d28d9', bg: '#f5f3ff', border: '#c4b5fd' },
|
||||
treat: { label: 'ΚΕΡΑΣΤΗΚΕ', color: '#b45309', bg: '#fffbeb', border: '#fcd34d' },
|
||||
comp: { label: 'ΚΕΡΑΣΤΗΚΕ', color: '#b45309', bg: '#fffbeb', border: '#fcd34d' },
|
||||
}
|
||||
|
||||
function PayMethodChip({ method }) {
|
||||
if (!method) return null
|
||||
const s = PAYMENT_METHOD_STYLES[method] || { label: method.toUpperCase(), color: '#374151', bg: '#f3f4f6', border: '#d1d5db' }
|
||||
return (
|
||||
<span style={{ fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 4, background: s.bg, color: s.color, border: `1px solid ${s.border}`, letterSpacing: 0.3 }}>
|
||||
{s.label}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function formatDate(dt) {
|
||||
if (!dt) return '—'
|
||||
return new Date(dt).toLocaleString('el-GR', { dateStyle: 'short', timeStyle: 'short' })
|
||||
}
|
||||
|
||||
const EVENT_LABELS = {
|
||||
ORDER_OPENED: 'Άνοιγμα',
|
||||
ITEMS_ADDED: 'Προσθήκη',
|
||||
PAYMENT: 'Πληρωμή',
|
||||
PAYMENT_OFFLINE: 'Πληρωμή (Offline)',
|
||||
ORDER_CLOSED: 'Κλείσιμο',
|
||||
ORDER_CANCELLED: 'Ακύρωση',
|
||||
ITEM_CANCELLED: 'Ακύρωση αντ.',
|
||||
}
|
||||
|
||||
function AuditTab({ order, waiterMap }) {
|
||||
if (!order.audit_logs || order.audit_logs.length === 0) {
|
||||
return <p className="py-8 text-center text-gray-400 text-sm">Δεν υπάρχουν εγγραφές.</p>
|
||||
}
|
||||
|
||||
const itemsById = Object.fromEntries((order.items || []).map(i => [i.id, i]))
|
||||
|
||||
return (
|
||||
<div className="divide-y divide-gray-100">
|
||||
{order.audit_logs.map(log => {
|
||||
const isDuplicate = log.is_duplicate === 1 || log.is_duplicate === true
|
||||
const isPayment = log.event_type === 'PAYMENT' || log.event_type === 'PAYMENT_OFFLINE'
|
||||
const badgeClass = isDuplicate
|
||||
? 'bg-red-100 text-red-700'
|
||||
: isPayment ? 'bg-green-100 text-green-700'
|
||||
: log.event_type.includes('CANCEL') ? 'bg-red-100 text-red-600'
|
||||
: log.event_type === 'ORDER_CLOSED' ? 'bg-gray-100 text-gray-600'
|
||||
: 'bg-blue-100 text-blue-700'
|
||||
const displayTime = log.offline_at ? formatDate(log.offline_at) : formatDate(log.created_at)
|
||||
|
||||
// Resolve item names for ITEMS_ADDED and ITEM_CANCELLED events
|
||||
let itemNames = []
|
||||
if (log.item_ids && (log.event_type === 'ITEMS_ADDED' || log.event_type === 'ITEM_CANCELLED')) {
|
||||
try {
|
||||
const ids = JSON.parse(log.item_ids)
|
||||
itemNames = ids.map(id => {
|
||||
const item = itemsById[id]
|
||||
return item ? `${item.product?.name ?? `#${item.product_id}`} ×${item.quantity}` : null
|
||||
}).filter(Boolean)
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={log.id} className={`flex items-start gap-3 px-4 py-3 ${isDuplicate ? 'bg-red-50' : ''}`}>
|
||||
<div className="shrink-0 mt-0.5">
|
||||
<span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${badgeClass}`}>
|
||||
{EVENT_LABELS[log.event_type] ?? log.event_type}
|
||||
</span>
|
||||
{isDuplicate && (
|
||||
<span className="block text-xs text-red-500 font-semibold mt-0.5">ΔΙΠΛΗ</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0 text-sm text-gray-700">
|
||||
<span>{log.waiter_name ?? waiterMap[log.waiter_id] ?? `#${log.waiter_id}`}</span>
|
||||
{log.amount != null && (
|
||||
<span className={`ml-2 font-semibold ${isDuplicate ? 'text-red-600' : 'text-green-700'}`}>
|
||||
€{log.amount.toFixed(2)}
|
||||
</span>
|
||||
)}
|
||||
{log.payment_method && (
|
||||
<span className="ml-1"><PayMethodChip method={log.payment_method} /></span>
|
||||
)}
|
||||
{itemNames.length > 0 && (
|
||||
<div className="mt-1 flex flex-wrap gap-1">
|
||||
{itemNames.map((name, i) => (
|
||||
<span key={i} className="rounded bg-gray-100 px-1.5 py-0.5 text-xs text-gray-600">{name}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-right shrink-0">
|
||||
<span className="text-xs text-gray-400">{displayTime}</span>
|
||||
{log.offline_at && (
|
||||
<span className="block text-xs text-orange-400">offline</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Price Events Tab ────────────────────────────────────────────────────────
|
||||
|
||||
const PRICE_EVENT_LABELS = {
|
||||
modifier_applied: 'Τροποποιητής',
|
||||
deal_triggered: 'Προσφορά',
|
||||
deal_offer_shown: 'Προσφορά (εμφανίστηκε)',
|
||||
deal_offer_accepted: 'Προσφορά (αποδεκτή)',
|
||||
deal_offer_dismissed:'Προσφορά (απορρίφθηκε)',
|
||||
waiter_discount: 'Έκπτωση σερβιτόρου',
|
||||
free_item_added: 'Δωρεάν αντικείμενο',
|
||||
}
|
||||
|
||||
const PRICE_EVENT_COLORS = {
|
||||
modifier_applied: { bg: '#eff6ff', color: '#1d4ed8', border: '#93c5fd' },
|
||||
deal_triggered: { bg: '#f0fdf4', color: '#15803d', border: '#86efac' },
|
||||
deal_offer_shown: { bg: '#fefce8', color: '#a16207', border: '#fde68a' },
|
||||
deal_offer_accepted: { bg: '#f0fdf4', color: '#15803d', border: '#86efac' },
|
||||
deal_offer_dismissed:{ bg: '#fef2f2', color: '#b91c1c', border: '#fca5a5' },
|
||||
waiter_discount: { bg: '#fdf4ff', color: '#7e22ce', border: '#d8b4fe' },
|
||||
free_item_added: { bg: '#f0fdf4', color: '#15803d', border: '#86efac' },
|
||||
}
|
||||
|
||||
function PriceEventsTab({ orderId }) {
|
||||
const { data: events = [], isLoading } = useQuery({
|
||||
queryKey: ['price-events', orderId],
|
||||
queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data),
|
||||
})
|
||||
|
||||
if (isLoading) return (
|
||||
<div className="flex justify-center py-16">
|
||||
<div className="w-5 h-5 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
|
||||
</div>
|
||||
)
|
||||
|
||||
if (events.length === 0) return (
|
||||
<div className="py-16 text-center text-gray-400">
|
||||
<Percent className="w-8 h-8 mx-auto mb-2 opacity-30" />
|
||||
<p className="text-sm">Δεν υπάρχουν συμβάντα τιμολόγησης για αυτή την παραγγελία.</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="divide-y divide-gray-100">
|
||||
{events.map(ev => {
|
||||
const label = PRICE_EVENT_LABELS[ev.event_type] ?? ev.event_type
|
||||
const style = PRICE_EVENT_COLORS[ev.event_type] ?? { bg: '#f8fafc', color: '#334155', border: '#cbd5e1' }
|
||||
const hasDelta = ev.price_before != null && ev.price_after != null
|
||||
return (
|
||||
<div key={ev.id} className="flex items-start gap-3 px-4 py-3">
|
||||
<div className="shrink-0 mt-0.5">
|
||||
<span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: style.bg, color: style.color, border: `1px solid ${style.border}` }}>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0 text-sm">
|
||||
<div className="flex flex-wrap gap-x-3 gap-y-0.5 items-baseline">
|
||||
{ev.modifier_name && <span className="font-medium text-gray-800">{ev.modifier_name}</span>}
|
||||
{ev.deal_name && <span className="font-medium text-gray-800">{ev.deal_name}</span>}
|
||||
{ev.applied_by_username && (
|
||||
<span className="text-gray-500 text-xs">από {ev.applied_by_username}</span>
|
||||
)}
|
||||
{hasDelta && (
|
||||
<span className={`text-xs font-semibold ${ev.delta_amount < 0 ? 'text-green-700' : 'text-red-600'}`}>
|
||||
{ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount?.toFixed(2)}€
|
||||
<span className="font-normal text-gray-400 ml-1">
|
||||
({ev.price_before?.toFixed(2)} → {ev.price_after?.toFixed(2)})
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{ev.waiter_note && (
|
||||
<p className="text-xs text-gray-400 mt-0.5 italic">"{ev.waiter_note}"</p>
|
||||
)}
|
||||
{ev.conditions_snapshot && Object.keys(ev.conditions_snapshot).length > 0 && (
|
||||
<details className="mt-1">
|
||||
<summary className="text-xs text-gray-400 cursor-pointer hover:text-gray-600">Συνθήκες</summary>
|
||||
<pre className="text-[10px] text-gray-500 bg-gray-50 rounded p-2 mt-1 overflow-x-auto">
|
||||
{JSON.stringify(ev.conditions_snapshot, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
<div className="shrink-0 text-right">
|
||||
<span className="text-xs text-gray-400">{formatDate(ev.applied_at)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function OrderDetailPage({ orderId: propOrderId, readOnly = false }) {
|
||||
const { orderId: paramOrderId } = useParams()
|
||||
const orderId = propOrderId ?? paramOrderId
|
||||
const navigate = useNavigate()
|
||||
const qc = useQueryClient()
|
||||
|
||||
const [tab, setTab] = useState('overview')
|
||||
const [confirmAction, setConfirmAction] = useState(null) // { type, payload }
|
||||
const [showPrintModal, setShowPrintModal] = useState(false)
|
||||
const [payPending, setPayPending] = useState(null) // item_ids waiting for method selection
|
||||
const [customerSearch, setCustomerSearch] = useState('')
|
||||
const [showCustomerDropdown, setShowCustomerDropdown] = useState(false)
|
||||
|
||||
const { data: order, isLoading } = useQuery({
|
||||
queryKey: ['order', orderId],
|
||||
queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data),
|
||||
enabled: !!orderId,
|
||||
})
|
||||
|
||||
const { data: waiters = [] } = useQuery({
|
||||
queryKey: ['waiters'],
|
||||
queryFn: () => client.get('/api/waiters/').then(r => r.data),
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const { data: printers = [] } = useQuery({
|
||||
queryKey: ['printers'],
|
||||
queryFn: () => client.get('/api/system/printers').then(r => r.data),
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const { data: rawPriceEvents = [] } = useQuery({
|
||||
queryKey: ['price-events', orderId],
|
||||
queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data),
|
||||
enabled: !!orderId,
|
||||
staleTime: 30_000,
|
||||
})
|
||||
const priceEventsMap = rawPriceEvents.reduce((acc, ev) => {
|
||||
if (!acc[ev.order_item_id]) acc[ev.order_item_id] = []
|
||||
acc[ev.order_item_id].push(ev)
|
||||
return acc
|
||||
}, {})
|
||||
|
||||
const printOrder = useMutation({
|
||||
mutationFn: (printerId) => client.post(`/api/orders/${orderId}/print`, { printer_id: printerId }),
|
||||
onSuccess: () => toast.success('Αποστολή στον εκτυπωτή…'),
|
||||
onError: () => toast.error('Σφάλμα εκτύπωσης'),
|
||||
})
|
||||
|
||||
const waiterMap = Object.fromEntries(waiters.map(w => [w.id, w.nickname || w.full_name || w.username]))
|
||||
const assignedIds = new Set((order?.waiters ?? []).map(w => w.waiter_id))
|
||||
|
||||
const invalidate = () => {
|
||||
qc.invalidateQueries({ queryKey: ['order', orderId] })
|
||||
qc.invalidateQueries({ queryKey: ['orders-active'] })
|
||||
}
|
||||
|
||||
const cancelItem = useMutation({
|
||||
mutationFn: (itemId) => client.delete(`/api/orders/${orderId}/items/${itemId}`),
|
||||
onSuccess: () => { toast.success('Αντικείμενο ακυρώθηκε'); invalidate() },
|
||||
onError: () => toast.error('Σφάλμα ακύρωσης αντικειμένου'),
|
||||
})
|
||||
|
||||
const cancelOrder = useMutation({
|
||||
mutationFn: () => client.delete(`/api/orders/${orderId}`),
|
||||
onSuccess: () => { toast.success('Παραγγελία ακυρώθηκε'); navigate('/tables') },
|
||||
onError: () => toast.error('Σφάλμα ακύρωσης παραγγελίας'),
|
||||
})
|
||||
|
||||
const closeOrder = useMutation({
|
||||
mutationFn: () => client.post(`/api/orders/${orderId}/close`),
|
||||
onSuccess: () => { toast.success('Παραγγελία έκλεισε'); navigate('/tables') },
|
||||
onError: () => toast.error('Σφάλμα κλεισίματος'),
|
||||
})
|
||||
|
||||
const assignWaiter = useMutation({
|
||||
mutationFn: (waiter_id) => client.put(`/api/orders/${orderId}/assign-waiter`, { waiter_id }),
|
||||
onSuccess: () => { toast.success('Σερβιτόρος προστέθηκε'); invalidate() },
|
||||
onError: () => toast.error('Σφάλμα'),
|
||||
})
|
||||
|
||||
const removeWaiter = useMutation({
|
||||
mutationFn: (wid) => client.delete(`/api/orders/${orderId}/waiters/${wid}`),
|
||||
onSuccess: () => { toast.success('Σερβιτόρος αφαιρέθηκε'); invalidate() },
|
||||
onError: () => toast.error('Σφάλμα'),
|
||||
})
|
||||
|
||||
const { data: customersData = [] } = useQuery({
|
||||
queryKey: ['customers', customerSearch],
|
||||
queryFn: () => client.get('/api/customers/', { params: customerSearch ? { search: customerSearch } : {} }).then(r => r.data),
|
||||
staleTime: 30_000,
|
||||
enabled: showCustomerDropdown,
|
||||
})
|
||||
|
||||
const assignCustomer = useMutation({
|
||||
mutationFn: (customer_id) => client.put(`/api/orders/${orderId}/customer`, { customer_id }),
|
||||
onSuccess: (_, customer_id) => { toast.success(customer_id ? 'Πελάτης ανατέθηκε' : 'Πελάτης αφαιρέθηκε'); invalidate(); setShowCustomerDropdown(false); setCustomerSearch('') },
|
||||
onError: () => toast.error('Σφάλμα'),
|
||||
})
|
||||
|
||||
const payItems = useMutation({
|
||||
mutationFn: ({ item_ids, payment_method }) => client.post(`/api/orders/${orderId}/pay`, { item_ids, payment_method }),
|
||||
onSuccess: () => { toast.success('Πληρώθηκε'); invalidate() },
|
||||
onError: () => toast.error('Σφάλμα πληρωμής'),
|
||||
})
|
||||
|
||||
const tabItem = useMutation({
|
||||
mutationFn: (itemId) => client.post(`/api/orders/${orderId}/items/${itemId}/tab`),
|
||||
onSuccess: () => { toast.success('Αντικείμενο μεταφέρθηκε στην καρτέλα'); invalidate() },
|
||||
onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
|
||||
})
|
||||
|
||||
function requestPay(item_ids) {
|
||||
setPayPending(item_ids)
|
||||
}
|
||||
|
||||
function confirmPay(method) {
|
||||
if (!payPending) return
|
||||
payItems.mutate({ item_ids: payPending, payment_method: method })
|
||||
setPayPending(null)
|
||||
}
|
||||
|
||||
function handleConfirm() {
|
||||
if (!confirmAction) return
|
||||
const { type, payload } = confirmAction
|
||||
if (type === 'cancelItem') cancelItem.mutate(payload)
|
||||
if (type === 'cancelOrder') cancelOrder.mutate()
|
||||
if (type === 'closeOrder') closeOrder.mutate()
|
||||
setConfirmAction(null)
|
||||
}
|
||||
|
||||
if (isLoading) return <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
|
||||
if (!order) return <div className="text-center py-16 text-gray-400">Παραγγελία δεν βρέθηκε.</div>
|
||||
|
||||
const activeItems = order.items.filter(i => i.status === 'active')
|
||||
const total = order.items
|
||||
.filter(i => i.status !== 'cancelled')
|
||||
.reduce((s, i) => s + effPrice(i) * i.quantity, 0)
|
||||
|
||||
const isOpen = ['open', 'partially_paid'].includes(order.status)
|
||||
|
||||
// The ordering tab needs full height and no outer padding
|
||||
if (tab === 'order') {
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
|
||||
{/* Compact header strip */}
|
||||
<div style={{ padding: '10px 20px', borderBottom: '1px solid #e2e8f0', display: 'flex', alignItems: 'center', gap: 16, flexShrink: 0 }}>
|
||||
{!propOrderId && (
|
||||
<button onClick={() => navigate(-1)} className="btn btn-ghost text-sm">← Πίσω</button>
|
||||
)}
|
||||
<div style={{ fontSize: 14, color: '#64748b' }}>
|
||||
Τραπέζι {order.table_name || order.table_id}
|
||||
</div>
|
||||
<Badge status={order.status} />
|
||||
<span style={{ fontSize: 14, fontWeight: 700, color: '#1e293b' }}>€{total.toFixed(2)}</span>
|
||||
<div style={{ flex: 1 }} />
|
||||
{/* Tab strip inline */}
|
||||
<div style={{ display: 'flex', gap: 1, borderBottom: 'none' }}>
|
||||
{[['overview', 'Επισκόπηση'], ['order', 'Παραγγελία'], ['pricing', 'Τιμολόγηση'], ['audit', 'Ιστορικό']].map(([key, label]) => (
|
||||
<button key={key} onClick={() => setTab(key)}
|
||||
style={{
|
||||
padding: '6px 14px', fontSize: 13, fontWeight: tab === key ? 700 : 500,
|
||||
background: 'none', border: 'none', cursor: 'pointer',
|
||||
borderBottom: `2px solid ${tab === key ? '#4f46e5' : 'transparent'}`,
|
||||
color: tab === key ? '#4f46e5' : '#64748b',
|
||||
}}>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{/* Full-height ordering terminal */}
|
||||
<div style={{ flex: 1, minHeight: 0, overflow: 'hidden' }}>
|
||||
<DesktopOrderingTab
|
||||
orderId={orderId}
|
||||
tableId={order.table_id}
|
||||
orderStatus={order.status}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-y-auto h-full p-6">
|
||||
<div className="max-w-3xl mx-auto space-y-6">
|
||||
{!propOrderId && (
|
||||
<button onClick={() => navigate(-1)} className="btn btn-ghost text-sm">← Πίσω</button>
|
||||
)}
|
||||
|
||||
{/* Header */}
|
||||
<div className="card p-5 flex flex-wrap gap-4 items-start justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">
|
||||
Τραπέζι {order.table_name || order.table_id} · Ανοίχτηκε {formatDate(order.opened_at)}
|
||||
{order.closed_at && ` · Έκλεισε ${formatDate(order.closed_at)}`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge status={order.status} />
|
||||
<span className="text-lg font-bold text-gray-800">€{total.toFixed(2)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Customer assignment */}
|
||||
<div className="card p-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h2 className="text-sm font-semibold text-gray-700">Πελάτης</h2>
|
||||
{order.customer_id && isOpen && !readOnly && (
|
||||
<button
|
||||
onClick={() => assignCustomer.mutate(null)}
|
||||
className="text-xs text-gray-400 hover:text-red-500"
|
||||
>
|
||||
Αφαίρεση
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{order.customer_id ? (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', background: '#eff6ff', borderRadius: 8, border: '1px solid #bfdbfe' }}>
|
||||
<span style={{ fontSize: 16 }}>👤</span>
|
||||
<div>
|
||||
<div style={{ fontSize: 13.5, fontWeight: 700, color: '#1d4ed8' }}>{order.customer_name || `Πελάτης #${order.customer_id}`}</div>
|
||||
{order.customer_phone && <div style={{ fontSize: 11.5, color: '#3b82f6' }}>{order.customer_phone}</div>}
|
||||
</div>
|
||||
</div>
|
||||
) : isOpen && !readOnly ? (
|
||||
<div style={{ position: 'relative' }}>
|
||||
{!showCustomerDropdown ? (
|
||||
<button
|
||||
onClick={() => setShowCustomerDropdown(true)}
|
||||
style={{ fontSize: 13, color: '#6b7280', border: '1px dashed #d1d5db', borderRadius: 8, padding: '7px 14px', cursor: 'pointer', background: 'white', width: '100%', textAlign: 'left' }}
|
||||
>
|
||||
+ Ανάθεση πελάτη
|
||||
</button>
|
||||
) : (
|
||||
<div>
|
||||
<input
|
||||
autoFocus
|
||||
value={customerSearch}
|
||||
onChange={e => setCustomerSearch(e.target.value)}
|
||||
placeholder="Αναζήτηση πελάτη…"
|
||||
style={{ width: '100%', padding: '7px 11px', border: '1.5px solid #3b82f6', borderRadius: 8, fontSize: 13, outline: 'none', boxSizing: 'border-box' }}
|
||||
/>
|
||||
<div style={{ position: 'absolute', top: '100%', left: 0, right: 0, background: 'white', border: '1px solid #e5e7eb', borderRadius: 8, boxShadow: '0 4px 16px rgba(0,0,0,0.10)', zIndex: 20, maxHeight: 220, overflowY: 'auto', marginTop: 4 }}>
|
||||
{customersData.length === 0 && (
|
||||
<div style={{ padding: '10px 14px', fontSize: 13, color: '#9ca3af' }}>Δεν βρέθηκαν πελάτες</div>
|
||||
)}
|
||||
{customersData.map(c => (
|
||||
<button key={c.id} onClick={() => assignCustomer.mutate(c.id)}
|
||||
style={{ display: 'block', width: '100%', textAlign: 'left', padding: '9px 14px', border: 'none', background: 'none', cursor: 'pointer', fontSize: 13, borderBottom: '1px solid #f3f4f6' }}
|
||||
className="hover:bg-blue-50"
|
||||
>
|
||||
<span style={{ fontWeight: 600, color: '#111315' }}>{c.name}</span>
|
||||
{c.nickname && <span style={{ color: '#9ca3af', marginLeft: 5 }}>«{c.nickname}»</span>}
|
||||
{c.phone && <span style={{ color: '#6b7280', marginLeft: 8, fontSize: 12 }}>{c.phone}</span>}
|
||||
</button>
|
||||
))}
|
||||
<button onClick={() => { setShowCustomerDropdown(false); setCustomerSearch('') }}
|
||||
style={{ display: 'block', width: '100%', padding: '8px 14px', fontSize: 12, color: '#9ca3af', border: 'none', background: 'none', cursor: 'pointer', borderTop: '1px solid #f0f0ef' }}>
|
||||
Ακύρωση
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ fontSize: 13, color: '#d1d5db' }}>Χωρίς πελάτη</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex gap-1 border-b border-gray-200">
|
||||
{[['overview', 'Επισκόπηση'], ['order', 'Παραγγελία'], ['pricing', 'Τιμολόγηση'], ['audit', 'Ιστορικό Συναλλαγών']].map(([key, label]) => (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => setTab(key)}
|
||||
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${tab === key ? 'border-primary-600 text-primary-700' : 'border-transparent text-gray-500 hover:text-gray-700'}`}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{tab === 'overview' && <>
|
||||
{/* Waiters */}
|
||||
<div className="card p-4">
|
||||
<h2 className="text-sm font-semibold text-gray-700 mb-3">Προσωπικό</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{order.waiters.map(w => (
|
||||
<div key={w.waiter_id} className="flex items-center gap-2 bg-gray-100 rounded-full px-3 py-1">
|
||||
<span className="text-sm">{waiterMap[w.waiter_id] || `#${w.waiter_id}`}</span>
|
||||
{isOpen && !readOnly && (
|
||||
<button
|
||||
onClick={() => removeWaiter.mutate(w.waiter_id)}
|
||||
className="text-gray-400 hover:text-red-500 text-xs leading-none"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{isOpen && !readOnly && (
|
||||
<select
|
||||
className="text-sm border border-gray-300 rounded-full pl-3 pr-8 py-1 focus:outline-none focus:ring-1 focus:ring-primary-600"
|
||||
defaultValue=""
|
||||
onChange={e => { if (e.target.value) assignWaiter.mutate(Number(e.target.value)) }}
|
||||
>
|
||||
<option value="">+ Πρόσθεσε</option>
|
||||
{waiters.filter(w => !assignedIds.has(w.id)).map(w => (
|
||||
<option key={w.id} value={w.id}>{w.nickname || w.full_name || w.username}</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Items */}
|
||||
<div className="card divide-y divide-gray-100">
|
||||
<div className="px-4 py-3">
|
||||
<h2 className="text-sm font-semibold text-gray-700">Αντικείμενα</h2>
|
||||
</div>
|
||||
{order.items.length === 0 && (
|
||||
<p className="px-4 py-6 text-center text-gray-400 text-sm">Κανένα αντικείμενο.</p>
|
||||
)}
|
||||
{order.items.map(item => {
|
||||
const isCancelled = item.status === 'cancelled'
|
||||
const isClosedItem = item.status === 'closed'
|
||||
const badgeStatus = isClosedItem ? 'closed_item' : item.status
|
||||
const hasPriceAdj = !!(item.price_adjustment && item.price_adjustment !== 0)
|
||||
const isDealItem = !!item.deal_id
|
||||
const itemPriceEvents = (priceEventsMap[item.id] ?? []).filter(ev => ['modifier_applied','waiter_discount','free_item_added'].includes(ev.event_type))
|
||||
const EVENT_COLORS_ODP = { modifier_applied: '#2563eb', waiter_discount: '#7c3aed', free_item_added: '#16a34a' }
|
||||
return (
|
||||
<div key={item.id} className={`flex items-center gap-3 px-4 py-3 ${isCancelled ? 'opacity-40 line-through' : ''} ${isClosedItem ? 'bg-amber-50/50' : ''}`}>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-gray-800 text-sm" style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
|
||||
{item.product?.name ?? `#${item.product_id}`}
|
||||
{item.course_id != null && (
|
||||
<span style={{
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: 18, height: 18, borderRadius: '50%',
|
||||
background: '#6366f1', color: '#fff',
|
||||
fontSize: 10, fontWeight: 700,
|
||||
}} title="Course">
|
||||
{item.course_id}
|
||||
</span>
|
||||
)}
|
||||
{isDealItem && <span style={{ fontSize: 10, fontWeight: 700, padding: '1px 5px', borderRadius: 4, background: 'rgba(167,139,250,0.12)', color: '#7c3aed', border: '1px solid rgba(167,139,250,0.3)' }}>ΔΩΡΕΑΝ</span>}
|
||||
</p>
|
||||
{item.notes && <p className="text-xs text-gray-400">{item.notes}</p>}
|
||||
<p className="text-xs" style={{ color: hasPriceAdj ? '#3b82f6' : '#6b7280' }}>
|
||||
x{item.quantity} · €{effPrice(item).toFixed(2)}/τμχ
|
||||
{hasPriceAdj && (
|
||||
<span className="ml-1 line-through text-gray-400">€{(item.unit_price ?? 0).toFixed(2)}</span>
|
||||
)}
|
||||
</p>
|
||||
{itemPriceEvents.map((ev, ei) => {
|
||||
const evColor = EVENT_COLORS_ODP[ev.event_type] || '#8a9099'
|
||||
const evLabel = ev.modifier_name || ev.deal_name || (ev.event_type === 'waiter_discount' ? 'Έκπτωση' : ev.event_type === 'free_item_added' ? 'Δωρεάν' : ev.event_type)
|
||||
return (
|
||||
<p key={ei} className="text-xs" style={{ color: evColor, display: 'flex', alignItems: 'center', gap: 3 }}>
|
||||
<span style={{ opacity: 0.6 }}>↳</span>
|
||||
<span>{evLabel}</span>
|
||||
{ev.delta_amount != null && <span style={{ fontWeight: 600 }}>{ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount.toFixed(2)} €</span>}
|
||||
</p>
|
||||
)
|
||||
})}
|
||||
{item.paid_by && (
|
||||
<p className="text-xs text-green-600 mt-0.5">
|
||||
Πληρώθηκε: {item.paid_by_name ?? waiterMap[item.paid_by] ?? `#${item.paid_by}`}
|
||||
{item.paid_at ? ` · ${formatDate(item.paid_at)}` : ''}
|
||||
{item.payment_method && (
|
||||
<span style={{ color: (PAYMENT_METHOD_STYLES[item.payment_method] || {}).color ?? '#374151', fontWeight: 600 }}>
|
||||
{' · '}{(PAYMENT_METHOD_STYLES[item.payment_method] || { label: item.payment_method.toUpperCase() }).label}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{isClosedItem && (
|
||||
<p className="text-xs text-amber-700 mt-0.5 font-medium">Απλήρωτο — κλείστηκε από manager</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<span className="text-sm font-semibold w-14 text-right" style={{ color: hasPriceAdj ? '#3b82f6' : '#374151' }}>€{itemTotal(item)}</span>
|
||||
{isOpen && !readOnly && item.status === 'active' && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => requestPay([item.id])}
|
||||
className="btn btn-secondary text-xs px-2 py-1 min-h-0 h-8"
|
||||
>
|
||||
Πληρωμή
|
||||
</button>
|
||||
{order.customer_id && (
|
||||
<button
|
||||
onClick={() => tabItem.mutate(item.id)}
|
||||
style={{ fontSize: 12, padding: '0 8px', height: 32, borderRadius: 6, border: '1px solid #bfdbfe', background: '#eff6ff', color: '#1d4ed8', cursor: 'pointer', fontWeight: 600, whiteSpace: 'nowrap' }}
|
||||
>
|
||||
📋 Καρτέλα
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => setConfirmAction({ type: 'cancelItem', payload: item.id })}
|
||||
className="btn btn-danger text-xs px-2 py-1 min-h-0 h-8"
|
||||
>
|
||||
Ακύρωση
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{item.status === 'tabbed' && (
|
||||
<span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: '#eff6ff', color: '#1d4ed8', border: '1px solid #bfdbfe' }}>
|
||||
📋 Καρτέλα
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{isOpen && !readOnly && activeItems.length > 0 && (
|
||||
<button
|
||||
onClick={() => requestPay(activeItems.map(i => i.id))}
|
||||
className="btn btn-primary"
|
||||
>
|
||||
Πληρωμή όλων
|
||||
</button>
|
||||
)}
|
||||
{isOpen && !readOnly && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => setConfirmAction({ type: 'closeOrder' })}
|
||||
className="btn btn-secondary"
|
||||
>
|
||||
Κλείσιμο παραγγελίας
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setConfirmAction({ type: 'cancelOrder' })}
|
||||
className="btn btn-danger"
|
||||
>
|
||||
Ακύρωση παραγγελίας
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
onClick={() => setShowPrintModal(true)}
|
||||
className="btn btn-secondary"
|
||||
>
|
||||
🖨 Εκτύπωση
|
||||
</button>
|
||||
</div>
|
||||
</>}
|
||||
|
||||
{tab === 'pricing' && (
|
||||
<div className="card divide-y divide-gray-100">
|
||||
<PriceEventsTab orderId={orderId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === 'audit' && (
|
||||
<div className="card divide-y divide-gray-100">
|
||||
<AuditTab order={order} waiterMap={waiterMap} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{payPending && (
|
||||
<PaymentMethodModal
|
||||
onSelect={confirmPay}
|
||||
onCancel={() => setPayPending(null)}
|
||||
title={payPending.length === 1 ? 'Τρόπος Πληρωμής;' : `Πληρωμή ${payPending.length} αντικειμένων;`}
|
||||
/>
|
||||
)}
|
||||
|
||||
{confirmAction && (
|
||||
<ConfirmModal
|
||||
title={
|
||||
confirmAction.type === 'cancelItem' ? 'Ακύρωση αντικειμένου;' :
|
||||
confirmAction.type === 'cancelOrder' ? 'Ακύρωση παραγγελίας;' :
|
||||
'Κλείσιμο παραγγελίας;'
|
||||
}
|
||||
message={
|
||||
confirmAction.type === 'cancelOrder'
|
||||
? 'Η παραγγελία θα ακυρωθεί οριστικά.'
|
||||
: undefined
|
||||
}
|
||||
confirmLabel={confirmAction.type === 'closeOrder' ? 'Κλείσιμο' : 'Ακύρωση'}
|
||||
confirmVariant={confirmAction.type === 'closeOrder' ? 'primary' : 'danger'}
|
||||
onConfirm={handleConfirm}
|
||||
onCancel={() => setConfirmAction(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showPrintModal && printers.length > 0 && (
|
||||
<PrintOrderModal
|
||||
printers={printers}
|
||||
onClose={() => setShowPrintModal(false)}
|
||||
onPrint={(printerId) => printOrder.mutate(printerId)}
|
||||
/>
|
||||
)}
|
||||
{showPrintModal && printers.length === 0 && (
|
||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
|
||||
<div className="bg-white rounded-2xl p-6 max-w-sm w-full mx-4 space-y-4">
|
||||
<p className="text-gray-700">Δεν βρέθηκαν ενεργοί εκτυπωτές.</p>
|
||||
<button onClick={() => setShowPrintModal(false)} className="btn btn-secondary w-full">Κλείσιμο</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,836 +0,0 @@
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import toast from 'react-hot-toast'
|
||||
import client from '../api/client'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import LiveFloor from './floor/LiveFloor'
|
||||
|
||||
function relativeTime(isoStr) {
|
||||
if (!isoStr) return ''
|
||||
const diffMs = Date.now() - new Date(isoStr).getTime()
|
||||
const diffMins = Math.floor(diffMs / 60000)
|
||||
if (diffMins < 1) return 'μόλις τώρα'
|
||||
if (diffMins < 60) return `πριν ${diffMins}λ`
|
||||
const h = Math.floor(diffMins / 60)
|
||||
if (h < 24) return `πριν ${h}ω`
|
||||
return `πριν ${Math.floor(h / 24)}μ`
|
||||
}
|
||||
|
||||
function FlagsDetailModal({ flags, tableName, onClose }) {
|
||||
return (
|
||||
<div style={{
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 9999,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
|
||||
}} onClick={onClose}>
|
||||
<div style={{
|
||||
background: 'white', borderRadius: 16, width: '100%', maxWidth: 360,
|
||||
padding: 20, boxShadow: '0 16px 48px rgba(0,0,0,0.18)',
|
||||
}} onClick={e => e.stopPropagation()}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
|
||||
<div style={{ fontSize: 15, fontWeight: 700, color: '#111315' }}>Σημαίες — {tableName}</div>
|
||||
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#8a9099' }}>✕</button>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{flags.map(f => (
|
||||
<div key={f.id} style={{
|
||||
display: 'flex', alignItems: 'center', gap: 12,
|
||||
padding: '10px 12px', borderRadius: 10,
|
||||
background: (f.color || '#6b7280') + '11',
|
||||
border: `1px solid ${(f.color || '#6b7280')}33`,
|
||||
}}>
|
||||
{f.emoji && <span style={{ fontSize: 20 }}>{f.emoji}</span>}
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 14, fontWeight: 600, color: f.color || '#374151' }}>{f.name}</div>
|
||||
{f.assigned_at && (
|
||||
<div style={{ fontSize: 11, color: '#8a9099', marginTop: 1 }}>{relativeTime(f.assigned_at)}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: 'open', label: 'Ανοιχτά' },
|
||||
{ value: 'partially_paid', label: 'Μερική πληρωμή' },
|
||||
{ value: 'paid', label: 'Πλήρως πληρωμένο' },
|
||||
{ value: 'free', label: 'Ελεύθερα' },
|
||||
]
|
||||
|
||||
const COLORS = {
|
||||
open: {
|
||||
label: 'Ανοιχτό',
|
||||
tint: '#eef7f0', tintStrong: '#d7ecdc',
|
||||
accent: '#2f9e5e', ink: '#1f7042',
|
||||
},
|
||||
partially_paid: {
|
||||
label: 'Μερική πληρ.',
|
||||
tint: '#f4eefb', tintStrong: '#e3d4f3',
|
||||
accent: '#7a44c9', ink: '#57309a',
|
||||
},
|
||||
paid: {
|
||||
label: 'Πλήρως πληρωμένο',
|
||||
tint: '#eff6ff', tintStrong: '#dbeafe',
|
||||
accent: '#2563eb', ink: '#1d4ed8',
|
||||
},
|
||||
free: {
|
||||
label: 'Ελεύθερο',
|
||||
tint: '#f4f4f2', tintStrong: '#dfe2e6',
|
||||
accent: '#8a9099', ink: '#5a6169',
|
||||
},
|
||||
}
|
||||
|
||||
function formatEuro(n) {
|
||||
return '€' + parseFloat(n).toFixed(2)
|
||||
}
|
||||
|
||||
function formatDuration(openedAt) {
|
||||
const mins = Math.floor((Date.now() - new Date(openedAt).getTime()) / 60000)
|
||||
if (mins < 60) return `${mins}m`
|
||||
const h = Math.floor(mins / 60)
|
||||
const m = mins % 60
|
||||
return m === 0 ? `${h}h` : `${h}h ${m}m`
|
||||
}
|
||||
|
||||
function occupiedMinsFromDate(openedAt) {
|
||||
return Math.floor((Date.now() - new Date(openedAt).getTime()) / 60000)
|
||||
}
|
||||
|
||||
function orderTotal(items = []) {
|
||||
return items
|
||||
.filter(i => i.status !== 'cancelled')
|
||||
.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
|
||||
}
|
||||
|
||||
function avatarColor(name) {
|
||||
const palette = ['#3758c9', '#7a44c9', '#2f9e5e', '#d94b26', '#8a6d2b', '#0d7a8a', '#c93775']
|
||||
let h = 0
|
||||
for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0
|
||||
return palette[h % palette.length]
|
||||
}
|
||||
|
||||
function WaiterBubble({ waiter, size = 26 }) {
|
||||
if (waiter.avatarUrl) {
|
||||
return (
|
||||
<img src={waiter.avatarUrl} alt={waiter.name}
|
||||
style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flexShrink: 0, boxShadow: '0 0 0 2px var(--cardBg, white)' }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
const parts = waiter.name.trim().split(' ')
|
||||
const initials = (parts[0][0] + (parts[1]?.[0] || '')).toUpperCase()
|
||||
return (
|
||||
<div style={{
|
||||
width: size, height: size, borderRadius: '50%',
|
||||
background: avatarColor(waiter.name), color: 'white',
|
||||
fontSize: size * 0.42, fontWeight: 600,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
flexShrink: 0, boxShadow: '0 0 0 2px var(--cardBg, white)',
|
||||
}}>{initials}</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Quick action modal ────────────────────────────────────────────────────────
|
||||
|
||||
function QuickActionModal({ table, order, flagDefs, currentFlags, waiters, templates, onClose, onDone }) {
|
||||
const qc = useQueryClient()
|
||||
const [selectedFlagIds, setSelectedFlagIds] = useState((currentFlags || []).map(f => f.id))
|
||||
const [notifyMsg, setNotifyMsg] = useState('')
|
||||
const [notifyAll, setNotifyAll] = useState(true)
|
||||
const [notifyWaiters, setNotifyWaiters] = useState(false)
|
||||
const [sending, setSending] = useState(false)
|
||||
|
||||
const setFlagsMut = useMutation({
|
||||
mutationFn: () => client.put(`/api/flags/table/${table.id}`, { flag_ids: selectedFlagIds }),
|
||||
onSuccess: () => qc.invalidateQueries({ queryKey: ['flag-assignments'] }),
|
||||
})
|
||||
|
||||
function toggleFlag(id) {
|
||||
setSelectedFlagIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
|
||||
}
|
||||
|
||||
async function save() {
|
||||
setSending(true)
|
||||
try {
|
||||
await setFlagsMut.mutateAsync()
|
||||
if (notifyWaiters && notifyMsg.trim() && order) {
|
||||
const waiterIds = notifyAll ? [] : order.waiters.map(w => w.waiter_id)
|
||||
await client.post('/api/notifications/send', {
|
||||
body: notifyMsg.trim(),
|
||||
target_waiter_ids: waiterIds,
|
||||
table_ids: [table.id],
|
||||
})
|
||||
toast.success('Σημαίες + ειδοποίηση εστάλη!')
|
||||
} else {
|
||||
toast.success('Σημαίες ενημερώθηκαν')
|
||||
}
|
||||
onDone()
|
||||
onClose()
|
||||
} catch {
|
||||
toast.error('Σφάλμα')
|
||||
} finally {
|
||||
setSending(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', zIndex: 9999,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
|
||||
}} onClick={onClose}>
|
||||
<div style={{
|
||||
background: 'white', borderRadius: 20, width: '100%', maxWidth: 460,
|
||||
padding: 24, boxShadow: '0 24px 64px rgba(0,0,0,0.22)',
|
||||
}} onClick={e => e.stopPropagation()}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
|
||||
<div style={{ fontSize: 15, fontWeight: 700 }}>⚡ {table.label || `T${table.number}`}</div>
|
||||
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: '#8a9099' }}>✕</button>
|
||||
</div>
|
||||
|
||||
<div style={{ fontSize: 12, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>Σημαίες</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 20 }}>
|
||||
{flagDefs.map(f => {
|
||||
const sel = selectedFlagIds.includes(f.id)
|
||||
return (
|
||||
<button key={f.id} onClick={() => toggleFlag(f.id)} style={{
|
||||
height: 30, padding: '0 12px', borderRadius: 999,
|
||||
border: `1.5px solid ${sel ? f.color : '#dfe2e6'}`,
|
||||
background: sel ? (f.color + '22') : 'white',
|
||||
color: sel ? f.color : '#374151',
|
||||
fontSize: 12, fontWeight: sel ? 700 : 500, cursor: 'pointer',
|
||||
display: 'flex', alignItems: 'center', gap: 5,
|
||||
}}>
|
||||
{f.emoji && <span>{f.emoji}</span>}
|
||||
{f.name}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{order && (
|
||||
<>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, cursor: 'pointer' }}>
|
||||
<input type="checkbox" checked={notifyWaiters} onChange={e => setNotifyWaiters(e.target.checked)} />
|
||||
<span style={{ fontSize: 13, color: '#374151', fontWeight: 500 }}>Ειδοποίησε τους σερβιτόρους</span>
|
||||
</label>
|
||||
|
||||
{notifyWaiters && (
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
|
||||
{templates.slice(0, 4).map(t => (
|
||||
<button key={t.id} onClick={() => setNotifyMsg(t.body)} style={{
|
||||
height: 26, padding: '0 10px', borderRadius: 6,
|
||||
border: `1px solid ${notifyMsg === t.body ? '#3758c9' : '#dfe2e6'}`,
|
||||
background: notifyMsg === t.body ? '#eff3ff' : '#f9fafb',
|
||||
color: notifyMsg === t.body ? '#3758c9' : '#374151',
|
||||
fontSize: 11, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap',
|
||||
}}>{t.body}</button>
|
||||
))}
|
||||
</div>
|
||||
<input
|
||||
value={notifyMsg}
|
||||
onChange={e => setNotifyMsg(e.target.value)}
|
||||
placeholder="Ή γράψτε μήνυμα…"
|
||||
style={{ width: '100%', height: 36, borderRadius: 8, border: '1px solid #dfe2e6', padding: '0 12px', fontSize: 13, fontFamily: 'inherit', boxSizing: 'border-box' }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
|
||||
<button onClick={onClose} style={{ height: 36, padding: '0 16px', borderRadius: 8, border: '1px solid #dfe2e6', background: 'white', fontSize: 13, cursor: 'pointer' }}>Άκυρο</button>
|
||||
<button onClick={save} disabled={sending} style={{ height: 36, padding: '0 18px', borderRadius: 8, background: '#3758c9', color: 'white', border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
|
||||
{sending ? 'Αποθήκευση…' : 'Αποθήκευση'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
function FlagPills({ flags, displayMode = 'both', onOverflowClick }) {
|
||||
if (flags.length === 0) return null
|
||||
const MAX_VISIBLE = 3
|
||||
const visible = flags.slice(0, MAX_VISIBLE)
|
||||
const overflow = flags.length - MAX_VISIBLE
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 4, overflow: 'hidden', flexWrap: 'nowrap', minWidth: 0 }}>
|
||||
{visible.map(f => (
|
||||
<span key={f.id} style={{
|
||||
fontSize: 11, fontWeight: 600, borderRadius: 999, padding: '2px 7px',
|
||||
background: (f.color || '#6b7280') + '22',
|
||||
color: f.color || '#6b7280',
|
||||
border: `1px solid ${f.color || '#6b7280'}55`,
|
||||
display: 'inline-flex', alignItems: 'center', gap: 3,
|
||||
whiteSpace: 'nowrap', flexShrink: 0,
|
||||
}}>
|
||||
{(displayMode === 'icon' || displayMode === 'both') && f.emoji && <span style={{ fontSize: 12 }}>{f.emoji}</span>}
|
||||
{(displayMode === 'text' || displayMode === 'both') && <span>{f.name}</span>}
|
||||
</span>
|
||||
))}
|
||||
{overflow > 0 && (
|
||||
<button
|
||||
onClick={e => { e.stopPropagation(); onOverflowClick?.() }}
|
||||
title={`+${overflow} ακόμα σημαίες`}
|
||||
style={{
|
||||
fontSize: 11, fontWeight: 700, borderRadius: 999, padding: '2px 7px',
|
||||
background: '#f0f4ff', color: '#3758c9', border: '1px solid #c2cff0',
|
||||
whiteSpace: 'nowrap', flexShrink: 0, cursor: 'pointer',
|
||||
}}
|
||||
>+{overflow}</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCardV1({ name, status, amount, openedAt, waiters = [], hasPendingPrint = false, flags = [], flagDisplayMode = 'both', upcomingReservation = null, onClick, onQuickAction, onFlagsClick }) {
|
||||
const s = COLORS[status] || COLORS.free
|
||||
const [hover, setHover] = useState(false)
|
||||
const [pressed, setPressed] = useState(false)
|
||||
const occupiedMins = openedAt ? occupiedMinsFromDate(openedAt) : null
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
onMouseEnter={() => setHover(true)}
|
||||
onMouseLeave={() => { setHover(false); setPressed(false) }}
|
||||
onMouseDown={() => setPressed(true)}
|
||||
onMouseUp={() => setPressed(false)}
|
||||
style={{
|
||||
'--cardBg': s.tint,
|
||||
position: 'relative', width: '100%', minWidth: 330, height: 200,
|
||||
padding: '16px 18px 16px 24px',
|
||||
background: s.tint, border: '1px solid ' + s.tintStrong, borderRadius: 14,
|
||||
boxShadow: pressed
|
||||
? 'inset 0 2px 4px rgba(16,20,24,0.08)'
|
||||
: hover
|
||||
? '0 6px 18px rgba(16,20,24,0.08), 0 2px 4px rgba(16,20,24,0.04)'
|
||||
: '0 1px 2px rgba(16,20,24,0.04), 0 1px 1px rgba(16,20,24,0.03)',
|
||||
transform: pressed ? 'translateY(1px)' : hover ? 'translateY(-2px)' : 'translateY(0)',
|
||||
transition: 'transform 120ms ease, box-shadow 120ms ease',
|
||||
cursor: onClick ? 'pointer' : 'default',
|
||||
textAlign: 'left', font: 'inherit', color: 'inherit',
|
||||
display: 'flex', flexDirection: 'column', outline: 'none', flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
<div style={{
|
||||
position: 'absolute', left: 0, top: 0, bottom: 0, width: 6,
|
||||
background: s.accent, borderRadius: '14px 0 0 14px',
|
||||
}} />
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
|
||||
<div style={{
|
||||
fontSize: 34, fontWeight: 700, lineHeight: 1, letterSpacing: -0.5,
|
||||
color: '#111315', fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
|
||||
}}>{name}</div>
|
||||
<div style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
height: 26, padding: '0 10px', borderRadius: 999,
|
||||
background: s.accent, color: 'white',
|
||||
fontSize: 12, fontWeight: 600, letterSpacing: 0.2,
|
||||
whiteSpace: 'nowrap', flexShrink: 0,
|
||||
}}>
|
||||
<span style={{ width: 6, height: 6, borderRadius: '50%', background: 'rgba(255,255,255,0.9)' }} />
|
||||
{s.label}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginTop: 6, minHeight: 22, display: 'flex', alignItems: 'center', gap: 4, overflow: 'hidden' }}>
|
||||
{hasPendingPrint && (
|
||||
<span style={{
|
||||
fontSize: 11, fontWeight: 700, background: '#92400e', color: '#fcd34d',
|
||||
borderRadius: 999, padding: '2px 8px', flexShrink: 0,
|
||||
display: 'inline-flex', alignItems: 'center', gap: 4,
|
||||
}}>⏳</span>
|
||||
)}
|
||||
{upcomingReservation && (
|
||||
<span title={`${upcomingReservation.guest_name} · ${upcomingReservation.party_size} άτομα · ${new Date(upcomingReservation.reserved_for).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })}`} style={{
|
||||
fontSize: 11, fontWeight: 700, background: '#4f46e5', color: '#e0e7ff',
|
||||
borderRadius: 999, padding: '2px 8px', flexShrink: 0,
|
||||
display: 'inline-flex', alignItems: 'center', gap: 4,
|
||||
}}>
|
||||
🔒 RESERVED · {new Date(upcomingReservation.reserved_for).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })}
|
||||
</span>
|
||||
)}
|
||||
<FlagPills
|
||||
flags={flags}
|
||||
displayMode={flagDisplayMode}
|
||||
onOverflowClick={onFlagsClick}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ marginTop: 'auto', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, alignItems: 'end' }}>
|
||||
<div>
|
||||
<div style={{ fontSize: 11, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.6 }}>Total</div>
|
||||
<div style={{ fontSize: 22, fontWeight: 600, color: '#111315', marginTop: 2, fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace" }}>
|
||||
{amount != null ? formatEuro(amount) : <span style={{ color: '#b8bdc4', letterSpacing: 2 }}>— —</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ fontSize: 11, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.6 }}>Time</div>
|
||||
<div style={{
|
||||
fontSize: 22, marginTop: 2,
|
||||
fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
|
||||
fontWeight: occupiedMins != null && occupiedMins >= 90 ? 700 : 500,
|
||||
color: '#111315',
|
||||
}}>
|
||||
{openedAt ? formatDuration(openedAt) : <span style={{ color: '#b8bdc4', letterSpacing: 2 }}>— —</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{
|
||||
marginTop: 12, paddingTop: 10,
|
||||
borderTop: '1px solid ' + s.tintStrong,
|
||||
height: 36, display: 'flex', alignItems: 'center', gap: 8,
|
||||
}}>
|
||||
{waiters.length === 0 ? (
|
||||
<span style={{ color: '#8a9099', fontSize: 13 }}>Unassigned</span>
|
||||
) : waiters.length >= 3 ? (
|
||||
<>
|
||||
<div style={{ display: 'flex' }}>
|
||||
{waiters.slice(0, 3).map((w, i) => (
|
||||
<div key={i} style={{ marginLeft: i === 0 ? 0 : -8 }}>
|
||||
<WaiterBubble waiter={w} size={24} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<span style={{
|
||||
fontSize: 13, fontWeight: 600, color: '#2b2f33',
|
||||
background: 'white', border: '1px solid #dfe2e6',
|
||||
borderRadius: 999, padding: '2px 8px',
|
||||
}}>Multiple ({waiters.length})</span>
|
||||
</>
|
||||
) : (
|
||||
waiters.map((w, i) => (
|
||||
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<WaiterBubble waiter={w} size={24} />
|
||||
<span style={{ fontSize: 14, color: '#2b2f33', fontWeight: 500 }}>{w.shortName}</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
{onQuickAction && (
|
||||
<button
|
||||
onClick={e => { e.stopPropagation(); onQuickAction() }}
|
||||
title="Γρήγορες ενέργειες"
|
||||
style={{
|
||||
marginLeft: 'auto', width: 28, height: 28, borderRadius: 8, flexShrink: 0,
|
||||
border: '1px solid ' + s.tintStrong, background: 'white',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
fontSize: 14, cursor: 'pointer', color: '#5a6169',
|
||||
}}
|
||||
>⚡</button>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Multi-select dropdown ─────────────────────────────────────────────────────
|
||||
|
||||
function MultiSelectDropdown({ label, options, selected, onChange, allLabel = 'Όλα' }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const ref = useRef(null)
|
||||
|
||||
useEffect(() => {
|
||||
function handleClick(e) {
|
||||
if (ref.current && !ref.current.contains(e.target)) setOpen(false)
|
||||
}
|
||||
document.addEventListener('mousedown', handleClick)
|
||||
return () => document.removeEventListener('mousedown', handleClick)
|
||||
}, [])
|
||||
|
||||
const allSelected = selected.length === 0
|
||||
const displayLabel = allSelected
|
||||
? allLabel
|
||||
: selected.length === 1
|
||||
? options.find(o => o.value === selected[0])?.label ?? selected[0]
|
||||
: `${selected.length} επιλεγμένα`
|
||||
|
||||
function toggle(value) {
|
||||
if (selected.includes(value)) {
|
||||
onChange(selected.filter(v => v !== value))
|
||||
} else {
|
||||
onChange([...selected, value])
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={ref} style={{ position: 'relative' }}>
|
||||
<button
|
||||
onClick={() => setOpen(o => !o)}
|
||||
style={{
|
||||
height: 36, padding: '0 14px',
|
||||
borderRadius: 8, border: '1px solid #dfe2e6',
|
||||
background: allSelected ? 'white' : '#f0f4ff',
|
||||
color: allSelected ? '#374151' : '#3758c9',
|
||||
fontSize: 13, fontWeight: allSelected ? 500 : 600,
|
||||
cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8,
|
||||
whiteSpace: 'nowrap', fontFamily: 'inherit',
|
||||
boxShadow: open ? '0 0 0 2px #c2cff0' : 'none',
|
||||
transition: 'box-shadow 100ms',
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: 11, color: '#8a9099', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginRight: 2 }}>{label}</span>
|
||||
{displayLabel}
|
||||
<span style={{ fontSize: 10, color: '#8a9099', marginLeft: 2 }}>{open ? '▲' : '▼'}</span>
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div style={{
|
||||
position: 'absolute', top: '100%', left: 0, marginTop: 6, zIndex: 100,
|
||||
background: 'white', border: '1px solid #dfe2e6', borderRadius: 12,
|
||||
boxShadow: '0 8px 24px rgba(16,20,24,0.12)',
|
||||
minWidth: 180, overflow: 'hidden',
|
||||
}}>
|
||||
{/* All option */}
|
||||
<button
|
||||
onClick={() => { onChange([]); setOpen(false) }}
|
||||
style={{
|
||||
width: '100%', padding: '10px 14px',
|
||||
display: 'flex', alignItems: 'center', gap: 10,
|
||||
background: allSelected ? '#f0f4ff' : 'white',
|
||||
border: 'none', cursor: 'pointer', textAlign: 'left',
|
||||
fontSize: 13, fontWeight: allSelected ? 700 : 400,
|
||||
color: allSelected ? '#3758c9' : '#374151',
|
||||
fontFamily: 'inherit',
|
||||
borderBottom: '1px solid #f4f4f2',
|
||||
}}
|
||||
>
|
||||
<span style={{
|
||||
width: 16, height: 16, borderRadius: 4,
|
||||
border: '1.5px solid ' + (allSelected ? '#3758c9' : '#dfe2e6'),
|
||||
background: allSelected ? '#3758c9' : 'white',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
flexShrink: 0,
|
||||
}}>
|
||||
{allSelected && <span style={{ color: 'white', fontSize: 10, fontWeight: 700 }}>✓</span>}
|
||||
</span>
|
||||
{allLabel}
|
||||
</button>
|
||||
{options.map(opt => {
|
||||
const checked = selected.includes(opt.value)
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
onClick={() => toggle(opt.value)}
|
||||
style={{
|
||||
width: '100%', padding: '10px 14px',
|
||||
display: 'flex', alignItems: 'center', gap: 10,
|
||||
background: checked ? '#f9f5ff' : 'white',
|
||||
border: 'none', cursor: 'pointer', textAlign: 'left',
|
||||
fontSize: 13, fontWeight: checked ? 600 : 400,
|
||||
color: checked ? '#57309a' : '#374151',
|
||||
fontFamily: 'inherit',
|
||||
borderBottom: '1px solid #f9f9f8',
|
||||
}}
|
||||
>
|
||||
<span style={{
|
||||
width: 16, height: 16, borderRadius: 4,
|
||||
border: '1.5px solid ' + (checked ? '#7a44c9' : '#dfe2e6'),
|
||||
background: checked ? '#7a44c9' : 'white',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
flexShrink: 0,
|
||||
}}>
|
||||
{checked && <span style={{ color: 'white', fontSize: 10, fontWeight: 700 }}>✓</span>}
|
||||
</span>
|
||||
{opt.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export default function TablesPage() {
|
||||
const { t } = useTranslation('common')
|
||||
const [view, setView] = useState('list') // list | map (6.8: the floor plans, live)
|
||||
const [statusFilter, setStatusFilter] = useState([])
|
||||
const [zoneFilter, setZoneFilter] = useState([])
|
||||
const [retryingId, setRetryingId] = useState(null)
|
||||
const [quickActionTarget, setQuickActionTarget] = useState(null)
|
||||
const [flagsDetail, setFlagsDetail] = useState(null) // { flags, tableName }
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const { data: tables = [], isLoading: tablesLoading } = useQuery({
|
||||
queryKey: ['tables'],
|
||||
queryFn: () => client.get('/api/tables/').then(r => r.data),
|
||||
refetchInterval: 5_000,
|
||||
})
|
||||
|
||||
const { data: orders = [], isLoading: ordersLoading } = useQuery({
|
||||
queryKey: ['orders-active'],
|
||||
queryFn: () => client.get('/api/orders/').then(r => r.data),
|
||||
refetchInterval: 5_000,
|
||||
})
|
||||
|
||||
const { data: flagDefs = [] } = useQuery({
|
||||
queryKey: ['flag-defs'],
|
||||
queryFn: () => client.get('/api/flags/defs').then(r => r.data),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const { data: flagAssignments = [] } = useQuery({
|
||||
queryKey: ['flag-assignments'],
|
||||
queryFn: () => client.get('/api/flags/assignments').then(r => r.data),
|
||||
refetchInterval: 10_000,
|
||||
staleTime: 8_000,
|
||||
})
|
||||
|
||||
// Build map: tableId -> { def, assigned_at }[]
|
||||
const flagDefMap = Object.fromEntries(flagDefs.map(f => [f.id, f]))
|
||||
const tableFlagsMap = {}
|
||||
flagAssignments.forEach(a => {
|
||||
if (!tableFlagsMap[a.table_id]) tableFlagsMap[a.table_id] = []
|
||||
const def = flagDefMap[a.flag_id]
|
||||
if (def) tableFlagsMap[a.table_id].push({ ...def, assigned_at: a.assigned_at })
|
||||
})
|
||||
|
||||
const { data: waiters = [] } = useQuery({
|
||||
queryKey: ['waiters'],
|
||||
queryFn: () => client.get('/api/waiters/').then(r => r.data),
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const { data: quickTemplates = [] } = useQuery({
|
||||
queryKey: ['quick-templates'],
|
||||
queryFn: () => client.get('/api/notifications/templates').then(r => r.data),
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const { data: groups = [] } = useQuery({
|
||||
queryKey: ['table-groups'],
|
||||
queryFn: () => client.get('/api/tables/groups').then(r => r.data),
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const { data: posSettings } = useQuery({
|
||||
queryKey: ['pos-settings'],
|
||||
queryFn: () => client.get('/api/settings/').then(r => r.data),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
const flagDisplayMode = posSettings?.['flags.display_mode']?.value ?? 'both'
|
||||
|
||||
const waiterMap = Object.fromEntries(waiters.map(w => {
|
||||
const name = w.full_name || w.nickname || w.username
|
||||
const shortName = w.nickname || (w.full_name ? w.full_name.split(' ')[0] : w.username)
|
||||
const avatarUrl = w.avatar_url ?? null
|
||||
return [w.id, { name, shortName, avatarUrl }]
|
||||
}))
|
||||
|
||||
const tableCards = tables.map(table => {
|
||||
const order = orders.find(o =>
|
||||
o.table_id === table.id && ['open', 'partially_paid', 'paid'].includes(o.status)
|
||||
)
|
||||
const tableStatus = order ? order.status : 'free'
|
||||
const hasPendingPrint = order ? order.items.some(i => i.status === 'active' && !i.printed) : false
|
||||
const tableFlags = tableFlagsMap[table.id] || []
|
||||
return { table, order, tableStatus, hasPendingPrint, tableFlags }
|
||||
})
|
||||
|
||||
const pendingPrintOrders = tableCards.filter(c => c.hasPendingPrint)
|
||||
|
||||
async function retrySingleOrder(orderId) {
|
||||
setRetryingId(orderId)
|
||||
try {
|
||||
const res = await client.post(`/api/orders/${orderId}/retry-print`)
|
||||
const results = res.data.print_results ?? []
|
||||
const allOk = results.length === 0 || results.every(r => r.success)
|
||||
if (allOk) toast.success('Εκτυπώθηκε επιτυχώς')
|
||||
else {
|
||||
const failed = results.filter(r => !r.success).map(r => r.printer_name).join(', ')
|
||||
toast.error(`Αποτυχία: ${failed}`)
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['orders-active'] })
|
||||
} catch {
|
||||
toast.error('Σφάλμα επικοινωνίας')
|
||||
} finally {
|
||||
setRetryingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function retryAllOrders() {
|
||||
for (const { order } of pendingPrintOrders) {
|
||||
if (order) await retrySingleOrder(order.id)
|
||||
}
|
||||
}
|
||||
|
||||
// Build zone options from groups + "Χωρίς ζώνη"
|
||||
const zoneOptions = [
|
||||
...groups.map(g => ({ value: String(g.id), label: g.name })),
|
||||
{ value: '__none__', label: 'Χωρίς ζώνη' },
|
||||
]
|
||||
|
||||
// Apply filters
|
||||
const filtered = tableCards.filter(c => {
|
||||
const statusOk = statusFilter.length === 0 || statusFilter.includes(c.tableStatus)
|
||||
let zoneOk = true
|
||||
if (zoneFilter.length > 0) {
|
||||
const tableGroupId = c.table.group_id ? String(c.table.group_id) : null
|
||||
if (zoneFilter.includes('__none__') && zoneFilter.length === 1) {
|
||||
zoneOk = !tableGroupId
|
||||
} else if (zoneFilter.includes('__none__')) {
|
||||
zoneOk = !tableGroupId || zoneFilter.includes(tableGroupId)
|
||||
} else {
|
||||
zoneOk = tableGroupId !== null && zoneFilter.includes(tableGroupId)
|
||||
}
|
||||
}
|
||||
return statusOk && zoneOk
|
||||
})
|
||||
|
||||
if (tablesLoading || ordersLoading) {
|
||||
return <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-y-auto h-full p-6 space-y-6">
|
||||
{flagsDetail && (
|
||||
<FlagsDetailModal
|
||||
flags={flagsDetail.flags}
|
||||
tableName={flagsDetail.tableName}
|
||||
onClose={() => setFlagsDetail(null)}
|
||||
/>
|
||||
)}
|
||||
{quickActionTarget && (
|
||||
<QuickActionModal
|
||||
table={quickActionTarget.table}
|
||||
order={quickActionTarget.order}
|
||||
flagDefs={flagDefs}
|
||||
currentFlags={quickActionTarget.currentFlags}
|
||||
waiters={waiters}
|
||||
templates={quickTemplates}
|
||||
onClose={() => setQuickActionTarget(null)}
|
||||
onDone={() => queryClient.invalidateQueries({ queryKey: ['flag-assignments'] })}
|
||||
/>
|
||||
)}
|
||||
<div className="flex items-center justify-end flex-wrap gap-3">
|
||||
<div className="flex rounded-control border border-line overflow-hidden mr-auto" role="group">
|
||||
{['list', 'map'].map(v => (
|
||||
<button key={v} type="button" aria-pressed={view === v} onClick={() => setView(v)} data-testid={`tables-view-${v}`}
|
||||
className={`px-3 py-1.5 text-label font-medium ${view === v ? 'bg-accent-soft text-accent-ink' : 'bg-surface text-ink-2 hover:bg-surface-2'}`}>
|
||||
{t(`floorMap.${v}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
|
||||
<MultiSelectDropdown
|
||||
label="Κατάσταση"
|
||||
options={STATUS_OPTIONS}
|
||||
selected={statusFilter}
|
||||
onChange={setStatusFilter}
|
||||
allLabel="Όλες οι καταστάσεις"
|
||||
/>
|
||||
<MultiSelectDropdown
|
||||
label="Ζώνη"
|
||||
options={zoneOptions}
|
||||
selected={zoneFilter}
|
||||
onChange={setZoneFilter}
|
||||
allLabel="Όλες οι ζώνες"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{view === 'map' && <LiveFloor zone={zoneFilter.length === 1 && zoneFilter[0] !== '__none__' ? Number(zoneFilter[0]) : null} onOpen={id => navigate(`/orders/${id}`)} />}
|
||||
|
||||
{view === 'list' && filtered.length === 0 && (
|
||||
<p className="text-center text-gray-400 py-16">Δεν βρέθηκαν τραπέζια.</p>
|
||||
)}
|
||||
|
||||
{view === 'list' && <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(330px, 1fr))', gap: 16 }}>
|
||||
{filtered.map(({ table, order, tableStatus, hasPendingPrint, tableFlags }) => {
|
||||
const waiterNames = order
|
||||
? order.waiters.map(w => waiterMap[w.waiter_id] || { name: `#${w.waiter_id}`, shortName: `#${w.waiter_id}`, avatarUrl: null })
|
||||
: []
|
||||
const amount = order ? orderTotal(order.items) : null
|
||||
|
||||
return (
|
||||
<TableCardV1
|
||||
key={table.id}
|
||||
name={table.label || `T${table.number}`}
|
||||
status={tableStatus}
|
||||
amount={amount}
|
||||
openedAt={order?.opened_at ?? null}
|
||||
waiters={waiterNames}
|
||||
hasPendingPrint={hasPendingPrint}
|
||||
flags={tableFlags}
|
||||
flagDisplayMode={flagDisplayMode}
|
||||
upcomingReservation={table.upcoming_reservation ?? null}
|
||||
onClick={order ? () => navigate(`/orders/${order.id}`) : undefined}
|
||||
onQuickAction={() => setQuickActionTarget({ table, order, currentFlags: tableFlags })}
|
||||
onFlagsClick={tableFlags.length > 3 ? () => setFlagsDetail({ flags: tableFlags, tableName: table.label || `T${table.number}` }) : undefined}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>}
|
||||
|
||||
{pendingPrintOrders.length > 0 && (
|
||||
<div className="bg-white rounded-2xl border border-orange-200 shadow-sm overflow-hidden">
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-orange-100" style={{ background: '#fff7ed' }}>
|
||||
<div className="flex items-center gap-3">
|
||||
<span style={{ fontSize: 20 }}>⏳</span>
|
||||
<div>
|
||||
<h2 className="text-base font-bold text-orange-900">Εκκρεμείς Εκτυπώσεις</h2>
|
||||
<p className="text-xs text-orange-700 mt-0.5">
|
||||
{pendingPrintOrders.length} παραγγελί{pendingPrintOrders.length !== 1 ? 'ες' : 'α'} δεν έχ{pendingPrintOrders.length !== 1 ? 'ουν' : 'ει'} σταλεί στην κουζίνα/μπαρ
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className="btn btn-primary text-sm"
|
||||
style={{ background: '#c2410c', borderColor: '#c2410c' }}
|
||||
onClick={retryAllOrders}
|
||||
disabled={retryingId !== null}
|
||||
>
|
||||
{retryingId !== null ? 'Αποστολή…' : 'Αποστολή Όλων'}
|
||||
</button>
|
||||
</div>
|
||||
<div className="divide-y divide-orange-50">
|
||||
{pendingPrintOrders.map(({ table, order }) => {
|
||||
const unprinted = order.items.filter(i => i.status === 'active' && !i.printed)
|
||||
const tableName = table.label || `T${table.number}`
|
||||
return (
|
||||
<div key={order.id} className="flex items-center gap-4 px-5 py-3">
|
||||
<div className="shrink-0 w-10 h-10 rounded-xl flex items-center justify-center font-bold text-sm"
|
||||
style={{ background: '#fff7ed', color: '#c2410c', border: '1px solid #fed7aa' }}>
|
||||
{tableName}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-semibold text-gray-800">
|
||||
{unprinted.length} αντικείμενο{unprinted.length !== 1 ? 'α' : ''} εκκρεμούν
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 truncate">
|
||||
{unprinted.map(i => i.product?.name || `#${i.product_id}`).join(', ')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<button className="btn btn-secondary text-xs" onClick={() => navigate(`/orders/${order.id}`)}>
|
||||
Λεπτομέρειες
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-primary text-xs"
|
||||
style={{ background: '#c2410c', borderColor: '#c2410c' }}
|
||||
onClick={() => retrySingleOrder(order.id)}
|
||||
disabled={retryingId === order.id}
|
||||
>
|
||||
{retryingId === order.id ? '…' : 'Εκτύπωση'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// Adding to a table's order from the manager (plan step 6.9), by the phones' rules: the menu
|
||||
// (GET /api/orders/menu: in-store prices, the counter's product shape), a tap adds a product (one
|
||||
// with a preference to pick opens its choices: the shared dialog, @xenia/ordering), the cart is
|
||||
// priced by the server (POST /api/orders/quote with the order, so deals and the order's sales
|
||||
// point count), and "Send" adds the lines by id (POST /api/orders/{id}/items; a new order is
|
||||
// opened first). Prices are never sent.
|
||||
import { useMemo, useState } from 'react'
|
||||
import toast from 'react-hot-toast'
|
||||
import { Minus, Plus, Search, Send, Trash2 } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import {
|
||||
ProductDialog, addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, setLineQty, toLine, unitOf, useQuote,
|
||||
} from '@xenia/ordering'
|
||||
import { Button, EmptyState, IconButton, Input, Spinner, Textarea, cx } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||
import { sendBody } from './orderLogic'
|
||||
|
||||
const SERVICE = '__service__'
|
||||
|
||||
export default function AddItems({ orderId, onSent, openOrder }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatMoney } = useFormat()
|
||||
const { data: menu } = useLiveQuery({ queryKey: ['ordering-menu'], queryFn: () => client.get('/api/orders/menu').then(r => r.data),
|
||||
events: ['products_changed', 'pricing.changed'], staleTime: 30_000 })
|
||||
const [category, setCategory] = useState(null)
|
||||
const [query, setQuery] = useState('')
|
||||
const [cart, setCart] = useState([])
|
||||
const [note, setNote] = useState('')
|
||||
const [choosing, setChoosing] = useState(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const fetchQuote = lines => client.post('/api/orders/quote', { order_id: orderId ?? undefined, order_type: 'here', lines }).then(r => r.data)
|
||||
const { quote, pending, error } = useQuote(fetchQuote, cart, String(orderId ?? 'new'))
|
||||
const products = useMemo(() => (menu?.products ?? []), [menu])
|
||||
const cats = useMemo(() => categoriesWithProducts((menu?.categories ?? []).filter(c => !c.parent_id), products.filter(p => !p.service)), [menu, products])
|
||||
const shown = query.trim() ? searchProducts(products, query)
|
||||
: category === SERVICE ? products.filter(p => p.service)
|
||||
: productsIn(products.filter(p => !p.service), category)
|
||||
const byId = id => products.find(p => p.id === id)
|
||||
|
||||
const tap = p => {
|
||||
if (!p.available) return
|
||||
if (needsChoices(p)) { setChoosing(p); return }
|
||||
const unit = unitOf(p)
|
||||
setCart(c => addLine(c, toLine(p, defaultSelection(p), unit ? unit.start : 1)))
|
||||
}
|
||||
const send = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const id = orderId ?? (await openOrder())
|
||||
const { data } = await client.post(`/api/orders/${id}/items`, sendBody(cart.map(line => ({ line })), note))
|
||||
const failed = (data.print_results ?? []).filter(r => !r.success)
|
||||
if (failed.length) toast.error(t('orders.add.notPrinted', { printers: failed.map(r => r.printer_name).join(', ') }))
|
||||
else toast.success(t('orders.add.sent'))
|
||||
setCart([])
|
||||
setNote('')
|
||||
onSent(id)
|
||||
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
|
||||
}
|
||||
|
||||
if (!menu) return <div className="flex justify-center p-6"><Spinner /></div>
|
||||
return (
|
||||
<section className="grid gap-3 content-start min-w-0" data-testid="order-add">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
|
||||
<Input value={query} onChange={e => setQuery(e.target.value)} placeholder={t('orders.add.search')} aria-label={t('orders.add.search')} className="pl-9" data-testid="order-search" />
|
||||
</div>
|
||||
</div>
|
||||
{!query.trim() && (
|
||||
<div className="flex flex-wrap gap-1.5" role="tablist">
|
||||
{[{ id: null, name: t('orders.add.all') }, ...cats, ...(products.some(p => p.service) ? [{ id: SERVICE, name: t('orders.add.service') }] : [])].map(c => (
|
||||
<button key={c.id ?? 'all'} type="button" role="tab" aria-selected={category === c.id} onClick={() => setCategory(c.id)}
|
||||
className={cx('px-3 py-1.5 rounded-full border text-label font-medium', category === c.id ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
|
||||
{c.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{shown.length === 0 ? <EmptyState compact title={t('orders.add.nothing')} /> : (
|
||||
<div className="grid gap-2 max-h-[45vh] overflow-y-auto pr-1" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(9.5rem, 1fr))' }}>
|
||||
{shown.map(p => (
|
||||
<button key={p.id} type="button" onClick={() => tap(p)} disabled={!p.available} data-testid="order-product" data-id={p.id} data-name={p.name}
|
||||
className={cx('min-h-20 p-2.5 rounded-control border text-left grid content-between gap-1 transition-colors duration-fast',
|
||||
p.available ? 'border-line bg-surface hover:border-accent hover:bg-accent-soft' : 'border-line bg-surface-2 opacity-50 cursor-not-allowed')}>
|
||||
<span className="text-label font-semibold text-ink line-clamp-2">{p.name}</span>
|
||||
<span className="text-caption text-ink-2 tabular-nums">{p.available ? formatMoney(p.price) : t('orders.add.soldOut')}{needsChoices(p) ? ' · …' : ''}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-2 p-3 rounded-card border border-line bg-surface shadow-raised" data-testid="order-cart">
|
||||
<h3 className="text-label font-semibold text-ink">{t('orders.add.toSend')}</h3>
|
||||
{cart.length === 0 ? <p className="text-caption text-ink-3">{t('orders.add.empty')}</p> : (
|
||||
<ul className="grid divide-y divide-line">
|
||||
{cart.map((line, i) => {
|
||||
const priced = quote?.lines?.[i]
|
||||
const p = byId(line.product_id)
|
||||
const unit = p ? unitOf(p) : null
|
||||
const step = unit ? unit.step : 1
|
||||
return (
|
||||
<li key={i} className="py-1.5 flex items-center gap-2" data-testid="cart-line">
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block text-label font-medium text-ink truncate">{p?.name ?? priced?.name}</span>
|
||||
{priced?.entries?.length > 0 && <span className="block text-caption text-ink-2 truncate">{priced.entries.map(e => e.name).join(', ')}</span>}
|
||||
</span>
|
||||
<IconButton size="sm" variant="secondary" label={t('orders.add.less')} onClick={() => setCart(c => setLineQty(c, i, line.quantity - step))}>
|
||||
{line.quantity - step <= 0 ? <Trash2 size={14} /> : <Minus size={14} />}
|
||||
</IconButton>
|
||||
<span className="w-12 text-center text-label font-semibold tabular-nums" data-testid="cart-qty">{unit ? `${line.quantity} ${unit.label}` : line.quantity}</span>
|
||||
<IconButton size="sm" variant="secondary" label={t('orders.add.more')} onClick={() => setCart(c => setLineQty(c, i, line.quantity + step))}><Plus size={14} /></IconButton>
|
||||
<span className="w-20 text-right text-label tabular-nums">{priced ? formatMoney(priced.total) : '…'}</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
{error && <p role="alert" className="text-label text-danger-ink">{errorMessage(error, t)}</p>}
|
||||
<Textarea rows={2} maxLength={300} value={note} onChange={e => setNote(e.target.value)} placeholder={t('orders.add.note')} aria-label={t('orders.add.note')} />
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="flex-1 text-body font-semibold text-ink tabular-nums" data-testid="cart-total">
|
||||
{cart.length ? (quote && !pending ? formatMoney(quote.total) : '…') : ''}
|
||||
</span>
|
||||
{cart.length > 0 && <Button variant="ghost" onClick={() => setCart([])}>{t('orders.add.clear')}</Button>}
|
||||
<Button icon={<Send size={16} />} disabled={!cart.length || !!error} loading={busy} onClick={send} data-testid="order-send">{t('orders.add.send')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{choosing && <ProductDialog product={choosing} fetchQuote={fetchQuote} onClose={() => setChoosing(null)} onAdd={line => setCart(c => addLine(c, line))} />}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// What happened to a table's order (plan step 6.9): the audit log (opened, lines added, paid,
|
||||
// cancelled, closed; a payment counted twice stands out) and the price changes (rules, deals,
|
||||
// discounts, by whom).
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { EmptyState, cx } from '@xenia/ui'
|
||||
import { Pill } from '../overview/parts'
|
||||
import { nameOf } from './orderLogic'
|
||||
|
||||
const EVENT_TONE = { PAYMENT: 'success', PAYMENT_OFFLINE: 'success', ORDER_CLOSED: 'neutral', ORDER_CANCELLED: 'danger', ITEM_CANCELLED: 'danger' }
|
||||
const ids = raw => { try { return raw ? JSON.parse(raw) : [] } catch { return [] } }
|
||||
|
||||
export function AuditList({ order }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatDateTime, formatMoney } = useFormat()
|
||||
const logs = order.audit_logs ?? []
|
||||
if (!logs.length) return <EmptyState compact title={t('orders.history.none')} />
|
||||
const byId = new Map(order.items.map(i => [i.id, i]))
|
||||
return (
|
||||
<ul className="divide-y divide-line" data-testid="order-audit">
|
||||
{logs.map(log => {
|
||||
const dup = !!log.is_duplicate
|
||||
const names = ids(log.item_ids).map(id => byId.get(id)).filter(Boolean).map(i => `${nameOf(i)} ×${i.quantity}`)
|
||||
return (
|
||||
<li key={log.id} className={cx('px-4 py-2.5 flex items-start gap-3', dup && 'bg-danger-soft')}>
|
||||
<span className="grid gap-0.5 shrink-0">
|
||||
<Pill tone={dup ? 'danger' : EVENT_TONE[log.event_type] ?? 'info'}>{t(`orders.history.event.${log.event_type}`, { defaultValue: log.event_type })}</Pill>
|
||||
{dup && <span className="text-caption font-semibold text-danger-ink">{t('orders.history.duplicate')}</span>}
|
||||
</span>
|
||||
<span className="flex-1 min-w-0 grid gap-1 text-label text-ink">
|
||||
<span>
|
||||
{log.waiter_name ?? (log.waiter_id ? `#${log.waiter_id}` : '')}
|
||||
{log.amount != null && <span className="ml-2 font-semibold text-success-ink tabular-nums">{formatMoney(log.amount)}</span>}
|
||||
{log.payment_method && <span className="ml-2 text-ink-2">{t(`orders.pay.method.${log.payment_method}`, { defaultValue: log.payment_method })}</span>}
|
||||
</span>
|
||||
{names.length > 0 && <span className="flex flex-wrap gap-1">{names.map((n, i) => <Pill key={i}>{n}</Pill>)}</span>}
|
||||
{log.note && <span className="text-caption text-ink-3">{log.note}</span>}
|
||||
</span>
|
||||
<span className="text-caption text-ink-3 text-right shrink-0">
|
||||
{formatDateTime(log.offline_at || log.created_at, 'datetimeShort')}
|
||||
{log.offline_at && <span className="block text-warning-ink">{t('orders.history.offline')}</span>}
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
export function PriceEventList({ events }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatDateTime, formatMoney } = useFormat()
|
||||
if (!events.length) return <EmptyState compact title={t('orders.history.noPrices')} />
|
||||
return (
|
||||
<ul className="divide-y divide-line" data-testid="order-price-events">
|
||||
{events.map(ev => (
|
||||
<li key={ev.id} className="px-4 py-2.5 flex items-start gap-3">
|
||||
<Pill tone="info">{t(`orders.history.price.${ev.event_type}`, { defaultValue: ev.event_type })}</Pill>
|
||||
<span className="flex-1 min-w-0 grid gap-0.5 text-label text-ink">
|
||||
<span className="flex flex-wrap gap-x-3">
|
||||
{(ev.modifier_name || ev.deal_name) && <span className="font-semibold">{ev.modifier_name || ev.deal_name}</span>}
|
||||
{ev.applied_by_username && <span className="text-ink-3">{t('orders.history.by', { name: ev.applied_by_username })}</span>}
|
||||
{ev.delta_amount != null && (
|
||||
<span className={cx('font-semibold tabular-nums', ev.delta_amount < 0 ? 'text-success-ink' : 'text-danger-ink')}>
|
||||
{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}
|
||||
{ev.price_before != null && ev.price_after != null && <span className="font-normal text-ink-3"> ({formatMoney(ev.price_before)} → {formatMoney(ev.price_after)})</span>}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{ev.waiter_note && <span className="text-caption text-ink-3 italic">{ev.waiter_note}</span>}
|
||||
</span>
|
||||
<span className="text-caption text-ink-3 shrink-0">{formatDateTime(ev.applied_at, 'datetimeShort')}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// A table's order lines in the manager (plan step 6.9): what was ordered with its choices, who
|
||||
// paid what and how, price changes; pick unpaid lines to pay, discount, cancel or put on the
|
||||
// customer's tab. The rules are the phones' (a discount needs pricing.discounts.apply, the
|
||||
// server checks every key again).
|
||||
import { useState } from 'react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import toast from 'react-hot-toast'
|
||||
import { Ban, CreditCard, Percent, Printer, Receipt } from 'lucide-react'
|
||||
import { useCan } from '@xenia/access'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Field, Input, cx } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { Pill } from '../overview/parts'
|
||||
import { lineAmount, lineDetails, nameOf, selectable, selectedAmount, shownLines, toggleSelected, unitOf } from './orderLogic'
|
||||
|
||||
const STATUS_TONE = { paid: 'success', cancelled: 'danger', tabbed: 'info', closed: 'warning' }
|
||||
const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink' }
|
||||
|
||||
export default function OrderLines({ order, open, priceEvents, onPay, onChanged }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatMoney, formatTime } = useFormat()
|
||||
const canDiscount = useCan('pricing.discounts.apply')
|
||||
const [selected, setSelected] = useState([])
|
||||
const [cancelling, setCancelling] = useState(false)
|
||||
const [discounting, setDiscounting] = useState(false)
|
||||
const lines = shownLines(order)
|
||||
const picked = selected.filter(id => order.items.some(i => i.id === id && selectable(i)))
|
||||
const amount = selectedAmount(order, picked)
|
||||
const done = msg => { toast.success(msg); setSelected([]); onChanged() }
|
||||
const onError = err => toast.error(errorMessage(err, t))
|
||||
|
||||
const cancel = useMutation({
|
||||
mutationFn: print => client.post(`/api/orders/${order.id}/cancel-items`, { item_ids: picked, print_cancellation: print }),
|
||||
onSuccess: () => { setCancelling(false); done(t('orders.lines.cancelled', { count: picked.length })) }, onError,
|
||||
})
|
||||
const toTab = useMutation({
|
||||
mutationFn: async () => { for (const id of picked) await client.post(`/api/orders/${order.id}/items/${id}/tab`) },
|
||||
onSuccess: () => done(t('orders.lines.tabbed')), onError: err => { onError(err); onChanged() },
|
||||
})
|
||||
|
||||
return (
|
||||
<section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden" data-testid="order-lines">
|
||||
{lines.length === 0 ? <EmptyState compact title={t('orders.lines.none')} /> : (
|
||||
<ul className="divide-y divide-line">
|
||||
{lines.map(item => {
|
||||
const can = open && selectable(item)
|
||||
const on = picked.includes(item.id)
|
||||
const d = lineDetails(item)
|
||||
const evs = priceEvents.filter(ev => ev.order_item_id === item.id && EVENT_TONE[ev.event_type])
|
||||
const gone = item.status === 'cancelled'
|
||||
return (
|
||||
<li key={item.id} className={cx('px-4 py-2.5 flex gap-3 items-start', on && 'bg-accent-soft', gone && 'opacity-50')}
|
||||
data-testid="order-line" data-status={item.status} data-name={nameOf(item)}>
|
||||
<input type="checkbox" className="mt-1 size-4 accent-[var(--x-accent)]" disabled={!can} checked={on}
|
||||
aria-label={t('orders.lines.pick', { name: nameOf(item) })} onChange={() => setSelected(s => toggleSelected(s, item.id))} data-testid="line-pick" />
|
||||
<div className={cx('flex-1 min-w-0 grid gap-0.5', gone && 'line-through')}>
|
||||
<div className="flex flex-wrap items-center gap-1.5 text-body font-semibold text-ink">
|
||||
<span>{item.quantity !== 1 || item.unit_type !== 'piece' ? `${item.quantity}× ` : ''}{nameOf(item)}</span>
|
||||
{item.deal_id && <Pill tone="accent">{t('orders.lines.free')}</Pill>}
|
||||
{STATUS_TONE[item.status] && (
|
||||
<Pill tone={STATUS_TONE[item.status]}>
|
||||
{t(`orders.lines.status.${item.status}`)}{item.status === 'paid' && item.payment_method ? ` · ${t(`orders.pay.method.${item.payment_method}`, { defaultValue: item.payment_method })}` : ''}
|
||||
</Pill>
|
||||
)}
|
||||
{item.status === 'active' && !item.printed && <Pill tone="warning"><Printer size={12} aria-hidden="true" />{t('orders.lines.notPrinted')}</Pill>}
|
||||
</div>
|
||||
{d.choices.length > 0 && <div className="text-caption text-ink-2">{d.choices.join(', ')}</div>}
|
||||
{d.removed.length > 0 && <div className="text-caption text-ink-2">{t('orders.lines.without', { list: d.removed.join(', ') })}</div>}
|
||||
{d.note && <div className="text-caption text-warning-ink">{d.note}</div>}
|
||||
<div className="text-caption text-ink-3">
|
||||
{t('orders.lines.added', { time: formatTime(item.added_at), name: item.added_by_name ?? '' })}
|
||||
{item.paid_by_name && ` · ${t('orders.lines.paidBy', { name: item.paid_by_name })}`}
|
||||
</div>
|
||||
{evs.map((ev, i) => (
|
||||
<div key={i} className={cx('flex items-center gap-2 text-caption', EVENT_TONE[ev.event_type])}>
|
||||
<span aria-hidden="true">↳</span>
|
||||
<span>{ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}</span>
|
||||
{ev.delta_amount != null && <span className="font-semibold">{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}</span>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="text-right grid">
|
||||
<span className={cx('text-body font-semibold tabular-nums', item.price_adjustment ? 'text-info-ink' : 'text-ink')}>{formatMoney(lineAmount(item))}</span>
|
||||
{item.quantity !== 1 && <span className="text-caption text-ink-3 tabular-nums">{t('orders.lines.each', { price: formatMoney(unitOf(item)) })}</span>}
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{open && picked.length > 0 && (
|
||||
<div className="sticky bottom-0 flex flex-wrap items-center gap-2 px-4 py-3 border-t border-line bg-surface-2" data-testid="line-actions">
|
||||
<span className="flex-1 text-label text-ink-2">{t('orders.lines.picked', { count: picked.length, amount: formatMoney(amount) })}</span>
|
||||
<Button size="sm" variant="ghost" onClick={() => setSelected([])}>{t('orders.lines.clear')}</Button>
|
||||
{order.customer_id && <Button size="sm" variant="secondary" icon={<Receipt size={14} />} loading={toTab.isPending} onClick={() => toTab.mutate()}>{t('orders.lines.toTab')}</Button>}
|
||||
{canDiscount && <Button size="sm" variant="secondary" icon={<Percent size={14} />} onClick={() => setDiscounting(true)} data-testid="lines-discount">{t('orders.lines.discount')}</Button>}
|
||||
<Button size="sm" variant="danger" icon={<Ban size={14} />} onClick={() => setCancelling(true)} data-testid="lines-cancel">{t('orders.lines.cancel')}</Button>
|
||||
<Button size="sm" icon={<CreditCard size={14} />} onClick={() => onPay(picked, amount, () => setSelected([]))} data-testid="lines-pay">{t('orders.lines.pay')}</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{cancelling && (
|
||||
<Dialog open size="sm" onClose={() => setCancelling(false)} title={t('orders.lines.cancelTitle', { count: picked.length })}
|
||||
description={t('orders.lines.cancelBody')}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={() => setCancelling(false)}>{t('orders.back')}</Button>
|
||||
<Button variant="secondary" loading={cancel.isPending && cancel.variables === false} onClick={() => cancel.mutate(false)} data-testid="cancel-no-print">{t('orders.lines.cancelNoPrint')}</Button>
|
||||
<Button variant="danger" icon={<Printer size={16} />} loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}</Button>
|
||||
</>} />
|
||||
)}
|
||||
{discounting && <DiscountDialog orderId={order.id} itemIds={picked} amount={amount} onClose={() => setDiscounting(false)}
|
||||
onDone={() => { setDiscounting(false); done(t('orders.discount.done')) }} />}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function DiscountDialog({ orderId, itemIds, amount, onClose, onDone }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatMoney } = useFormat()
|
||||
const [pct, setPct] = useState('10')
|
||||
const [note, setNote] = useState('')
|
||||
const value = Number(String(pct).replace(',', '.'))
|
||||
const ok = value > 0 && value <= 100
|
||||
const apply = useMutation({
|
||||
mutationFn: () => client.post(`/api/orders/${orderId}/items/discount`, { item_ids: itemIds, discount_percent: value, note: note.trim() || null }),
|
||||
onSuccess: onDone, onError: err => toast.error(errorMessage(err, t)),
|
||||
})
|
||||
return (
|
||||
<Dialog open size="sm" onClose={onClose} title={t('orders.discount.title', { count: itemIds.length })} description={t('orders.discount.body')}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose}>{t('orders.back')}</Button>
|
||||
<Button disabled={!ok} loading={apply.isPending} onClick={() => apply.mutate()} data-testid="discount-apply">{t('orders.discount.apply')}</Button>
|
||||
</>}>
|
||||
<div className="grid gap-3">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{[5, 10, 15, 20, 50, 100].map(p => (
|
||||
<Button key={p} size="sm" variant={value === p ? 'primary' : 'secondary'} onClick={() => setPct(String(p))}>{p}%</Button>
|
||||
))}
|
||||
</div>
|
||||
<Field label={t('orders.discount.pct')} hint={ok ? t('orders.discount.about', { amount: formatMoney(-(amount * value) / 100) }) : undefined}>
|
||||
<Input inputMode="decimal" value={pct} onChange={e => setPct(e.target.value)} data-testid="discount-pct" />
|
||||
</Field>
|
||||
<Field label={t('orders.discount.note')}>
|
||||
<Input value={note} maxLength={200} onChange={e => setNote(e.target.value)} />
|
||||
</Field>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
// A table's order in the manager (plan step 6.9; replaces the v1 order page and its desktop
|
||||
// ordering tab). Taken, changed, paid and closed by the phones' rules: lines go by id and the
|
||||
// server prices them (4.4); paying asks cash or card; "Close" with unpaid lines either takes
|
||||
// the payment first or, when the venue allows it (orders.close_with_unpaid), writes them off
|
||||
// after saying so. `/orders/new?table=5` is a table without an order: the first "Send" opens it.
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import toast from 'react-hot-toast'
|
||||
import { ArrowLeft, Ban, CheckCheck, CreditCard, Printer } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Select, Spinner, cx } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||
import { useDuration } from '../overview/hooks'
|
||||
import { tableName } from '../overview/overviewLogic'
|
||||
import { Money, Pill } from '../overview/parts'
|
||||
import AddItems from './AddItems'
|
||||
import OrderLines from './OrderLines'
|
||||
import OrderPeople from './OrderPeople'
|
||||
import PayDialog from './PayDialog'
|
||||
import { AuditList, PriceEventList } from './OrderHistory'
|
||||
import { closeStep, totals, unpaidIds, venueRules } from './orderLogic'
|
||||
|
||||
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded', 'kds_order_updated', 'kds_item_updated']
|
||||
const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
|
||||
const TABS = ['order', 'prices', 'history']
|
||||
|
||||
export default function OrderPage() {
|
||||
const { orderId } = useParams()
|
||||
const [params] = useSearchParams()
|
||||
if (orderId === 'new') return <NewOrder tableId={Number(params.get('table')) || null} />
|
||||
return <OrderView orderId={Number(orderId)} />
|
||||
}
|
||||
|
||||
function useVenue() {
|
||||
const { data } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
|
||||
return venueRules(data)
|
||||
}
|
||||
|
||||
function Back() {
|
||||
const { t } = useTranslation('manager')
|
||||
const navigate = useNavigate()
|
||||
return <Button size="sm" variant="ghost" icon={<ArrowLeft size={16} />} onClick={() => navigate('/tables')}>{t('orders.toTables')}</Button>
|
||||
}
|
||||
|
||||
function NewOrder({ tableId }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const navigate = useNavigate()
|
||||
const qc = useQueryClient()
|
||||
const { data: tables = [] } = useLiveQuery({ queryKey: ['tables'], queryFn: () => client.get('/api/tables/').then(r => r.data), events: ['table_list_changed'] })
|
||||
const table = tables.find(x => x.id === tableId)
|
||||
const open = async () => (await client.post('/api/orders/', { table_id: tableId, order_type: 'here' })).data.id
|
||||
return (
|
||||
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="order-new">
|
||||
<div className="max-w-6xl mx-auto grid gap-4">
|
||||
<header className="flex flex-wrap items-center gap-3">
|
||||
<Back />
|
||||
<h1 className="text-title font-semibold text-ink">{t('orders.newTitle', { table: table ? tableName(table) : tableId ?? '' })}</h1>
|
||||
<Pill tone="neutral">{t('overview.tableState.free')}</Pill>
|
||||
</header>
|
||||
<p className="text-label text-ink-2">{t('orders.newHint')}</p>
|
||||
<AddItems orderId={null} openOrder={open} onSent={id => {
|
||||
qc.invalidateQueries({ queryKey: ['orders-active'] })
|
||||
navigate(`/orders/${id}`, { replace: true })
|
||||
}} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function OrderView({ orderId }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatTime, formatMoney } = useFormat()
|
||||
const since = useDuration()
|
||||
const navigate = useNavigate()
|
||||
const qc = useQueryClient()
|
||||
const venue = useVenue()
|
||||
const [tab, setTab] = useState('order')
|
||||
const [paying, setPaying] = useState(null) // { ids, amount, thenClose, after }
|
||||
const [confirm, setConfirm] = useState(null) // 'close' | 'writeOff' | 'cancel'
|
||||
const [printerId, setPrinterId] = useState('')
|
||||
|
||||
const { data: order, isPending, error } = useLiveQuery({
|
||||
queryKey: ['order', orderId], queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data), events: ORDER_EVENTS,
|
||||
})
|
||||
const { data: staff = [] } = useLiveQuery({ queryKey: ['waiters'], queryFn: () => client.get('/api/waiters/').then(r => r.data), staleTime: 60_000 })
|
||||
const { data: printers = [] } = useLiveQuery({ queryKey: ['printers'], queryFn: () => client.get('/api/system/printers').then(r => r.data), staleTime: 60_000 })
|
||||
const { data: priceEvents = [] } = useLiveQuery({
|
||||
queryKey: ['price-events', orderId], queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data), events: ['order_updated'],
|
||||
})
|
||||
|
||||
const refresh = () => {
|
||||
qc.invalidateQueries({ queryKey: ['order', orderId] })
|
||||
qc.invalidateQueries({ queryKey: ['price-events', orderId] })
|
||||
qc.invalidateQueries({ queryKey: ['orders-active'] })
|
||||
}
|
||||
const onError = err => toast.error(errorMessage(err, t))
|
||||
const close = useMutation({ mutationFn: () => client.post(`/api/orders/${orderId}/close`), onSuccess: () => { setConfirm(null); toast.success(t('orders.closed')); refresh() }, onError })
|
||||
const cancel = useMutation({
|
||||
mutationFn: print => client.delete(`/api/orders/${orderId}`, { params: { print_cancellation: print } }),
|
||||
onSuccess: () => { setConfirm(null); toast.success(t('orders.cancelled')); refresh(); navigate('/tables') }, onError,
|
||||
})
|
||||
const print = useMutation({ mutationFn: pid => client.post(`/api/orders/${orderId}/print`, { printer_id: pid }), onSuccess: () => toast.success(t('orders.printing')), onError })
|
||||
|
||||
if (isPending) return <div className="h-full grid place-items-center"><Spinner /></div>
|
||||
if (error || !order) {
|
||||
return <div className="p-6 grid gap-3 justify-items-center"><EmptyState title={t('orders.notFound')} description={error ? errorMessage(error, t) : undefined} /><Back /></div>
|
||||
}
|
||||
|
||||
const editable = ['open', 'partially_paid', 'paid'].includes(order.status)
|
||||
const sums = totals(order)
|
||||
const due = unpaidIds(order)
|
||||
|
||||
function startClose() {
|
||||
const step = closeStep(order, venue.closeWithUnpaid)
|
||||
if (step === 'payFirst') setPaying({ ids: due, amount: sums.due, thenClose: true })
|
||||
else setConfirm(step)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="order-page" data-status={order.status}>
|
||||
<div className="max-w-6xl mx-auto grid gap-4">
|
||||
<header className="flex flex-wrap items-center gap-3">
|
||||
<Back />
|
||||
<h1 className="text-title font-semibold text-ink">{order.table_name ? t('orders.title', { table: order.table_name }) : t('orders.titleNoTable', { id: order.id })}</h1>
|
||||
<Pill tone={STATUS_TONE[order.status] ?? 'neutral'} data-testid="order-status">{t(`overview.orderStatus.${order.status}`, { defaultValue: order.status })}</Pill>
|
||||
<span className="text-label text-ink-2">{t('overview.order.sub', { id: order.id, time: formatTime(order.opened_at), since: since(order.opened_at, order.closed_at ? new Date(order.closed_at).getTime() : undefined) })}</span>
|
||||
<span className="flex-1" />
|
||||
<span className="flex items-baseline gap-4 text-label text-ink-2">
|
||||
{sums.paid > 0 && <span>{t('orders.paid')} <Money value={sums.paid} className="font-semibold text-success-ink" /></span>}
|
||||
{sums.paid > 0 && sums.due > 0 && <span>{t('orders.due')} <Money value={sums.due} className="font-semibold text-ink" data-testid="order-due" /></span>}
|
||||
<span>{t('orders.total')} <Money value={sums.total} className="text-title font-semibold text-ink" data-testid="order-total" /></span>
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="flex gap-1" role="tablist">
|
||||
{TABS.map(k => <Button key={k} size="sm" variant={tab === k ? 'primary' : 'ghost'} role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`order-tab-${k}`}>{t(`orders.tabs.${k}`)}</Button>)}
|
||||
</span>
|
||||
<span className="flex-1" />
|
||||
{editable && due.length > 0 && <Button icon={<CreditCard size={16} />} onClick={() => setPaying({ ids: due, amount: sums.due })} data-testid="order-pay-all">{t('orders.payAll')}</Button>}
|
||||
{editable && <Button variant="secondary" icon={<CheckCheck size={16} />} onClick={startClose} data-testid="order-close">{t('orders.close')}</Button>}
|
||||
{editable && <Button variant="danger" icon={<Ban size={16} />} onClick={() => setConfirm('cancel')} data-testid="order-cancel">{t('orders.cancel')}</Button>}
|
||||
{printers.length > 0 && (
|
||||
<span className="flex items-center gap-2">
|
||||
<Select size="sm" value={printerId} onChange={e => setPrinterId(e.target.value)} aria-label={t('orders.printer')}
|
||||
placeholder={t('orders.printer')} options={printers.map(p => ({ value: String(p.id), label: p.name }))} />
|
||||
<Button size="sm" variant="secondary" icon={<Printer size={16} />} disabled={!printerId} loading={print.isPending} onClick={() => print.mutate(Number(printerId))}>{t('orders.print')}</Button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{tab === 'order' && (
|
||||
<div className={cx('grid gap-4 items-start', editable && 'lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]')}>
|
||||
<div className="grid gap-4 min-w-0">
|
||||
<OrderLines order={order} open={editable} priceEvents={priceEvents} onChanged={refresh}
|
||||
onPay={(ids, amount, after) => setPaying({ ids, amount, after })} />
|
||||
<OrderPeople order={order} open={editable} staff={staff} onChanged={refresh} />
|
||||
</div>
|
||||
{editable && <AddItems orderId={order.id} onSent={refresh} />}
|
||||
</div>
|
||||
)}
|
||||
{tab === 'prices' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><PriceEventList events={priceEvents} /></section>}
|
||||
{tab === 'history' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><AuditList order={order} /></section>}
|
||||
</div>
|
||||
|
||||
{paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose}
|
||||
onClose={() => setPaying(null)}
|
||||
onDone={() => { toast.success(paying.thenClose ? t('orders.closed') : t('orders.pay.done')); paying.after?.(); setPaying(null); refresh() }} />}
|
||||
|
||||
{(confirm === 'close' || confirm === 'writeOff') && (
|
||||
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t(confirm === 'close' ? 'orders.confirmClose' : 'orders.writeOffTitle')}
|
||||
description={confirm === 'writeOff' ? t('orders.writeOffBody', { count: due.length, amount: formatMoney(sums.due) }) : undefined}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('orders.back')}</Button>
|
||||
{confirm === 'writeOff' && <Button variant="secondary" onClick={() => { setConfirm(null); setPaying({ ids: due, amount: sums.due, thenClose: true }) }}>{t('orders.payAndClose')}</Button>}
|
||||
<Button variant={confirm === 'writeOff' ? 'danger' : 'primary'} loading={close.isPending} onClick={() => close.mutate()} data-testid="order-close-confirm">
|
||||
{confirm === 'writeOff' ? t('orders.writeOff') : t('orders.close')}
|
||||
</Button>
|
||||
</>} />
|
||||
)}
|
||||
{confirm === 'cancel' && (
|
||||
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t('orders.cancelTitle')} description={t('orders.cancelBody')}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('orders.back')}</Button>
|
||||
<Button variant="secondary" loading={cancel.isPending && cancel.variables === false} onClick={() => cancel.mutate(false)} data-testid="order-cancel-confirm">{t('orders.lines.cancelNoPrint')}</Button>
|
||||
<Button variant="danger" icon={<Printer size={16} />} loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}</Button>
|
||||
</>} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Who is on a table's order (plan step 6.9): its waiters (add or take one off) and its customer
|
||||
// (search and attach one, or take them off; with the customers app on).
|
||||
import { useState } from 'react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import toast from 'react-hot-toast'
|
||||
import { UserRound, X } from 'lucide-react'
|
||||
import { useModule } from '@xenia/access'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, IconButton, Input, Select } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||
import { Pill } from '../overview/parts'
|
||||
import { addableWaiters, personName } from './orderLogic'
|
||||
|
||||
export default function OrderPeople({ order, open, staff, onChanged }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const crm = useModule('crm')
|
||||
const onError = err => toast.error(errorMessage(err, t))
|
||||
const add = useMutation({ mutationFn: id => client.put(`/api/orders/${order.id}/assign-waiter`, { waiter_id: id }), onSuccess: onChanged, onError })
|
||||
const remove = useMutation({ mutationFn: id => client.delete(`/api/orders/${order.id}/waiters/${id}`), onSuccess: onChanged, onError })
|
||||
const name = id => personName(staff.find(s => s.id === id)) || `#${id}`
|
||||
const addable = addableWaiters(staff, order)
|
||||
|
||||
return (
|
||||
<section className="rounded-card border border-line bg-surface shadow-raised p-4 grid gap-3" data-testid="order-people">
|
||||
<div className="grid gap-2">
|
||||
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.people.staff')}</h3>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{order.waiters.length === 0 && <span className="text-label text-ink-3">{t('orders.people.noStaff')}</span>}
|
||||
{order.waiters.map(w => (
|
||||
<Pill key={w.waiter_id} tone="accent" data-testid="order-waiter">
|
||||
{name(w.waiter_id)}
|
||||
{open && (
|
||||
<button type="button" className="ml-0.5 rounded-full hover:bg-surface-3" aria-label={t('orders.people.remove', { name: name(w.waiter_id) })}
|
||||
onClick={() => remove.mutate(w.waiter_id)}><X size={12} /></button>
|
||||
)}
|
||||
</Pill>
|
||||
))}
|
||||
{open && addable.length > 0 && (
|
||||
<Select size="sm" value="" placeholder={t('orders.people.add')} aria-label={t('orders.people.add')} data-testid="order-waiter-add"
|
||||
onChange={e => e.target.value && add.mutate(Number(e.target.value))}
|
||||
options={addable.map(s => ({ value: String(s.id), label: personName(s) }))} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{crm && <Customer order={order} open={open} onChanged={onChanged} />}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function Customer({ order, open, onChanged }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [searching, setSearching] = useState(false)
|
||||
const [q, setQ] = useState('')
|
||||
const { data: found = [] } = useLiveQuery({
|
||||
queryKey: ['customers', q], enabled: searching, staleTime: 30_000,
|
||||
queryFn: () => client.get('/api/customers/', { params: q ? { search: q } : {} }).then(r => r.data),
|
||||
})
|
||||
const set = useMutation({
|
||||
mutationFn: id => client.put(`/api/orders/${order.id}/customer`, { customer_id: id }),
|
||||
onSuccess: () => { setSearching(false); setQ(''); onChanged() },
|
||||
onError: err => toast.error(errorMessage(err, t)),
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="grid gap-2 border-t border-line pt-3">
|
||||
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.people.customer')}</h3>
|
||||
{order.customer_id ? (
|
||||
<div className="flex items-center gap-2 p-2 rounded-control bg-info-soft text-info-ink">
|
||||
<UserRound size={16} aria-hidden="true" />
|
||||
<span className="flex-1 min-w-0 grid">
|
||||
<span className="text-label font-semibold truncate">{order.customer_name || `#${order.customer_id}`}</span>
|
||||
{order.customer_phone && <span className="text-caption">{order.customer_phone}</span>}
|
||||
</span>
|
||||
{open && <IconButton size="sm" variant="ghost" label={t('orders.people.customerRemove')} onClick={() => set.mutate(null)}><X size={14} /></IconButton>}
|
||||
</div>
|
||||
) : !open ? <span className="text-label text-ink-3">{t('orders.people.noCustomer')}</span>
|
||||
: !searching ? <Button size="sm" variant="secondary" onClick={() => setSearching(true)}>{t('orders.people.customerAdd')}</Button>
|
||||
: (
|
||||
<div className="grid gap-1">
|
||||
<Input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder={t('orders.people.customerSearch')} aria-label={t('orders.people.customerSearch')} />
|
||||
<ul className="max-h-52 overflow-y-auto rounded-control border border-line divide-y divide-line">
|
||||
{found.length === 0 && <li className="px-3 py-2 text-label text-ink-3">{t('orders.people.customerNone')}</li>}
|
||||
{found.map(c => (
|
||||
<li key={c.id}>
|
||||
<button type="button" className="w-full text-left px-3 py-2 hover:bg-surface-2 text-label" onClick={() => set.mutate(c.id)}>
|
||||
<span className="font-semibold text-ink">{c.name}</span>
|
||||
{c.phone && <span className="ml-2 text-ink-3">{c.phone}</span>}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<Button size="sm" variant="ghost" onClick={() => { setSearching(false); setQ('') }}>{t('orders.back')}</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Paying lines of a table's order from the manager (plan step 6.9), as the phones do: how much,
|
||||
// then cash or card (card only when the venue takes cards). `thenClose` is the phones'
|
||||
// "instant-pay close": the rest is paid and the order closed in one go, for venues that don't
|
||||
// close with unpaid items (orders.close_with_unpaid, 4.8).
|
||||
import { useState } from 'react'
|
||||
import { Banknote, CreditCard } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
|
||||
export default function PayDialog({ orderId, itemIds, amount, card = true, thenClose = false, onClose, onDone }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatMoney } = useFormat()
|
||||
const [busy, setBusy] = useState(null)
|
||||
const [error, setError] = useState(null)
|
||||
|
||||
async function pay(method) {
|
||||
setBusy(method)
|
||||
setError(null)
|
||||
try {
|
||||
await client.post(`/api/orders/${orderId}/pay`, { item_ids: itemIds, payment_method: method })
|
||||
if (thenClose) await client.post(`/api/orders/${orderId}/close`)
|
||||
onDone(method)
|
||||
} catch (err) {
|
||||
setError(errorMessage(err, t))
|
||||
} finally { setBusy(null) }
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open size="sm" onClose={busy ? undefined : onClose}
|
||||
title={thenClose ? t('orders.pay.closeTitle') : t('orders.pay.title', { count: itemIds.length })}
|
||||
description={thenClose ? t('orders.pay.closeBody') : undefined}
|
||||
footer={<Button variant="secondary" onClick={onClose} disabled={!!busy}>{t('orders.back')}</Button>}>
|
||||
<div className="grid gap-3" data-testid="pay-dialog">
|
||||
<div className="text-center text-display font-semibold tabular-nums text-ink" data-testid="pay-amount">{formatMoney(amount)}</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Button size="lg" icon={<Banknote size={20} />} loading={busy === 'cash'} disabled={!!busy} onClick={() => pay('cash')} data-testid="pay-cash">
|
||||
{t('orders.pay.cash')}
|
||||
</Button>
|
||||
<Button size="lg" variant="secondary" icon={<CreditCard size={20} />} loading={busy === 'card'} disabled={!!busy || !card}
|
||||
onClick={() => pay('card')} data-testid="pay-card" title={card ? undefined : t('orders.pay.noCard')}>
|
||||
{t('orders.pay.card')}
|
||||
</Button>
|
||||
</div>
|
||||
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// A table's quick actions from the Tables page (plan step 6.9): its flags (VIP, birthday…), and
|
||||
// a message to the table's waiters or to everyone, from a ready-made text or typed.
|
||||
import { useState } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import toast from 'react-hot-toast'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, Field, Input, Switch, cx } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||
import { tableName } from '../overview/overviewLogic'
|
||||
|
||||
export default function QuickActions({ card, flagDefs, current, onClose }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const qc = useQueryClient()
|
||||
const { table, order } = card
|
||||
const [ids, setIds] = useState(() => current.map(f => f.id))
|
||||
const [notify, setNotify] = useState(false)
|
||||
const [toAll, setToAll] = useState(!order?.waiters?.length)
|
||||
const [message, setMessage] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const { data: templates = [] } = useLiveQuery({ queryKey: ['quick-templates'], queryFn: () => client.get('/api/notifications/templates').then(r => r.data), staleTime: 60_000 })
|
||||
const toggle = id => setIds(list => (list.includes(id) ? list.filter(x => x !== id) : [...list, id]))
|
||||
|
||||
async function save() {
|
||||
setBusy(true)
|
||||
try {
|
||||
await client.put(`/api/flags/table/${table.id}`, { flag_ids: ids })
|
||||
if (notify && message.trim()) {
|
||||
await client.post('/api/notifications/send', {
|
||||
body: message.trim(), table_ids: [table.id],
|
||||
target_waiter_ids: toAll ? [] : (order?.waiters ?? []).map(w => w.waiter_id),
|
||||
})
|
||||
toast.success(t('orders.quick.sent'))
|
||||
} else toast.success(t('orders.quick.saved'))
|
||||
qc.invalidateQueries({ queryKey: ['flag-assignments'] })
|
||||
onClose()
|
||||
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open size="sm" onClose={onClose} title={t('orders.quick.title', { table: tableName(table) })}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose}>{t('orders.back')}</Button>
|
||||
<Button loading={busy} disabled={notify && !message.trim()} onClick={save} data-testid="quick-save">{t('orders.quick.save')}</Button>
|
||||
</>}>
|
||||
<div className="grid gap-4" data-testid="quick-actions">
|
||||
<Field label={t('orders.quick.flags')}>
|
||||
{flagDefs.length === 0 ? <span className="text-label text-ink-3">{t('orders.quick.noFlags')}</span> : (
|
||||
<span className="flex flex-wrap gap-1.5">
|
||||
{flagDefs.map(f => (
|
||||
<button key={f.id} type="button" aria-pressed={ids.includes(f.id)} onClick={() => toggle(f.id)} data-testid="quick-flag"
|
||||
className={cx('inline-flex items-center gap-1 px-3 py-1 rounded-full border text-label',
|
||||
ids.includes(f.id) ? 'border-accent bg-accent-soft text-accent-ink font-semibold' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
|
||||
{f.emoji && <span aria-hidden="true">{f.emoji}</span>}{f.name}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
</Field>
|
||||
<label className="flex items-center gap-3 text-body text-ink">
|
||||
<Switch checked={notify} onChange={setNotify} aria-label={t('orders.quick.notify')} />
|
||||
{t('orders.quick.notify')}
|
||||
</label>
|
||||
{notify && (
|
||||
<div className="grid gap-2">
|
||||
{templates.length > 0 && (
|
||||
<span className="flex flex-wrap gap-1.5">
|
||||
{templates.slice(0, 6).map(tp => (
|
||||
<Button key={tp.id} size="sm" variant={message === tp.body ? 'primary' : 'secondary'} onClick={() => setMessage(tp.body)}>{tp.body}</Button>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
<Input value={message} maxLength={300} onChange={e => setMessage(e.target.value)} placeholder={t('orders.quick.message')} aria-label={t('orders.quick.message')} />
|
||||
{order?.waiters?.length > 0 && (
|
||||
<label className="flex items-center gap-3 text-label text-ink-2">
|
||||
<Switch checked={toAll} onChange={setToAll} aria-label={t('orders.quick.toAll')} />
|
||||
{toAll ? t('orders.quick.toAll') : t('orders.quick.toTable')}
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// The tables now, in the manager (plan step 6.9; the map since 6.8): each table's state, total,
|
||||
// time open, waiters, flags and a booking kept for it soon (RESERVED). A table with an order
|
||||
// opens its order page; a free one opens a new order there. Quick actions set the table's flags
|
||||
// and can tell its waiters (or everyone) a message. Lines that didn't print are listed below.
|
||||
// Everything stays current through the live events.
|
||||
import { useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Clock, Lock, Printer, Zap } from 'lucide-react'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, EmptyState, IconButton, Select, Spinner, cx } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||
import LiveFloor from '../floor/LiveFloor'
|
||||
import { useDuration } from '../overview/hooks'
|
||||
import { TABLE_STATES, durationParts, orderTotal, tableCards, tableName } from '../overview/overviewLogic'
|
||||
import { Money, Pill } from '../overview/parts'
|
||||
import PendingPrints from '../overview/PendingPrints'
|
||||
import { BORDER, SOFT, SOLID } from '../overview/tones'
|
||||
import QuickActions from './QuickActions'
|
||||
import { NO_ZONE, cardTarget, filterCards, flagsByTable, personName } from './orderLogic'
|
||||
|
||||
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded']
|
||||
const STATE_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', free: 'neutral' }
|
||||
|
||||
export default function TablesPage() {
|
||||
const { t } = useTranslation('manager')
|
||||
const tc = useTranslation('common').t
|
||||
const navigate = useNavigate()
|
||||
const [view, setView] = useState('list')
|
||||
const [states, setStates] = useState([])
|
||||
const [zone, setZone] = useState('')
|
||||
const [quick, setQuick] = useState(null) // a card
|
||||
|
||||
const { data: tables = [], isPending: loadingTables } = useLiveQuery({
|
||||
queryKey: ['tables'], queryFn: () => client.get('/api/tables/').then(r => r.data),
|
||||
events: ['table_list_changed', 'reservation_updated'], refetchInterval: 60_000,
|
||||
})
|
||||
const { data: orders = [], isPending: loadingOrders } = useLiveQuery({
|
||||
queryKey: ['orders-active'], queryFn: () => client.get('/api/orders/').then(r => r.data), events: ORDER_EVENTS, refetchInterval: 60_000,
|
||||
})
|
||||
const { data: groups = [] } = useLiveQuery({ queryKey: ['table-groups'], queryFn: () => client.get('/api/tables/groups').then(r => r.data), events: ['table_list_changed'] })
|
||||
const { data: flagDefs = [] } = useLiveQuery({ queryKey: ['flag-defs'], queryFn: () => client.get('/api/flags/defs').then(r => r.data), staleTime: 60_000 })
|
||||
const { data: flagRows = [] } = useLiveQuery({ queryKey: ['flag-assignments'], queryFn: () => client.get('/api/flags/assignments').then(r => r.data), events: ['table_flags_changed'] })
|
||||
const { data: staff = [] } = useLiveQuery({ queryKey: ['waiters'], queryFn: () => client.get('/api/waiters/').then(r => r.data), staleTime: 60_000 })
|
||||
|
||||
const cards = tableCards(tables, orders)
|
||||
const shown = filterCards(cards, { states, zone })
|
||||
const flags = flagsByTable(flagDefs, flagRows)
|
||||
const name = id => personName(staff.find(s => s.id === id)) || `#${id}`
|
||||
const toggleState = s => setStates(list => (list.includes(s) ? list.filter(x => x !== s) : [...list, s]))
|
||||
|
||||
if (loadingTables || loadingOrders) return <div className="h-full grid place-items-center"><Spinner /></div>
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-y-auto p-4 lg:p-6 grid gap-4 content-start" data-testid="tables-page">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="flex rounded-control border border-line overflow-hidden" role="group">
|
||||
{['list', 'map'].map(v => (
|
||||
<button key={v} type="button" aria-pressed={view === v} onClick={() => setView(v)} data-testid={`tables-view-${v}`}
|
||||
className={cx('px-3 py-1.5 text-label font-medium', view === v ? 'bg-accent-soft text-accent-ink' : 'bg-surface text-ink-2 hover:bg-surface-2')}>
|
||||
{tc(`floorMap.${v}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span className="flex-1" />
|
||||
{view === 'list' && TABLE_STATES.map(s => (
|
||||
<button key={s} type="button" aria-pressed={states.includes(s)} onClick={() => toggleState(s)} data-testid={`tables-state-${s}`}
|
||||
className={cx('inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border text-label font-semibold',
|
||||
states.includes(s) ? `${SOFT[STATE_TONE[s]]} ${BORDER[STATE_TONE[s]]}` : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
|
||||
<span className={cx('w-2 h-2 rounded-full', SOLID[STATE_TONE[s]])} aria-hidden="true" />
|
||||
{t(`overview.tableState.${s}`)}
|
||||
<span className="tabular-nums text-ink">{cards.filter(c => c.state === s).length}</span>
|
||||
</button>
|
||||
))}
|
||||
<Select size="sm" value={zone} onChange={e => setZone(e.target.value)} aria-label={t('orders.tables.zone')} data-testid="tables-zone">
|
||||
<option value="">{t('orders.tables.allZones')}</option>
|
||||
{groups.map(g => <option key={g.id} value={String(g.id)}>{g.name}</option>)}
|
||||
<option value={NO_ZONE}>{t('orders.tables.noZone')}</option>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{view === 'map' && (
|
||||
<LiveFloor zone={zone && zone !== NO_ZONE ? Number(zone) : null} onOpen={id => navigate(`/orders/${id}`)} />
|
||||
)}
|
||||
|
||||
{view === 'list' && (shown.length === 0
|
||||
? <EmptyState title={t('orders.tables.none')} />
|
||||
: (
|
||||
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(17rem,1fr))]">
|
||||
{shown.map(card => (
|
||||
<TableCard key={card.table.id} card={card} zone={groups.length > 1 ? groups.find(g => g.id === card.table.group_id)?.name : null} flags={flags[card.table.id] ?? []} waiterName={name}
|
||||
onOpen={() => navigate(cardTarget(card))} onQuick={() => setQuick(card)} />
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
|
||||
<PendingPrints cards={cards.filter(c => c.pendingPrint)} onOpen={id => navigate(`/orders/${id}`)} />
|
||||
|
||||
{quick && <QuickActions card={quick} flagDefs={flagDefs} current={flags[quick.table.id] ?? []} onClose={() => setQuick(null)} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TableCard({ card, zone, flags, waiterName, onOpen, onQuick }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatTime } = useFormat()
|
||||
const since = useDuration()
|
||||
const { table, order, state, pendingPrint } = card
|
||||
const tone = STATE_TONE[state]
|
||||
const booking = table.upcoming_reservation
|
||||
const open = order ? durationParts(order.opened_at) : null
|
||||
const long = !!open && open.h * 60 + open.m >= 90 // the v1 card's "been here a while"
|
||||
return (
|
||||
<div className={cx('relative rounded-card border bg-surface shadow-raised overflow-hidden grid', BORDER[tone])} data-testid="table-card" data-state={state} data-table={table.id}>
|
||||
<span className={cx('absolute inset-y-0 left-0 w-1.5', SOLID[tone])} aria-hidden="true" />
|
||||
<button type="button" onClick={onOpen} className="text-left pl-5 pr-4 pt-3 pb-2 grid gap-2 hover:bg-surface-2 transition-colors duration-fast"
|
||||
aria-label={t('orders.tables.open', { table: tableName(table), state: t(`overview.tableState.${state}`) })}>
|
||||
<span className="flex items-start gap-2">
|
||||
<span className="flex-1 grid gap-1">
|
||||
<span className="text-display font-bold leading-none text-ink tabular-nums">{tableName(table)}</span>
|
||||
{zone && <span className="text-caption text-ink-3">{zone}</span>}
|
||||
</span>
|
||||
<span className={cx('px-2 py-0.5 rounded-full text-caption font-semibold', SOFT[tone])}>{t(`overview.tableState.${state}`)}</span>
|
||||
</span>
|
||||
<span className="flex flex-wrap gap-1 min-h-6">
|
||||
{pendingPrint && <Pill tone="warning"><Printer size={12} aria-hidden="true" />{t('orders.tables.notPrinted')}</Pill>}
|
||||
{booking && (
|
||||
<Pill tone="accent" data-testid="table-reserved" title={`${booking.guest_name} · ${booking.party_size}`}>
|
||||
<Lock size={12} aria-hidden="true" />{t('orders.tables.reserved', { time: formatTime(booking.reserved_for), name: booking.guest_name })}
|
||||
</Pill>
|
||||
)}
|
||||
{flags.slice(0, 3).map(f => (
|
||||
<Pill key={f.id} tone="neutral">{f.emoji && <span aria-hidden="true">{f.emoji}</span>}{f.name}</Pill>
|
||||
))}
|
||||
{flags.length > 3 && <Pill tone="neutral" title={flags.slice(3).map(f => f.name).join(', ')}>+{flags.length - 3}</Pill>}
|
||||
</span>
|
||||
<span className="grid grid-cols-2 gap-2">
|
||||
<span className="grid">
|
||||
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.total')}</span>
|
||||
{order ? <Money value={orderTotal(order.items)} className="text-title font-semibold text-ink" /> : <span className="text-title text-ink-3">—</span>}
|
||||
</span>
|
||||
<span className="grid">
|
||||
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.tables.time')}</span>
|
||||
<span className={cx('text-title tabular-nums inline-flex items-center gap-1', long ? 'font-bold text-warning-ink' : 'text-ink')}>
|
||||
{order ? <><Clock size={14} aria-hidden="true" />{since(order.opened_at)}</> : <span className="text-ink-3">—</span>}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
<div className="flex items-center gap-2 pl-5 pr-2 py-2 border-t border-line">
|
||||
<span className="flex-1 min-w-0 truncate text-label text-ink-2">
|
||||
{!order ? (table.seat_count ? t('orders.tables.seats', { count: table.seat_count }) : '')
|
||||
: order.waiters.length ? order.waiters.map(w => waiterName(w.waiter_id)).join(', ') : t('orders.tables.noWaiter')}
|
||||
</span>
|
||||
<IconButton size="sm" variant="ghost" label={t('orders.quick.title', { table: tableName(table) })} onClick={onQuick} data-testid="table-quick"><Zap size={16} /></IconButton>
|
||||
<Button size="sm" variant={order ? 'secondary' : 'primary'} onClick={onOpen} data-testid="table-open">{order ? t('orders.tables.view') : t('orders.tables.take')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// A table's order in the manager, as plain data (plan step 6.9), tested in tests/orders.test.mjs.
|
||||
// The rules are the phones': prices come from the server (lines by id, 4.4); closing with unpaid
|
||||
// items needs the venue's "close with unpaid items" (orders.close_with_unpaid, 4.8), otherwise
|
||||
// the rest is paid first.
|
||||
|
||||
export const OPEN_STATUSES = ['open', 'partially_paid', 'paid']
|
||||
export const isOpen = order => !!order && OPEN_STATUSES.includes(order.status)
|
||||
|
||||
const parse = raw => { try { return raw ? JSON.parse(raw) : [] } catch { return [] } }
|
||||
|
||||
/** What a line has: its choices ("Well done, Fries"), what's left out, the note. */
|
||||
export function lineDetails(item) {
|
||||
const opts = parse(item.selected_options).map(o => (typeof o === 'string' ? o : o?.name)).filter(Boolean)
|
||||
const removed = parse(item.removed_ingredients).map(o => (typeof o === 'string' ? o : o?.name)).filter(Boolean)
|
||||
return { choices: opts, removed, note: item.notes || null }
|
||||
}
|
||||
|
||||
export const unitOf = item => (item.unit_price ?? 0) + (item.price_adjustment ?? 0)
|
||||
export const lineAmount = item => Math.round(unitOf(item) * item.quantity * 100) / 100
|
||||
export const nameOf = item => item.product_name || item.product?.name || `#${item.product_id}`
|
||||
|
||||
const LIVE = ['active', 'ready', 'paid', 'closed']
|
||||
const UNPAID = ['active', 'ready']
|
||||
|
||||
/** The order's sums: everything still on it, what's paid, what's due. */
|
||||
export function totals(order) {
|
||||
const items = order?.items ?? []
|
||||
const sum = list => Math.round(list.reduce((s, i) => s + lineAmount(i), 0) * 100) / 100
|
||||
const total = sum(items.filter(i => LIVE.includes(i.status)))
|
||||
const paid = sum(items.filter(i => i.status === 'paid'))
|
||||
const due = sum(items.filter(i => UNPAID.includes(i.status)))
|
||||
return { total, paid, due }
|
||||
}
|
||||
|
||||
export const unpaidIds = order => (order?.items ?? []).filter(i => UNPAID.includes(i.status)).map(i => i.id)
|
||||
|
||||
/** Lines in the order they were added; cancelled ones last. */
|
||||
export function shownLines(order, { showCancelled = true } = {}) {
|
||||
const items = [...(order?.items ?? [])].sort((a, b) => (a.added_at ?? '').localeCompare(b.added_at ?? '') || a.id - b.id)
|
||||
const live = items.filter(i => i.status !== 'cancelled')
|
||||
return showCancelled ? [...live, ...items.filter(i => i.status === 'cancelled')] : live
|
||||
}
|
||||
|
||||
/** Selection: only unpaid lines can be paid or cancelled. */
|
||||
export function selectable(item) { return UNPAID.includes(item.status) }
|
||||
export function toggleSelected(sel, id) { return sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id] }
|
||||
export const selectedAmount = (order, sel) => Math.round((order?.items ?? []).filter(i => sel.includes(i.id)).reduce((s, i) => s + lineAmount(i), 0) * 100) / 100
|
||||
|
||||
/**
|
||||
* What "Close" does: 'close' (nothing unpaid), 'writeOff' (unpaid lines and the venue allows
|
||||
* closing with them: say so first), or 'payFirst' (the venue doesn't: offer to pay the rest).
|
||||
*/
|
||||
export function closeStep(order, closeWithUnpaid) {
|
||||
const due = unpaidIds(order).length
|
||||
if (!due) return 'close'
|
||||
return closeWithUnpaid ? 'writeOff' : 'payFirst'
|
||||
}
|
||||
|
||||
/** The venue's settings rows (GET /api/settings/) → the two that matter here. */
|
||||
export function venueRules(settings) {
|
||||
const v = key => settings?.[key]?.value
|
||||
return { closeWithUnpaid: v('orders.close_with_unpaid') === 'true', card: v('payments.card_enabled') !== 'false' }
|
||||
}
|
||||
|
||||
/** The cart's lines as the server takes them, plus the order's note (POST /api/orders/{id}/items). */
|
||||
export function sendBody(cart, note) {
|
||||
return { lines: cart.map(c => c.line), order_note: note?.trim() || null }
|
||||
}
|
||||
|
||||
/** Waiters to add: the active staff not already on the order. */
|
||||
export function addableWaiters(staff = [], order) {
|
||||
const on = new Set((order?.waiters ?? []).map(w => w.waiter_id))
|
||||
return staff.filter(s => s.is_active !== false && !on.has(s.id))
|
||||
}
|
||||
|
||||
export const personName = p => (p ? p.nickname || p.full_name || p.username : '')
|
||||
|
||||
// ── the Tables page ─────────────────────────────────────────────────────────
|
||||
|
||||
export const NO_ZONE = 'none'
|
||||
|
||||
/** Cards (overviewLogic.tableCards) shown for the chosen states (none = all) and zone
|
||||
* ('' = all, NO_ZONE = tables without a zone, else a zone id as text). */
|
||||
export function filterCards(cards, { states = [], zone = '' } = {}) {
|
||||
return cards.filter(c => {
|
||||
if (states.length && !states.includes(c.state)) return false
|
||||
if (zone === NO_ZONE) return !c.table.group_id
|
||||
if (zone) return String(c.table.group_id ?? '') === zone
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/** Flags on each table: { tableId: [{ ...flag, assigned_at }] } from the definitions and the assignments. */
|
||||
export function flagsByTable(defs = [], assignments = []) {
|
||||
const byId = new Map(defs.map(f => [f.id, f]))
|
||||
const out = {}
|
||||
for (const a of assignments) {
|
||||
const def = byId.get(a.flag_id)
|
||||
if (def) (out[a.table_id] ??= []).push({ ...def, assigned_at: a.assigned_at })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Where a table's card goes: its order, or a new order at that table. */
|
||||
export const cardTarget = card => (card.order ? `/orders/${card.order.id}` : `/orders/new?table=${card.table.id}`)
|
||||
@@ -14,6 +14,8 @@ import { useLiveQuery } from '../../live/useLiveQuery'
|
||||
import { lineTotal, orderTotal } from './overviewLogic'
|
||||
import { Money, Pill } from './parts'
|
||||
import { useDuration } from './hooks'
|
||||
import PayDialog from '../orders/PayDialog'
|
||||
import { closeStep, selectedAmount, unpaidIds, venueRules } from '../orders/orderLogic'
|
||||
|
||||
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded']
|
||||
const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
|
||||
@@ -27,6 +29,9 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
|
||||
const [confirm, setConfirm] = useState(null) // { kind: 'cancelItem', itemId } | { kind: 'cancelOrder' } | { kind: 'close' }
|
||||
const [printCancel, setPrintCancel] = useState(null) // the same, after "yes": ask about the ticket
|
||||
const [printerId, setPrinterId] = useState('')
|
||||
const [paying, setPaying] = useState(null) // { ids, thenClose } (6.9: cash or card, the venue's close rule)
|
||||
const { data: settings } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
|
||||
const venue = venueRules(settings)
|
||||
|
||||
const { data: order, isPending } = useLiveQuery({
|
||||
queryKey: ['order', orderId],
|
||||
@@ -52,7 +57,12 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
|
||||
onSuccess: () => { toast.success(done); refresh(); after?.() },
|
||||
onError: err => toast.error(errorMessage(err, t)),
|
||||
})
|
||||
const pay = useMutation(run(ids => client.post(`/api/orders/${orderId}/pay`, { item_ids: ids }), t('overview.order.paidDone')))
|
||||
const pay = ids => setPaying({ ids })
|
||||
const startClose = () => {
|
||||
const step = closeStep(order, venue.closeWithUnpaid)
|
||||
if (step === 'payFirst') setPaying({ ids: unpaidIds(order), thenClose: true })
|
||||
else setConfirm({ kind: step === 'writeOff' ? 'writeOff' : 'close' })
|
||||
}
|
||||
const cancelItem = useMutation(run(({ itemId, print }) => client.delete(`/api/orders/${orderId}/items/${itemId}`, { params: { print_cancellation: print } }), t('overview.order.lineCancelled')))
|
||||
const cancelOrder = useMutation(run(({ print }) => client.delete(`/api/orders/${orderId}`, { params: { print_cancellation: print } }), t('overview.order.cancelled'), onClose))
|
||||
const close = useMutation(run(() => client.post(`/api/orders/${orderId}/close`), t('overview.order.closed'), onClose))
|
||||
@@ -64,7 +74,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
|
||||
const confirmed = () => {
|
||||
const c = confirm
|
||||
setConfirm(null)
|
||||
if (c.kind === 'close') close.mutate()
|
||||
if (c.kind === 'close' || c.kind === 'writeOff') close.mutate()
|
||||
else setPrintCancel(c)
|
||||
}
|
||||
const cancelWith = printIt => {
|
||||
@@ -83,8 +93,8 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
|
||||
</span>}
|
||||
description={order ? t('overview.order.sub', { id: order.id, time: formatTime(order.opened_at), since: since(order.opened_at) }) : undefined}
|
||||
footer={order && <div className="flex flex-wrap items-center gap-2 w-full">
|
||||
{isOpen && active.length > 0 && <Button onClick={() => pay.mutate(active.map(i => i.id))} loading={pay.isPending} data-testid="order-pay-all">{t('overview.order.payAll')}</Button>}
|
||||
{isOpen && <Button variant="secondary" onClick={() => setConfirm({ kind: 'close' })}>{t('overview.order.close')}</Button>}
|
||||
{isOpen && active.length > 0 && <Button onClick={() => pay(active.map(i => i.id))} data-testid="order-pay-all">{t('overview.order.payAll')}</Button>}
|
||||
{isOpen && <Button variant="secondary" onClick={startClose} data-testid="order-close">{t('overview.order.close')}</Button>}
|
||||
{isOpen && <Button variant="danger" onClick={() => setConfirm({ kind: 'cancelOrder' })}>{t('overview.order.cancel')}</Button>}
|
||||
<span className="flex-1" />
|
||||
{printers.length > 0 && (
|
||||
@@ -125,7 +135,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
|
||||
</div>
|
||||
<Money value={lineTotal(item)} className={cx('text-body font-semibold min-w-16 text-right', item.price_adjustment ? 'text-info-ink' : 'text-ink')} />
|
||||
{isOpen && item.status === 'active' && (<>
|
||||
<Button size="sm" variant="secondary" onClick={() => pay.mutate([item.id])}>{t('overview.order.pay')}</Button>
|
||||
<Button size="sm" variant="secondary" onClick={() => pay([item.id])}>{t('overview.order.pay')}</Button>
|
||||
<IconButton size="sm" variant="ghost" label={t('overview.order.cancelLine')} onClick={() => setConfirm({ kind: 'cancelItem', itemId: item.id })}><X size={16} /></IconButton>
|
||||
</>)}
|
||||
</div>
|
||||
@@ -146,16 +156,28 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
|
||||
)}
|
||||
|
||||
{confirm && (
|
||||
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t(`overview.order.confirm.${confirm.kind}`)}
|
||||
<Dialog open size="sm" onClose={() => setConfirm(null)} title={confirm.kind === 'writeOff' ? t('orders.writeOffTitle') : t(`overview.order.confirm.${confirm.kind}`)}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('overview.back')}</Button>
|
||||
<Button variant={confirm.kind === 'close' ? 'primary' : 'danger'} onClick={confirmed} data-testid="order-confirm">
|
||||
{confirm.kind === 'close' ? t('overview.order.close') : t('overview.order.cancel')}
|
||||
{confirm.kind === 'close' ? t('overview.order.close') : confirm.kind === 'writeOff' ? t('orders.writeOff') : t('overview.order.cancel')}
|
||||
</Button>
|
||||
</>}>
|
||||
{confirm.kind === 'cancelOrder' && <p>{t('overview.order.confirm.cancelOrderBody')}</p>}
|
||||
{confirm.kind === 'writeOff' && <p>{t('orders.writeOffBody', { count: unpaidIds(order).length, amount: formatMoney(selectedAmount(order, unpaidIds(order))) })}</p>}
|
||||
</Dialog>
|
||||
)}
|
||||
{paying && order && (
|
||||
<PayDialog orderId={orderId} itemIds={paying.ids} amount={selectedAmount(order, paying.ids)} card={venue.card} thenClose={!!paying.thenClose}
|
||||
onClose={() => setPaying(null)}
|
||||
onDone={() => {
|
||||
toast.success(paying.thenClose ? t('overview.order.closed') : t('overview.order.paidDone'))
|
||||
const closed = paying.thenClose
|
||||
setPaying(null)
|
||||
refresh()
|
||||
if (closed) onClose()
|
||||
}} />
|
||||
)}
|
||||
{printCancel && (
|
||||
<Dialog open size="sm" onClose={() => setPrintCancel(null)} title={t('overview.order.printCancel')}
|
||||
footer={<>
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import { X } from 'lucide-react'
|
||||
|
||||
const METHODS = [
|
||||
{ key: 'cash', label: 'ΜΕΤΡΗΤΑ', icon: '💵', color: '#15803d', bg: '#f0fdf4', border: '#86efac' },
|
||||
{ key: 'card', label: 'ΚΑΡΤΑ', icon: '💳', color: '#1d4ed8', bg: '#eff6ff', border: '#93c5fd' },
|
||||
{ key: 'transfer', label: 'ΤΡΑΠΕΖΙΚΗ ΜΕΤΑΦΟΡΑ', icon: '🏦', color: '#6d28d9', bg: '#f5f3ff', border: '#c4b5fd' },
|
||||
{ key: 'treat', label: 'ΚΕΡΑΣΤΗΚΕ', icon: '🎁', color: '#b45309', bg: '#fffbeb', border: '#fcd34d' },
|
||||
]
|
||||
|
||||
export default function PaymentMethodModal({ onSelect, onCancel, title = 'Τρόπος Πληρωμής;' }) {
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
|
||||
onClick={onCancel}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-sm rounded-2xl bg-white shadow-2xl"
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
|
||||
<span className="text-base font-bold text-gray-800">{title}</span>
|
||||
<button onClick={onCancel} className="text-gray-400 hover:text-gray-600 p-1">
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Method buttons */}
|
||||
<div className="p-4 grid grid-cols-2 gap-3">
|
||||
{METHODS.map(m => (
|
||||
<button
|
||||
key={m.key}
|
||||
onClick={() => onSelect(m.key)}
|
||||
style={{ background: m.bg, borderColor: m.border, color: m.color }}
|
||||
className="flex flex-col items-center justify-center gap-2 rounded-xl border-2 py-5 font-bold text-sm transition-transform active:scale-95 hover:opacity-90"
|
||||
>
|
||||
<span className="text-2xl">{m.icon}</span>
|
||||
{m.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="px-4 pb-4">
|
||||
<button
|
||||
onClick={onCancel}
|
||||
className="w-full rounded-lg border border-gray-200 py-2 text-sm text-gray-500 hover:bg-gray-50"
|
||||
>
|
||||
Ακύρωση
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user