feat: initial commit — local services (backend + manager dashboard + waiter PWA)

Includes all work to date:
- local_backend: FastAPI backend with products, orders, tables, shifts, cloud sync
- manager_dashboard: React manager UI with product/category management, reports, settings
- waiter_pwa: React PWA for waiter devices
- Category reparent endpoint and UI
- Waiter domain: local_ip sent on heartbeat, waiter_domain persisted from cloud response
- QR code modal in AppInfoTab for waiter domain
- Product form: number input spinners removed, category pre-selected on new product
- Category row: count badge moved to far right

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-20 14:04:38 +03:00
co-authored by Claude Sonnet 4.6
commit 8ba8c95ecd
209 changed files with 48017 additions and 0 deletions
+843
View File
@@ -0,0 +1,843 @@
import { useEffect, useState } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import ProductPicker from '../components/ProductPicker'
import OrderDrawer from '../components/OrderDrawer'
import client from '../api/client'
export default function AddItemsPage() {
const { tableId } = useParams()
const [searchParams] = useSearchParams()
const isNewTable = searchParams.get('new') === '1'
const navigate = useNavigate()
const [categories, setCategories] = useState([])
const [products, setProducts] = useState([])
const [cart, setCart] = useState([])
const [orderId, setOrderId] = useState(null)
const [sending, setSending] = useState(false)
const [retrying, setRetrying] = useState(false)
const [error, setError] = useState('')
const [printAck, setPrintAck] = useState(null)
const [cartOpen, setCartOpen] = useState(false)
const [editItem, setEditItem] = useState(null) // { cartKey, product, drawerState }
const [viewAllOpen, setViewAllOpen] = useState(false)
const [searchOpen, setSearchOpen] = useState(false)
const [searchQuery, setSearchQuery] = useState('')
useEffect(() => {
async function load() {
const [catRes, prodRes, statusRes] = await Promise.all([
client.get('/api/products/categories'),
client.get('/api/products/'),
client.get(`/api/tables/${tableId}/status`),
])
setCategories(catRes.data)
setProducts(prodRes.data)
setOrderId(statusRes.data.active_order_id)
// Pre-populate cart from "order again" if present
const stored = sessionStorage.getItem('orderAgainItems')
if (stored) {
sessionStorage.removeItem('orderAgainItems')
try {
const items = JSON.parse(stored)
const initialCart = items.map(it => ({
...it,
_key: Date.now() + Math.random(),
}))
setCart(initialCart)
} catch {}
}
}
load()
}, [tableId])
// Back button: if this was a new table and nothing was added, leave the table FREE
function handleBack() {
if (isNewTable && cart.length === 0) {
navigate('/tables', { replace: true })
} else {
navigate(`/tables/${tableId}`)
}
}
function addToCart(item) {
setCart(prev => {
// Try to find an identical item already in the cart to stack onto.
// Two items are identical when every meaningful field matches exactly.
const { _key: _k, _drawerState: _ds, ...newCore } = item
const matchIdx = prev.findIndex(existing => {
const { _key, _drawerState, ...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 removeFromCart(key) {
setCart(prev => prev.filter(i => i._key !== key))
}
function changeCartQty(key, newQty) {
if (newQty <= 0) {
removeFromCart(key)
} else {
setCart(prev => prev.map(i => i._key === key ? { ...i, quantity: newQty } : i))
}
}
function openEditDrawer(cartItem) {
const product = products.find(p => p.id === cartItem.product_id)
if (!product) return
setCartOpen(false)
setEditItem({ cartKey: cartItem._key, product, drawerState: cartItem._drawerState })
}
function handleEditSave(updatedItem) {
setCart(prev => prev.map(i =>
i._key === editItem.cartKey ? { ...updatedItem, _key: i._key } : i
))
setEditItem(null)
}
async function sendOrder() {
if (cart.length === 0) return
setSending(true)
setError('')
setPrintAck(null)
setCartOpen(false)
try {
// For new (free) tables, open the order now — lazily
let activeOrderId = orderId
if (!activeOrderId) {
const { data: newOrder } = await client.post('/api/orders/', { table_id: Number(tableId) })
activeOrderId = newOrder.id
setOrderId(activeOrderId)
}
const res = await client.post(`/api/orders/${activeOrderId}/items`, {
items: cart.map(({ _key, _drawerState, ...item }) => item),
})
const printResults = res.data.print_results ?? []
const allOk = printResults.length === 0 || printResults.every(r => r.success)
setPrintAck({ allOk, results: printResults })
if (allOk) setTimeout(() => navigate('/tables'), 1200)
} catch (err) {
setError(err.response?.data?.detail || 'Σφάλμα αποστολής — η παραγγελία δεν στάλθηκε')
} finally {
setSending(false)
}
}
async function retryNow() {
if (!orderId) return
setRetrying(true)
try {
const res = await client.post(`/api/orders/${orderId}/retry-print`)
const printResults = res.data.print_results ?? []
const allOk = printResults.length === 0 || printResults.every(r => r.success)
setPrintAck({ allOk, results: printResults })
if (allOk) setTimeout(() => navigate('/tables'), 1200)
} catch { } finally { setRetrying(false) }
}
function saveAsDraft() { navigate(`/tables/${tableId}`, { replace: true }) }
function leaveAndContinue() { navigate(`/tables/${tableId}`, { replace: true }) }
function getProduct(id) { return products.find(p => p.id === id) }
// Returns structured sections for the expanded cart view
function buildItemSections(item, product) {
const sections = []
if (item.selected_options?.length) {
const prefIds = new Set(
(product?.preference_sets || []).flatMap(ps => ps.choices.map(c => c.id))
)
// Build a map: prefChoiceId → preference set name
const prefSetByChoiceId = {}
;(product?.preference_sets || []).forEach(ps => {
ps.choices.forEach(c => { prefSetByChoiceId[c.id] = ps.name })
})
const quickNames = new Set((product?.quick_options || []).map(o => o.name))
const extraIds = new Set((product?.options || []).map(o => o.id))
// Group prefs: { prefSetName, choiceName, subName }
const prefGroups = []
// Group extras: { name, subName, qty } — one entry per unique (id)
const extraGroups = []
const quickLines = []
let i = 0
const opts = item.selected_options
while (i < opts.length) {
const o = opts[i]
if (prefIds.has(o.id)) {
// Collect sub immediately following (id === null)
const setName = prefSetByChoiceId[o.id] ?? ''
let subName = null
if (i + 1 < opts.length && opts[i + 1].id == null) {
subName = opts[i + 1].name
i += 2
} else {
i++
}
// Merge into existing prefGroup for same setName, or create new
const existing = prefGroups.find(g => g.setName === setName)
if (existing) {
// multiple choices from same set (shouldn't normally happen, but handle gracefully)
existing.values.push(subName ? `${o.name} · ${subName}` : o.name)
} else {
prefGroups.push({ setName, values: [subName ? `${o.name} · ${subName}` : o.name] })
}
} else if (o.id != null && extraIds.has(o.id)) {
// Collect sub immediately following
let subName = null
if (i + 1 < opts.length && opts[i + 1].id == null) {
subName = opts[i + 1].name
i += 2
} else {
i++
}
// Merge duplicates
const existing = extraGroups.find(g => g.id === o.id && g.subName === subName)
if (existing) existing.qty++
else extraGroups.push({ id: o.id, name: o.name, subName, qty: 1 })
} else if (quickNames.has(o.name)) {
quickLines.push(o)
i++
} else {
i++
}
}
// Deduplicate quick lines: multiple entries of same name → single entry with qty
const quickDeduped = []
quickLines.forEach(o => {
const existing = quickDeduped.find(x => x.name === o.name)
if (existing) existing._qty = (existing._qty || 1) + 1
else quickDeduped.push({ ...o, _qty: 1 })
})
if (prefGroups.length > 0) sections.push({ type: 'prefs', lines: prefGroups })
if (quickDeduped.length > 0) sections.push({ type: 'quick', lines: quickDeduped })
if (extraGroups.length > 0) sections.push({ type: 'extras', lines: extraGroups })
}
if (item.removed_ingredients?.length) {
sections.push({ type: 'removed', lines: item.removed_ingredients.map(n => ({ name: n })) })
}
if (item.notes) {
sections.push({ type: 'note', lines: [{ name: item.notes }] })
}
return sections
}
// Simple flat summary for the collapsed one-liner
function buildItemSummary(item) {
const lines = []
if (item.selected_options?.length) {
item.selected_options.forEach(o => {
if (o.price_delta && o.price_delta !== 0)
lines.push(`${o.name} (${o.price_delta > 0 ? '+' : ''}${o.price_delta.toFixed(2)} €)`)
else lines.push(o.name)
})
}
if (item.removed_ingredients?.length) lines.push(`Χωρίς: ${item.removed_ingredients.join(', ')}`)
if (item.notes) lines.push(item.notes)
return lines
}
// Print-failure dialog
if (printAck && !printAck.allOk) {
return (
<div className="page">
<header className="top-bar">
<button className="icon-btn" onClick={() => navigate(`/tables/${tableId}`, { replace: true })}>←</button>
<span className="top-bar__title">Πρόβλημα εκτύπωσης</span>
</header>
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 14, padding: 20, overflowY: 'auto' }}>
<div style={{ background: '#7f1d1d', borderRadius: 14, padding: '14px 16px', border: '1px solid #ef4444' }}>
<p style={{ fontWeight: 700, fontSize: 15, color: '#fca5a5', marginBottom: 6 }}>⚠ Η παραγγελία αποθηκεύτηκε</p>
<p style={{ fontSize: 13, color: '#fca5a5', lineHeight: 1.5 }}>Ένας ή περισσότεροι εκτυπωτές δεν ανταποκρίθηκαν.</p>
</div>
{printAck.results.map((r, i) => (
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, background: r.success ? '#14532d' : '#431407', border: `1px solid ${r.success ? '#22c55e' : '#c2410c'}`, borderRadius: 12, padding: '10px 14px' }}>
<span style={{ fontSize: 20 }}>{r.success ? '✓' : '✗'}</span>
<div style={{ flex: 1 }}>
<p style={{ fontWeight: 600, fontSize: 14, color: r.success ? '#86efac' : '#fdba74' }}>{r.printer_name}</p>
{!r.success && <p style={{ fontSize: 12, color: '#fdba74', marginTop: 2 }}>Εκτυπωτής μη προσβάσιμος</p>}
</div>
</div>
))}
<p style={{ fontSize: 12, color: '#64748b', textAlign: 'center', margin: '4px 0' }}>Επιλέξτε πώς να συνεχίσετε:</p>
<button className="btn btn--primary" style={{ width: '100%', padding: '14px 16px', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12, opacity: retrying ? 0.7 : 1 }} onClick={retryNow} disabled={retrying}>
<span style={{ fontSize: 22 }}>🔄</span>
<div>
<p style={{ fontWeight: 700, fontSize: 14, margin: 0 }}>{retrying ? 'Επανάληψη…' : 'Επανάληψη τώρα'}</p>
<p style={{ fontSize: 12, opacity: 0.8, margin: 0, marginTop: 2 }}>Δοκιμή αποστολής στον εκτυπωτή ξανά</p>
</div>
</button>
<button className="btn btn--secondary" style={{ width: '100%', padding: '14px 16px', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12 }} onClick={saveAsDraft}>
<span style={{ fontSize: 22 }}>📋</span>
<div>
<p style={{ fontWeight: 700, fontSize: 14, margin: 0 }}>Αποθήκευση ως προσχέδιο</p>
<p style={{ fontSize: 12, opacity: 0.75, margin: 0, marginTop: 2 }}>Τα αντικείμενα μένουν στο τραπέζι με πορτοκαλί ένδειξη</p>
</div>
</button>
<button style={{ width: '100%', padding: '14px 16px', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12, background: '#1e293b', border: '1px solid #334155', borderRadius: 12, color: '#cbd5e1', cursor: 'pointer' }} onClick={leaveAndContinue}>
<span style={{ fontSize: 22 }}>🕐</span>
<div>
<p style={{ fontWeight: 700, fontSize: 14, margin: 0 }}>Συνέχεια (προσχέδιο)</p>
<p style={{ fontSize: 12, opacity: 0.75, margin: 0, marginTop: 2 }}>Τα αντικείμενα εμφανίζονται ως εκκρεμή στο dashboard</p>
</div>
</button>
</div>
</div>
)
}
// Compact names for the strip preview (max 3 items shown)
const stripItems = cart.slice(-3).reverse()
const hiddenCount = cart.length > 3 ? cart.length - 3 : 0
return (
<div className="page" style={{ position: 'relative' }}>
<header className="top-bar">
<button className="icon-btn" onClick={handleBack}>←</button>
<span className="top-bar__title">{isNewTable ? 'Νέα Παραγγελία' : 'Προσθήκη'}</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
{/* Search button */}
<button className="icon-btn" onClick={() => { setSearchQuery(''); setSearchOpen(true) }} title="Αναζήτηση">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2.2"/>
<path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
</svg>
</button>
{/* Categories button */}
<button className="icon-btn" onClick={() => setViewAllOpen(true)} title="Όλες οι κατηγορίες">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<rect x="3" y="3" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
<rect x="14" y="3" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
<rect x="3" y="14" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
<rect x="14" y="14" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
</svg>
</button>
{/* Cart button with badge */}
<button
className="icon-btn"
style={{ position: 'relative' }}
onClick={() => setCartOpen(true)}
>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none">
<path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4zM3 6h18M16 10a4 4 0 01-8 0" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
{cart.length > 0 && (
<span style={{
position: 'absolute', top: -2, right: -2,
minWidth: 18, height: 18, borderRadius: 9,
background: 'var(--accent)', color: 'var(--accent-fg)',
fontSize: 11, fontWeight: 800,
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: '0 4px',
}}>{cart.length}</span>
)}
</button>
</div>
</header>
{/* Product picker takes all remaining space */}
{categories.length > 0 && (
<ProductPicker
categories={categories}
products={products}
onAdd={addToCart}
viewAllOpen={viewAllOpen}
setViewAllOpen={setViewAllOpen}
/>
)}
{/* ── Bottom bar: floating mini-cart + full-width ΑΠΟΣΤΟΛΗ ─────────────── */}
<div style={{
background: 'var(--bg2)',
borderTop: '1px solid var(--border)',
padding: '10px 12px 14px',
flexShrink: 0,
}}>
{/* Floating compact cart — shown only when there are items */}
{cart.length > 0 && (
<div
onClick={() => setCartOpen(true)}
style={{
background: 'var(--bg3)',
border: '1px solid var(--border)',
borderRadius: 12,
padding: '8px 12px',
marginBottom: 10,
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
gap: 4,
}}
>
{stripItems.map(item => {
const p = getProduct(item.product_id)
return (
<div key={item._key} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ fontSize: 12, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>{p?.name ?? `#${item.product_id}`}</span>
<span style={{ fontSize: 12, fontWeight: 700, color: '#f59e0b', fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>×{item.quantity}</span>
</div>
)
})}
{hiddenCount > 0 && (
<div style={{ fontSize: 11, color: 'var(--muted)', textAlign: 'right' }}>
+{hiddenCount} ακόμα — δείτε όλα →
</div>
)}
</div>
)}
{/* Full-width send button */}
<button
className="btn btn--primary btn--lg"
style={{ width: '100%', opacity: cart.length === 0 ? 0.4 : 1 }}
onClick={sendOrder}
disabled={cart.length === 0 || sending || !!printAck?.allOk}
>
{sending ? 'Αποστολή…' : `ΑΠΟΣΤΟΛΗ${cart.length > 0 ? ` (${cart.length})` : ''}`}
</button>
{error && <p className="error-msg" style={{ marginTop: 8 }}>{error}</p>}
</div>
{/* ── Cart side drawer ────────────────────────────────────────────────── */}
<>
{/* Backdrop */}
<div
onClick={() => setCartOpen(false)}
style={{
position: 'fixed', inset: 0,
background: 'rgba(0,0,0,0.55)',
opacity: cartOpen ? 1 : 0,
pointerEvents: cartOpen ? 'auto' : 'none',
transition: 'opacity 240ms ease',
zIndex: 50,
}}
/>
{/* Panel */}
<div style={{
position: 'fixed', top: 0, right: 0, bottom: 0,
width: 'min(88vw, 380px)',
background: 'var(--bg)',
borderLeft: '1px solid var(--border)',
transform: cartOpen ? 'translateX(0)' : 'translateX(100%)',
transition: 'transform 280ms cubic-bezier(0.32, 0.72, 0, 1)',
zIndex: 51,
display: 'flex', flexDirection: 'column',
boxShadow: '-8px 0 32px rgba(0,0,0,0.4)',
}}>
{/* Drawer header */}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
<div>
<div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)' }}>Παραγγελία</div>
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{cart.length} {cart.length === 1 ? 'προϊόν' : 'προϊόντα'}</div>
</div>
<button onClick={() => setCartOpen(false)} style={{ background: 'var(--bg3)', border: 'none', borderRadius: '50%', width: 34, height: 34, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'var(--text)' }}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
</button>
</div>
{/* Item list */}
<div style={{ flex: 1, overflowY: 'auto', padding: 12 }}>
{cart.length === 0 ? (
<p style={{ color: 'var(--muted)', textAlign: 'center', padding: '40px 0', fontSize: 14 }}>Η παραγγελία είναι κενή.</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{cart.map(item => {
const product = getProduct(item.product_id)
const summaryLines = buildItemSummary(item)
const sections = buildItemSections(item, product)
return (
<CartItem
key={item._key}
item={item}
product={product}
summaryLines={summaryLines}
sections={sections}
onEdit={() => openEditDrawer(item)}
onRemove={() => removeFromCart(item._key)}
onChangeQty={qty => changeCartQty(item._key, qty)}
/>
)
})}
</div>
)}
</div>
{/* Drawer footer */}
<div style={{ padding: '12px 12px 20px', borderTop: '1px solid var(--border)', flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
<button
className="btn btn--primary btn--lg"
style={{ width: '100%' }}
onClick={sendOrder}
disabled={cart.length === 0 || sending || !!printAck?.allOk}
>
{sending ? 'Αποστολή…' : `Αποστολή Παραγγελίας (${cart.length})`}
</button>
</div>
</div>
</>
{/* Edit drawer */}
{editItem && (
<OrderDrawer
product={editItem.product}
isOpen={!!editItem}
onClose={() => setEditItem(null)}
onAdd={handleEditSave}
initialState={editItem.drawerState}
/>
)}
{/* ── Search modal ─────────────────────────────────────────────────────── */}
{searchOpen && (
<SearchModal
products={products}
query={searchQuery}
setQuery={setSearchQuery}
onClose={() => setSearchOpen(false)}
onAdd={item => { addToCart(item); setSearchOpen(false) }}
/>
)}
{/* Full-screen success overlay — blocks all interaction while navigating */}
{printAck?.allOk && (
<div style={{
position: 'fixed', inset: 0, zIndex: 9999,
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
background: 'rgba(0,0,0,0.72)',
animation: 'fadeInOverlay 180ms ease',
}}>
<div style={{
background: '#14532d', border: '2px solid #22c55e',
borderRadius: 20, padding: '36px 48px',
display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,
animation: 'popIn 220ms cubic-bezier(0.34,1.56,0.64,1)',
}}>
<svg width="56" height="56" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="11" stroke="#22c55e" strokeWidth="2"/>
<path d="M7 12.5l3.5 3.5 6.5-7" stroke="#22c55e" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
<span style={{ color: '#86efac', fontWeight: 700, fontSize: 18, letterSpacing: 0.3 }}>
Εκτυπώθηκε Επιτυχώς
</span>
</div>
<style>{`
@keyframes fadeInOverlay { from { opacity: 0 } to { opacity: 1 } }
@keyframes popIn { from { transform: scale(0.7); opacity: 0 } to { transform: scale(1); opacity: 1 } }
`}</style>
</div>
)}
</div>
)
}
// ── Cart Item (used in the side drawer) ───────────────────────────────────────
const SECTION_META = {
prefs: { icon: '◉', label: null },
quick: { icon: '>', label: null },
extras: { icon: '+', label: null },
removed: { icon: '−', label: null },
note: { icon: 'i', label: null },
}
function SectionIcon({ type }) {
const icons = {
prefs: <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="4" fill="#f59e0b"/><circle cx="12" cy="12" r="9" stroke="#f59e0b" strokeWidth="2"/></svg>,
quick: <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="#a3e635" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>,
extras: <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M12 5v14M5 12h14" stroke="#60a5fa" strokeWidth="2.5" strokeLinecap="round"/></svg>,
removed: <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M5 12h14" stroke="#ef4444" strokeWidth="2.5" strokeLinecap="round"/></svg>,
note: <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="1.5" fill="#94a3b8"/><path d="M12 7v1M12 16v1" stroke="#94a3b8" strokeWidth="2" strokeLinecap="round"/><circle cx="12" cy="12" r="9" stroke="#94a3b8" strokeWidth="1.5"/></svg>,
}
return <span style={{ display: 'inline-flex', alignItems: 'center', flexShrink: 0 }}>{icons[type] ?? null}</span>
}
function CartItem({ item, product, summaryLines, sections, onEdit, onRemove, onChangeQty }) {
const [expanded, setExpanded] = useState(false)
const hasDetails = sections.length > 0
return (
<div style={{ background: 'var(--bg2)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
{/* Whole header row is always clickable to expand (qty stepper is always available) */}
<div
onClick={() => setExpanded(e => !e)}
style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', cursor: 'pointer' }}
>
{/* Chevron — always shown */}
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" style={{ transform: `rotate(${expanded ? 180 : 0}deg)`, transition: 'transform 180ms', flexShrink: 0, color: 'var(--muted)' }}>
<path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
</svg>
{/* Name */}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{product?.name ?? `#${item.product_id}`}
</div>
{!expanded && hasDetails && (
<div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{summaryLines[0]}{summaryLines.length > 1 ? ` +${summaryLines.length - 1}` : ''}
</div>
)}
</div>
{/* Quantity on the right */}
<span style={{ color: '#f59e0b', fontSize: 13, fontWeight: 700, fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>×{item.quantity}</span>
{/* Edit — stop propagation so it doesn't toggle expand */}
<button onClick={e => { e.stopPropagation(); onEdit() }} style={{ background: 'none', border: '1px solid var(--border)', borderRadius: 7, color: 'var(--muted)', cursor: 'pointer', padding: '3px 9px', fontSize: 12, fontWeight: 500, flexShrink: 0 }}>
Επεξ.
</button>
{/* Remove */}
<button onClick={e => { e.stopPropagation(); onRemove() }} style={{ background: 'none', border: 'none', color: 'var(--danger)', cursor: 'pointer', padding: 4, display: 'flex', alignItems: 'center', flexShrink: 0 }}>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
</button>
</div>
{expanded && (
<div style={{ paddingBottom: 10 }}>
{sections.map((sec, si) => (
<div key={si}>
<div style={{ margin: '0 12px', height: 1, background: 'var(--border)' }} />
<div style={{ padding: '6px 12px 2px', display: 'flex', flexDirection: 'column', gap: 4 }}>
{sec.type === 'prefs' && sec.lines.map((line, li) => (
<div key={li} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
<SectionIcon type="prefs" />
<span style={{ fontSize: 12, lineHeight: 1.4, flex: 1 }}>
<span style={{ color: 'var(--muted)', display: 'block', fontSize: 11 }}>{line.setName}</span>
<span style={{ color: 'var(--text)' }}>{line.values.join(' · ')}</span>
</span>
</div>
))}
{sec.type === 'quick' && sec.lines.map((line, li) => (
<div key={li} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
<SectionIcon type="quick" />
<span style={{ fontSize: 12, color: 'var(--text)', flex: 1 }}>
{line.name}
{line._qty > 1 && <span style={{ color: '#f59e0b', marginLeft: 4, fontWeight: 700 }}>×{line._qty}</span>}
</span>
</div>
))}
{sec.type === 'extras' && sec.lines.map((line, li) => (
<div key={li} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
<SectionIcon type="extras" />
<span style={{ fontSize: 12, color: 'var(--text)', flex: 1 }}>
{line.name}
{line.subName && <span> · {line.subName}</span>}
{line.qty > 1 && <span style={{ color: '#f59e0b', marginLeft: 4, fontWeight: 700 }}>×{line.qty}</span>}
</span>
</div>
))}
{sec.type === 'removed' && sec.lines.map((line, li) => (
<div key={li} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
<SectionIcon type="removed" />
<span style={{ fontSize: 12, color: 'var(--text)', flex: 1 }}>Χωρίς {line.name}</span>
</div>
))}
{sec.type === 'note' && sec.lines.map((line, li) => (
<div key={li} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
<SectionIcon type="note" />
<span style={{ fontSize: 12, color: 'var(--text)', lineHeight: 1.4, flex: 1, whiteSpace: 'pre-wrap' }}>{line.name}</span>
</div>
))}
</div>
</div>
))}
{/* ── Quick qty row ── */}
<div style={{ margin: '8px 12px 0', height: 1, background: 'var(--border)' }} />
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16,
padding: '10px 12px 2px',
}}>
<button
onClick={e => { e.stopPropagation(); onChangeQty(item.quantity - 1) }}
style={{
width: 36, height: 36, borderRadius: '50%',
background: 'var(--bg3)', border: '1px solid var(--border)',
color: item.quantity <= 1 ? 'var(--muted)' : 'var(--danger)',
fontSize: 20, fontWeight: 700, cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
>
{item.quantity <= 1 ? (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
) : '−'}
</button>
<span style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)', minWidth: 28, textAlign: 'center' }}>
{item.quantity}
</span>
<button
onClick={e => { e.stopPropagation(); onChangeQty(item.quantity + 1) }}
style={{
width: 36, height: 36, borderRadius: '50%',
background: 'var(--bg3)', border: '1px solid var(--border)',
color: '#22c55e',
fontSize: 20, fontWeight: 700, cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
>+</button>
</div>
</div>
)}
</div>
)
}
// ── Search Modal ──────────────────────────────────────────────────────────────
function SearchModal({ products, query, setQuery, onClose, onAdd }) {
const [drawerProduct, setDrawerProduct] = useState(null)
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())
)
function openProduct(p) {
// Blur the input first so the keyboard dismisses, then open the drawer
document.activeElement?.blur()
setDrawerProduct(p)
}
// The modal is position:fixed anchored to bottom:0.
// When the soft keyboard opens on mobile the browser shrinks the visual
// viewport and fixed elements reposition automatically — the panel sits
// right on top of the keyboard without any JS measurement needed.
return (
<>
{/* Dim backdrop — tap to close */}
<div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 200 }} />
{/* Panel: fixed to bottom, grows upward, capped at 60vh so results don't
push the input off screen on short viewports */}
<div style={{
position: 'fixed', left: 0, right: 0, bottom: 0,
zIndex: 201,
background: 'var(--bg)',
borderTop: '1px solid var(--border)',
display: 'flex', flexDirection: 'column',
maxHeight: '60vh',
}}>
{/* Results scroll area — flex:1 so it takes space above the input */}
<div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
{query.trim().length === 0 ? (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: '16px 20px', fontSize: 14 }}>
Πληκτρολογήστε για αναζήτηση…
</p>
) : results.length === 0 ? (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: '16px 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={() => openProduct(p)}
style={{
display: 'flex', alignItems: 'center', gap: 12,
width: '100%', padding: '10px 16px',
background: 'none', border: 'none', cursor: 'pointer',
borderBottom: '1px solid var(--border)',
textAlign: 'left',
}}
>
<div style={{
width: 40, height: 40, borderRadius: 10, flexShrink: 0,
background: 'var(--bg3)', overflow: 'hidden',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{p.image_url
? <img src={p.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--muted)' }}>{initials}</span>
}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{p.name}
</div>
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
{Number(p.base_price).toFixed(2)} €
</div>
</div>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" style={{ color: 'var(--muted)', flexShrink: 0 }}>
<path d="M9 18l6-6-6-6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</button>
)
})}
</div>
{/* Search input — pinned at the bottom of the panel, above the keyboard */}
<div style={{
display: 'flex', alignItems: 'center', gap: 8,
padding: '10px 12px 12px',
borderTop: '1px solid var(--border)',
flexShrink: 0,
}}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" style={{ color: 'var(--muted)', flexShrink: 0 }}>
<circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2.2"/>
<path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
</svg>
<input
autoFocus
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Αναζήτηση προϊόντος…"
style={{
flex: 1, height: 44, background: 'var(--bg2)',
border: '1px solid var(--border)', borderRadius: 12,
padding: '0 12px', fontSize: 16, color: 'var(--text)',
fontFamily: 'inherit', outline: 'none',
}}
/>
<button
onClick={onClose}
style={{
background: 'var(--bg3)', border: 'none', borderRadius: '50%',
width: 36, height: 36, flexShrink: 0,
display: 'flex', alignItems: 'center', justifyContent: 'center',
cursor: 'pointer', color: 'var(--text)',
}}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none">
<path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
</svg>
</button>
</div>
</div>
{/* Product drawer — closes search modal when item is added */}
{drawerProduct && (
<OrderDrawer
product={drawerProduct}
isOpen
onClose={() => setDrawerProduct(null)}
onAdd={item => { onAdd(item); setDrawerProduct(null); onClose() }}
/>
)}
</>
)
}
+229
View File
@@ -0,0 +1,229 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import PinPad from '../components/PinPad'
import useAuthStore from '../store/authStore'
import client from '../api/client'
// ─── Waiter card ──────────────────────────────────────────────────────────────
function WaiterCard({ waiter, onClick }) {
const initials = (waiter.full_name || waiter.nickname || '?')
.split(' ')
.map(w => w[0])
.join('')
.slice(0, 2)
.toUpperCase()
return (
<button
onClick={onClick}
style={{
display: 'flex', alignItems: 'center', gap: 14,
padding: '14px 16px',
background: 'var(--bg2)',
border: '1px solid var(--border)',
borderRadius: 14,
cursor: 'pointer',
width: '100%',
textAlign: 'left',
position: 'relative',
transition: 'border-color 0.15s',
boxSizing: 'border-box',
}}
>
{/* Avatar */}
<div style={{
width: 48, height: 48, borderRadius: '50%', flexShrink: 0,
background: waiter.avatar_url ? 'transparent' : 'var(--bg3)',
border: `2px solid ${waiter.on_shift ? '#22c55e' : 'var(--border)'}`,
overflow: 'hidden',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 18, fontWeight: 700, color: 'var(--text)',
}}>
{waiter.avatar_url
? <img src={waiter.avatar_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: initials
}
</div>
{/* Name block */}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', wordBreak: 'break-word', whiteSpace: 'normal', lineHeight: 1.3 }}>
{waiter.full_name || waiter.nickname || '—'}
</div>
{waiter.nickname && waiter.full_name && (
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{waiter.nickname}</div>
)}
</div>
{/* On-shift dot */}
{waiter.on_shift && (
<span style={{
width: 10, height: 10, borderRadius: '50%',
background: '#22c55e',
flexShrink: 0,
boxShadow: '0 0 6px #22c55e88',
}} title="Σε βάρδια" />
)}
<span style={{ color: 'var(--muted)', fontSize: 18, flexShrink: 0 }}>›</span>
</button>
)
}
// ─── Main page ────────────────────────────────────────────────────────────────
export default function LoginPage() {
const { login } = useAuthStore()
const navigate = useNavigate()
const [waiters, setWaiters] = useState([])
const [loadingWaiters, setLoadingWaiters] = useState(true)
const [serverUnreachable, setServerUnreachable] = useState(false)
const [selectedWaiter, setSelectedWaiter] = useState(null)
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
useEffect(() => {
client.get('/api/auth/waiters')
.then(r => { setWaiters(r.data); setServerUnreachable(false) })
.catch(err => {
// No response = network error = server unreachable
if (!err.response) setServerUnreachable(true)
setWaiters([])
})
.finally(() => setLoadingWaiters(false))
}, [])
async function handlePin(pin) {
if (!selectedWaiter) return
setError('')
setLoading(true)
try {
// We send waiter id as identifier; backend matches by id+pin
const { data } = await client.post('/api/auth/login-by-id', { waiter_id: selectedWaiter.id, pin })
login({ id: data.user.id, username: data.user.username, role: data.user.role }, data.access_token)
navigate('/tables')
} catch (err) {
setError(err.response?.data?.detail || 'Λανθασμένο PIN')
} finally {
setLoading(false)
}
}
// ── Waiter picker screen ───────────────────────────────────────────────────
if (!selectedWaiter) {
// Sort: on-shift first, then alphabetical
const sorted = [...waiters].sort((a, b) => {
if (a.on_shift !== b.on_shift) return a.on_shift ? -1 : 1
return (a.full_name || a.nickname || '').localeCompare(b.full_name || b.nickname || '')
})
return (
<div className="page">
{/* Static header — never scrolls */}
<div style={{ flexShrink: 0, padding: '40px 16px 20px', textAlign: 'center' }}>
<h1 className="app-title" style={{ marginBottom: 10 }}>Xenia POS</h1>
<p className="app-subtitle">Ποιος είσαι;</p>
</div>
{/* Scrollable card list */}
<div style={{ flex: 1, overflowY: 'auto', padding: '4px 16px 40px' }}>
<div style={{ maxWidth: 480, margin: '0 auto' }}>
{loadingWaiters ? (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: 32 }}>Φόρτωση…</p>
) : serverUnreachable ? (
<div style={{ textAlign: 'center', padding: 32 }}>
<div style={{ fontSize: 48, marginBottom: 16 }}>🔌</div>
<p style={{ fontSize: 17, fontWeight: 700, color: '#ef4444', marginBottom: 8 }}>
Δεν βρέθηκε ο Server
</p>
<p style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.6, marginBottom: 24 }}>
Δεν είναι δυνατή η σύνδεση με τον Manager.<br />
Δεν μπορεί να ξεκινήσει βάρδια χωρίς σύνδεση.
</p>
<button
className="btn btn--secondary"
onClick={() => {
setLoadingWaiters(true)
setServerUnreachable(false)
client.get('/api/auth/waiters')
.then(r => { setWaiters(r.data); setServerUnreachable(false) })
.catch(err => { if (!err.response) setServerUnreachable(true) })
.finally(() => setLoadingWaiters(false))
}}
>
⟳ Επανάληψη
</button>
</div>
) : waiters.length === 0 ? (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: 32 }}>Δεν βρέθηκαν σερβιτόροι</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'stretch' }}>
{sorted.map(w => (
<WaiterCard key={w.id} waiter={w} onClick={() => { setError(''); setSelectedWaiter(w) }} />
))}
</div>
)}
</div>
</div>
</div>
)
}
// ── PIN screen ─────────────────────────────────────────────────────────────
const initials = (selectedWaiter.full_name || selectedWaiter.nickname || '?')
.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase()
return (
<div className="page page--centered">
<div className="login-box">
<h1 className="app-title">XeniaPOS</h1>
{/* Selected waiter mini-card */}
<div style={{
display: 'flex', alignItems: 'center', gap: 12,
background: 'var(--bg2)', border: '1px solid var(--border)',
borderRadius: 12, padding: '10px 14px', marginBottom: 4,
}}>
<div style={{
width: 40, height: 40, borderRadius: '50%', flexShrink: 0,
background: selectedWaiter.avatar_url ? 'transparent' : 'var(--bg3)',
border: `2px solid ${selectedWaiter.on_shift ? '#22c55e' : 'var(--border)'}`,
overflow: 'hidden',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 15, fontWeight: 700, color: 'var(--text)',
}}>
{selectedWaiter.avatar_url
? <img src={selectedWaiter.avatar_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: initials
}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>
{selectedWaiter.full_name || selectedWaiter.nickname}
</div>
{selectedWaiter.nickname && selectedWaiter.full_name && (
<div style={{ fontSize: 12, color: 'var(--muted)' }}>{selectedWaiter.nickname}</div>
)}
</div>
<button
onClick={() => { setSelectedWaiter(null); setError('') }}
style={{ background: 'none', border: 'none', color: 'var(--muted)', cursor: 'pointer', fontSize: 13, padding: '4px 8px' }}
>
Αλλαγή
</button>
</div>
<p style={{ textAlign: 'center', color: 'var(--muted)', fontSize: 13, marginBottom: 12 }}>Εισάγετε PIN</p>
<PinPad onSubmit={handlePin} loading={loading} />
{error && <p className="error-msg">{error}</p>}
</div>
</div>
)
}
+31
View File
@@ -0,0 +1,31 @@
import client from '../api/client'
import { useState } from 'react'
export default function OfflinePage() {
const [checking, setChecking] = useState(false)
async function retry() {
setChecking(true)
try {
await client.get('/api/system/health')
window.location.href = '/'
} catch {
setChecking(false)
}
}
return (
<div className="page page--centered">
<div style={{ textAlign: 'center', maxWidth: 300 }}>
<p style={{ fontSize: 48, marginBottom: 16 }}>📡</p>
<h2 style={{ color: '#e2e8f0', marginBottom: 8 }}>Δεν υπάρχει σύνδεση</h2>
<p style={{ color: '#64748b', marginBottom: 32 }}>
Δεν είναι δυνατή η επικοινωνία με το σύστημα. Ελέγξτε τη σύνδεση WiFi.
</p>
<button className="btn btn--primary btn--lg" onClick={retry} disabled={checking}>
{checking ? 'Έλεγχος…' : 'Επανάληψη'}
</button>
</div>
</div>
)
}
+345
View File
@@ -0,0 +1,345 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import useTableViewStore from '../store/tableViewStore'
import useThemeStore from '../store/themeStore'
// ─── Tab definitions (stub future tabs here) ──────────────────────────────────
const TABS = [
{ key: 'layout', label: 'Εμφάνιση' },
{ key: 'favorites', label: 'Αγαπημένα', disabled: true },
]
// ─── Density option data ──────────────────────────────────────────────────────
const DENSITY_OPTIONS = [
{
key: '1x1',
label: '1×1',
desc: '4 ανά σειρά — μόνο όνομα',
preview: <Grid4 />,
},
{
key: '2x1',
label: '2×1',
desc: '2 ανά σειρά — όνομα + κατάσταση',
preview: <Grid2H />,
},
{
key: '2x2',
label: '2×2',
desc: '2 ανά σειρά — συμπαγής κάρτα',
preview: <Grid2 />,
},
{
key: '4x1',
label: '4×1',
desc: '1 ανά σειρά — οριζόντια λίστα',
preview: <Grid1H />,
},
{
key: '4x2',
label: '4×2',
desc: '1 ανά σειρά — πλήρης κάρτα',
preview: <Grid1 />,
},
{
key: '4x3',
label: '4×3',
desc: '1 ανά σειρά — κάρτα με λίστα παραγγελίας',
preview: <Grid1Detail />,
},
]
// ─── Mini grid preview SVGs ───────────────────────────────────────────────────
function Grid4() {
return (
<svg viewBox="0 0 56 48" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ width: '100%', height: '100%' }}>
{[0,1,2,3].map(i => (
<rect key={i} x={2 + i * 13} y="4" width="11" height="13" rx="2" fill="currentColor" opacity="0.9"/>
))}
{[0,1,2,3].map(i => (
<rect key={i+4} x={2 + i * 13} y="20" width="11" height="13" rx="2" fill="currentColor" opacity="0.55"/>
))}
{[0,1,2,3].map(i => (
<rect key={i+8} x={2 + i * 13} y="36" width="11" height="13" rx="2" fill="currentColor" opacity="0.25"/>
))}
</svg>
)
}
function Grid2H() {
return (
<svg viewBox="0 0 56 48" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ width: '100%', height: '100%' }}>
{[0,1].map(i => (
<rect key={i} x={2 + i * 27} y="4" width="25" height="11" rx="2" fill="currentColor" opacity="0.9"/>
))}
{[0,1].map(i => (
<rect key={i+2} x={2 + i * 27} y="19" width="25" height="11" rx="2" fill="currentColor" opacity="0.55"/>
))}
{[0,1].map(i => (
<rect key={i+4} x={2 + i * 27} y="34" width="25" height="11" rx="2" fill="currentColor" opacity="0.25"/>
))}
</svg>
)
}
function Grid2() {
return (
<svg viewBox="0 0 56 48" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ width: '100%', height: '100%' }}>
<rect x="2" y="4" width="24" height="18" rx="2" fill="currentColor" opacity="0.9"/>
<rect x="30" y="4" width="24" height="18" rx="2" fill="currentColor" opacity="0.9"/>
<rect x="2" y="26" width="24" height="18" rx="2" fill="currentColor" opacity="0.45"/>
<rect x="30" y="26" width="24" height="18" rx="2" fill="currentColor" opacity="0.45"/>
</svg>
)
}
function Grid1H() {
return (
<svg viewBox="0 0 56 48" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ width: '100%', height: '100%' }}>
<rect x="2" y="4" width="52" height="11" rx="2" fill="currentColor" opacity="0.9"/>
<rect x="2" y="19" width="52" height="11" rx="2" fill="currentColor" opacity="0.55"/>
<rect x="2" y="34" width="52" height="11" rx="2" fill="currentColor" opacity="0.25"/>
</svg>
)
}
function Grid1() {
return (
<svg viewBox="0 0 56 48" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ width: '100%', height: '100%' }}>
<rect x="2" y="4" width="52" height="18" rx="2" fill="currentColor" opacity="0.9"/>
<rect x="2" y="27" width="52" height="18" rx="2" fill="currentColor" opacity="0.45"/>
</svg>
)
}
function Grid1Detail() {
return (
<svg viewBox="0 0 56 48" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ width: '100%', height: '100%' }}>
<rect x="2" y="4" width="52" height="20" rx="2" fill="currentColor" opacity="0.9"/>
{/* left section lines */}
<rect x="5" y="8" width="14" height="3" rx="1" fill="white" opacity="0.6"/>
<rect x="5" y="13" width="9" height="2" rx="1" fill="white" opacity="0.4"/>
<rect x="5" y="18" width="11" height="2" rx="1" fill="white" opacity="0.4"/>
{/* vertical divider */}
<rect x="22" y="7" width="1" height="14" rx="0.5" fill="white" opacity="0.3"/>
{/* right section lines */}
<rect x="25" y="8" width="24" height="2" rx="1" fill="white" opacity="0.5"/>
<rect x="25" y="12" width="20" height="2" rx="1" fill="white" opacity="0.35"/>
<rect x="25" y="16" width="22" height="2" rx="1" fill="white" opacity="0.25"/>
<rect x="2" y="29" width="52" height="15" rx="2" fill="currentColor" opacity="0.45"/>
</svg>
)
}
// ─── Layout tab ───────────────────────────────────────────────────────────────
function LayoutTab() {
const { density, setDensity } = useTableViewStore()
const { dark, toggle } = useThemeStore()
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 32, padding: '24px 16px' }}>
{/* Card density */}
<section>
<h2 style={sectionTitle}>Κάρτες τραπεζιών</h2>
<p style={sectionSub}>Επίλεξε πόσα στοιχεία εμφανίζονται σε κάθε κάρτα.</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 14 }}>
{DENSITY_OPTIONS.map(opt => {
const active = density === opt.key
return (
<button
key={opt.key}
onClick={() => setDensity(opt.key)}
style={{
display: 'flex', alignItems: 'center', gap: 16,
padding: '14px 16px',
borderRadius: 14,
border: `2px solid ${active ? 'var(--accent)' : 'var(--border)'}`,
background: active ? 'var(--accent)' + '18' : 'var(--bg2)',
cursor: 'pointer',
textAlign: 'left',
transition: 'border-color 0.12s, background 0.12s',
}}
>
{/* Mini preview */}
<div style={{
width: 56, height: 48, flexShrink: 0,
color: active ? 'var(--accent)' : 'var(--muted)',
transition: 'color 0.12s',
}}>
{opt.preview}
</div>
{/* Text */}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{
fontSize: 15, fontWeight: 700,
color: active ? 'var(--accent)' : 'var(--text)',
marginBottom: 2,
}}>
{opt.label}
</div>
<div style={{ fontSize: 13, color: 'var(--muted)', lineHeight: 1.4 }}>
{opt.desc}
</div>
</div>
{/* Check */}
{active && (
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" style={{ flexShrink: 0, color: 'var(--accent)' }}>
<circle cx="10" cy="10" r="9" stroke="currentColor" strokeWidth="1.5"/>
<path d="M6.5 10l2.5 2.5 4.5-5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
)}
</button>
)
})}
</div>
</section>
{/* Theme */}
<section>
<h2 style={sectionTitle}>Θέμα</h2>
<div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
{[
{ key: false, icon: '☀️', label: 'Φωτεινό' },
{ key: true, icon: '🌙', label: 'Σκοτεινό' },
].map(opt => {
const active = dark === opt.key
return (
<button
key={String(opt.key)}
onClick={() => { if (!active) toggle() }}
style={{
flex: 1,
display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
padding: '18px 12px',
borderRadius: 14,
border: `2px solid ${active ? 'var(--accent)' : 'var(--border)'}`,
background: active ? 'var(--accent)' + '18' : 'var(--bg2)',
cursor: active ? 'default' : 'pointer',
transition: 'border-color 0.12s, background 0.12s',
}}
>
<span style={{ fontSize: 28 }}>{opt.icon}</span>
<span style={{
fontSize: 14, fontWeight: 600,
color: active ? 'var(--accent)' : 'var(--muted)',
}}>{opt.label}</span>
</button>
)
})}
</div>
</section>
</div>
)
}
const sectionTitle = {
fontSize: 13, fontWeight: 700, color: 'var(--muted)',
letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 4,
}
const sectionSub = {
fontSize: 14, color: 'var(--muted)', lineHeight: 1.5,
}
// ─── Favorites stub tab ───────────────────────────────────────────────────────
function FavoritesTab() {
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12, padding: 40, flex: 1 }}>
<span style={{ fontSize: 40 }}>⭐</span>
<p style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)' }}>Σύντομα διαθέσιμο</p>
<p style={{ fontSize: 14, color: 'var(--muted)', textAlign: 'center', lineHeight: 1.5 }}>
Τα αγαπημένα προϊόντα θα εμφανίζονται εδώ για γρήγορη παραγγελία.
</p>
</div>
)
}
// ─── Main page ────────────────────────────────────────────────────────────────
export default function SettingsPage() {
const navigate = useNavigate()
const [activeTab, setActiveTab] = useState('layout')
return (
<div className="page">
{/* Top bar */}
<header className="top-bar">
<button
onClick={() => navigate(-1)}
style={{
display: 'flex', alignItems: 'center', gap: 6,
background: 'none', border: 'none', cursor: 'pointer',
color: 'var(--text)', fontSize: 15, fontWeight: 600,
padding: '0 4px', minHeight: 44, borderRadius: 8,
}}
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
<path d="M12.5 15l-5-5 5-5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
Πίσω
</button>
<span className="top-bar__title" style={{ textAlign: 'center' }}>Ρυθμίσεις</span>
{/* spacer to balance the back button */}
<div style={{ width: 72 }} />
</header>
{/* Tab strip */}
<div style={{
display: 'flex', gap: 0,
borderBottom: '1px solid var(--border)',
background: 'var(--bg2)',
padding: '0 16px',
}}>
{TABS.map(tab => (
<button
key={tab.key}
disabled={tab.disabled}
onClick={() => !tab.disabled && setActiveTab(tab.key)}
style={{
padding: '14px 16px',
background: 'none', border: 'none',
borderBottom: activeTab === tab.key ? '2px solid var(--accent)' : '2px solid transparent',
color: tab.disabled
? 'var(--muted)'
: activeTab === tab.key
? 'var(--accent)'
: 'var(--text)',
fontSize: 14, fontWeight: 600,
cursor: tab.disabled ? 'not-allowed' : 'pointer',
opacity: tab.disabled ? 0.45 : 1,
marginBottom: -1, // overlap the border-bottom
whiteSpace: 'nowrap',
transition: 'color 0.12s',
}}
>
{tab.label}
{tab.disabled && (
<span style={{
marginLeft: 6, fontSize: 10, fontWeight: 700,
background: 'var(--bg3)', color: 'var(--muted)',
borderRadius: 4, padding: '1px 5px',
verticalAlign: 'middle',
}}>σύντομα</span>
)}
</button>
))}
</div>
{/* Tab body */}
<div style={{ flex: 1, overflowY: 'auto', minHeight: 0, overscrollBehavior: 'contain' }}>
{activeTab === 'layout' && <LayoutTab />}
{activeTab === 'favorites' && <FavoritesTab />}
</div>
</div>
)
}
File diff suppressed because it is too large Load Diff
+783
View File
@@ -0,0 +1,783 @@
import { useEffect, useRef, useState, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import TableCard from '../components/TableCard'
import ConnectionBanner from '../components/ConnectionBanner'
import EmergencyBar from '../components/EmergencyBar'
import UserMenu from '../components/UserMenu'
import useAuthStore from '../store/authStore'
import useTableColourStore from '../store/tableColourStore'
import useConnectionStore from '../store/connectionStore'
import useTableViewStore from '../store/tableViewStore'
import client from '../api/client'
import db from '../db/posdb'
import { queueOfflinePayment } from '../services/offlinePayments'
import { useNotifications } from '../context/NotificationContext'
import { FlagsIcon, TransferIcon, MergeIcon, PrintIcon, WaiterIcon } from '../components/Icons'
function fmtPrice(v) { return Number(v || 0).toFixed(2) + ' €' }
// ─── Icons ────────────────────────────────────────────────────────────────────
function FilterIcon({ size = 20 }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
<polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/>
</svg>
)
}
// ─── Notification drawer ──────────────────────────────────────────────────────
function NotificationDrawer({ messages, onClose }) {
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-sheet" onClick={e => e.stopPropagation()} style={{ maxHeight: '80svh' }}>
<div className="modal-handle" />
<h2 className="modal-title" style={{ marginBottom: 16 }}>Ειδοποιήσεις</h2>
{messages.length === 0 && (
<p style={{ textAlign: 'center', color: 'var(--muted)', padding: 24 }}>Δεν υπάρχουν ειδοποιήσεις</p>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 0, overflowY: 'auto', flex: 1 }}>
{messages.map(msg => {
const tableIds = (() => { try { return JSON.parse(msg.table_ids || '[]') } catch { return [] } })()
return (
<div key={msg.id} style={{
padding: '12px 4px', borderBottom: '1px solid var(--border)',
display: 'flex', gap: 12, alignItems: 'flex-start',
opacity: msg._acked ? 0.5 : 1,
}}>
<span style={{ fontSize: 20, flexShrink: 0 }}>📢</span>
<div style={{ flex: 1, minWidth: 0 }}>
{msg.sender_name && (
<div style={{ fontSize: 11, fontWeight: 700, color: '#a5b4fc', marginBottom: 2 }}>{msg.sender_name}</div>
)}
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{msg.body}</div>
{tableIds.length > 0 && (
<div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>Τραπέζι: {tableIds.join(', ')}</div>
)}
<div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>
{new Date(msg.created_at).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })}
</div>
</div>
</div>
)
})}
</div>
<button className="btn btn--secondary" style={{ width: '100%', marginTop: 12 }} onClick={onClose}>Κλείσιμο</button>
</div>
</div>
)
}
// ─── Table quick-view modal (long press) ──────────────────────────────────────
const QUICK_ACTIONS = [
{ Icon: FlagsIcon, label: 'Ενδείξεις Τραπεζιού', key: 'flags', color: '#fac823', iconBg: 'rgba(251,191,36,0.15)' },
{ Icon: TransferIcon, label: 'Μεταφορά', key: 'transfer', color: '#6099db', iconBg: 'rgba(96,165,250,0.15)' },
{ Icon: MergeIcon, label: 'Συγχώνευση', key: 'merge', color: '#6099db', iconBg: 'rgba(96,165,250,0.15)' },
{ Icon: PrintIcon, label: 'Εκτύπωση Σύνοψης', key: 'print_synopsis', color: '#cbd5e1', iconBg: 'rgba(148,163,184,0.15)' },
{ Icon: WaiterIcon, label: 'Ανάθεση Σερβιτόρου', key: 'assign_waiter', color: '#39b861', iconBg: 'rgba(34,197,94,0.15)' },
]
function TableQuickModal({ table, order, flags, onClose, onNavigate, onAction }) {
const tableName = table.label || `T${table.number}`
const activeItems = order?.items?.filter(i => i.status === 'active') || []
const total = activeItems.reduce((s, i) => s + i.unit_price * i.quantity, 0)
const paid = order?.payments?.reduce((s, p) => s + p.amount, 0) || 0
const due = Math.max(0, total - paid)
const statusLabel = {
open: 'Ανοιχτό', partially_paid: 'Μερικώς πληρωμένο', paid: 'Πληρωμένο',
}[order?.status] || 'Ελεύθερο'
return (
<div className="modal-overlay" onClick={onClose}>
<div style={{ width: '100%', maxWidth: 480, margin: '0 auto' }} onClick={e => e.stopPropagation()}>
<div style={{ background: 'var(--bg2)', borderRadius: '16px 16px 0 0', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
<div className="modal-handle" style={{ marginBottom: 12 }} />
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
<span style={{ fontSize: 22, fontWeight: 700, color: 'var(--text)' }}>{tableName}</span>
<span style={{ fontSize: 13, color: 'var(--muted)' }}>{statusLabel}</span>
</div>
{order ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14 }}>
<span style={{ color: 'var(--muted)' }}>Σύνολο</span>
<span style={{ fontWeight: 600, color: 'var(--text)' }}>{fmtPrice(total)}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14 }}>
<span style={{ color: 'var(--muted)' }}>Πληρωμένο</span>
<span style={{ fontWeight: 600, color: '#22c55e' }}>{fmtPrice(paid)}</span>
</div>
{due > 0 && (
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14 }}>
<span style={{ color: 'var(--muted)' }}>Υπόλοιπο</span>
<span style={{ fontWeight: 700, color: '#f59e0b' }}>{fmtPrice(due)}</span>
</div>
)}
</div>
) : (
<p style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 12 }}>Δεν υπάρχει ενεργή παραγγελία</p>
)}
{flags.length > 0 && (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
{flags.map(f => (
<div key={f.id} style={{
display: 'flex', alignItems: 'center', gap: 6,
background: (f.color || '#6295F3') + '22',
border: `1px solid ${f.color || '#6295F3'}`,
borderRadius: 20, padding: '4px 10px',
}}>
<span style={{ fontSize: 14 }}>{f.emoji || '🏷️'}</span>
<span style={{ fontSize: 12, fontWeight: 600, color: f.color || '#6295F3' }}>{f.name}</span>
</div>
))}
</div>
)}
<button className="btn btn--primary" style={{ width: '100%', marginTop: 14 }} onClick={() => { onClose(); onNavigate() }}>
Άνοιγμα τραπεζιού
</button>
</div>
<div style={{ background: 'var(--bg2)', borderRadius: '0 0 16px 16px', padding: '8px 20px 24px', borderTop: '2px solid var(--border)' }}>
<p style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', letterSpacing: 1, marginBottom: 8, marginTop: 8 }}>ACTIONS</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
{QUICK_ACTIONS.map((a, i) => {
const disabled = !order && a.key !== 'flags'
return (
<button key={a.key} disabled={disabled} onClick={() => { onClose(); onAction(a.key) }} style={{
display: 'flex', alignItems: 'center', gap: 14,
padding: '12px 0', background: 'none', border: 'none',
borderBottom: i < QUICK_ACTIONS.length - 1 ? '1px solid var(--border)' : 'none',
cursor: disabled ? 'not-allowed' : 'pointer',
opacity: disabled ? 0.35 : 1, textAlign: 'left',
}}>
<span style={{ width: 36, height: 36, borderRadius: 9, flexShrink: 0, background: a.iconBg, display: 'flex', alignItems: 'center', justifyContent: 'center', color: a.color }}>
<a.Icon width="18" height="18" />
</span>
<span style={{ fontSize: 15, fontWeight: 600, color: a.color }}>{a.label}</span>
{!disabled && <span style={{ marginLeft: 'auto', color: 'var(--muted)', fontSize: 18 }}>›</span>}
</button>
)
})}
</div>
</div>
</div>
</div>
)
}
// ─── Emergency payment modal ──────────────────────────────────────────────────
function EmergencyPayModal({ table, order, onClose, onPay }) {
const [paying, setPaying] = useState(false)
const activeItems = order?.items?.filter(i => i.status === 'active') || []
const total = activeItems.reduce((s, i) => s + (i.unit_price || 0) * (i.quantity || 1), 0)
async function handlePay() {
setPaying(true)
await onPay(order.id, activeItems.map(i => i.id), 'cash')
onClose()
}
return (
<div className="modal-overlay" onClick={onClose}>
<div style={{ width: '100%', maxWidth: 400, margin: '0 auto' }} onClick={e => e.stopPropagation()}>
<div className="modal-sheet">
<div className="modal-handle" />
<div style={{ textAlign: 'center', marginBottom: 16 }}>
<div style={{ fontSize: 32, marginBottom: 8 }}>🚨</div>
<p style={{ fontSize: 18, fontWeight: 700, color: '#ef4444' }}>ΕΚΤΑΚΤΗ ΠΛΗΡΩΜΗ</p>
<p style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4 }}>Τραπέζι: <strong>{table.label || `T${table.number}`}</strong></p>
</div>
<div style={{ background: 'var(--bg3)', borderRadius: 12, padding: '12px 16px', marginBottom: 20 }}>
<p style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 8 }}>Ενεργά αντικείμενα:</p>
{activeItems.length === 0
? <p style={{ fontSize: 13, color: 'var(--muted)', fontStyle: 'italic' }}>Δεν υπάρχουν δεδομένα (offline snapshot)</p>
: activeItems.map(item => (
<div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, marginBottom: 4 }}>
<span style={{ color: 'var(--text)' }}>{item.product?.name || `#${item.product_id}`} ×{item.quantity}</span>
<span style={{ color: 'var(--text)', fontWeight: 600 }}>{((item.unit_price || 0) * (item.quantity || 1)).toFixed(2)} €</span>
</div>
))
}
<div style={{ borderTop: '1px solid var(--border)', marginTop: 10, paddingTop: 10, display: 'flex', justifyContent: 'space-between', fontWeight: 700, fontSize: 16 }}>
<span>Σύνολο</span>
<span style={{ color: '#ef4444' }}>{total.toFixed(2)} €</span>
</div>
</div>
{total === 0
? <p style={{ fontSize: 13, color: '#ef4444', marginBottom: 16, lineHeight: 1.5, fontWeight: 600 }}>
Δεν είναι δυνατή η πληρωμή χωρίς offline δεδομένα. Άνοιξε το τραπέζι ενώ ο server ήταν online.
</p>
: <p style={{ fontSize: 12, color: '#f59e0b', marginBottom: 16, lineHeight: 1.5 }}>
⚠️ Μόνο μετρητά σε κατάσταση έκτακτης ανάγκης. Η πληρωμή συγχρονίζεται μόλις αποκατασταθεί η σύνδεση.
</p>
}
<div style={{ display: 'flex', gap: 10 }}>
<button className="btn btn--secondary" style={{ flex: 1 }} onClick={onClose}>Ακύρωση</button>
<button
style={{ flex: 1, height: 44, borderRadius: 12, border: 'none', background: total === 0 ? '#64748b' : '#dc2626', color: '#fff', fontSize: 15, fontWeight: 700, cursor: (paying || total === 0) ? 'not-allowed' : 'pointer', opacity: (paying || total === 0) ? 0.5 : 1 }}
onClick={handlePay} disabled={paying || total === 0}
>
{paying ? '⟳ Καταχώρηση…' : '✓ Πληρωμή'}
</button>
</div>
</div>
</div>
</div>
)
}
// ─── Filters modal ────────────────────────────────────────────────────────────
function FiltersModal({ groups, onClose }) {
const {
ownerFilter, statusFilter, zoneFilter,
setOwnerFilter, setStatusFilter, setZoneFilter,
clearFilters, setActiveZoneTab,
} = useTableViewStore()
function toggleZone(id) {
const next = zoneFilter.includes(id)
? zoneFilter.filter(z => z !== id)
: [...zoneFilter, id]
setZoneFilter(next)
// if we remove a zone that is the active tab, reset to 'all'
if (!next.length) setActiveZoneTab('all')
}
const hasActiveFilters = ownerFilter !== 'all' || statusFilter !== 'all' || zoneFilter.length > 0
return (
<div className="modal-overlay" onClick={onClose} style={{ alignItems: 'flex-end' }}>
<div
className="modal-sheet"
onClick={e => e.stopPropagation()}
style={{ borderRadius: '20px 20px 0 0', paddingBottom: 40, gap: 20 }}
>
<div className="modal-handle" />
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span style={{ fontSize: 17, fontWeight: 700, color: 'var(--text)' }}>Φίλτρα</span>
{hasActiveFilters && (
<button
onClick={() => { clearFilters(); onClose() }}
style={{ fontSize: 13, fontWeight: 600, color: 'var(--danger)', background: 'none', border: 'none', cursor: 'pointer', padding: '4px 8px' }}
>
Καθαρισμός
</button>
)}
</div>
{/* Owner: ALL | MINE */}
<div>
<p style={sectionLabel}>Ανάθεση</p>
<div style={segmentedWrap}>
{[['all', 'Όλα'], ['mine', 'Δικά μου']].map(([key, lbl]) => (
<button key={key} onClick={() => setOwnerFilter(key)} style={segBtn(ownerFilter === key)}>{lbl}</button>
))}
</div>
</div>
{/* Status: ALL | FREE | OPEN | PAID */}
<div>
<p style={sectionLabel}>Κατάσταση</p>
<div style={{ ...segmentedWrap, display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
{[['all', 'Όλα'], ['free', 'Ελεύθερα'], ['open', 'Ανοιχτά'], ['paid', 'Πληρωμένα']].map(([key, lbl]) => (
<button key={key} onClick={() => setStatusFilter(key)} style={{ ...segBtn(statusFilter === key), borderRadius: 10 }}>{lbl}</button>
))}
</div>
</div>
{/* Zones: multi-select, one segmented container per zone */}
{groups.length > 0 && (
<div>
<p style={sectionLabel}>Ζώνες {zoneFilter.length > 0 ? `(${zoneFilter.length} επιλεγμένες)` : ''}</p>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
{groups.map(g => {
const active = zoneFilter.includes(g.id)
return (
<div key={g.id} style={segmentedWrap}>
<button
onClick={() => toggleZone(g.id)}
style={{
...segBtn(active),
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
}}
>
{g.color && (
<span style={{
width: 8, height: 8, borderRadius: '50%',
background: active ? 'currentColor' : g.color,
flexShrink: 0, opacity: active ? 0.9 : 1,
}} />
)}
{g.name}
</button>
</div>
)
})}
</div>
</div>
)}
<button className="btn btn--secondary" style={{ width: '100%' }} onClick={onClose}>Εντάξει</button>
</div>
</div>
)
}
const sectionLabel = { fontSize: 11, fontWeight: 700, color: 'var(--muted)', letterSpacing: 0.8, textTransform: 'uppercase', marginBottom: 8 }
const segmentedWrap = { display: 'flex', gap: 6, background: 'var(--bg3)', borderRadius: 12, padding: 4 }
function segBtn(active) {
return {
flex: 1, padding: '9px 8px', borderRadius: 9, border: 'none',
cursor: 'pointer', fontWeight: 600, fontSize: 14,
background: active ? 'var(--accent)' : 'transparent',
color: active ? 'var(--accent-fg)' : 'var(--muted)',
transition: 'background 0.12s',
}
}
// ─── Main page ────────────────────────────────────────────────────────────────
export default function TableListPage() {
const { user } = useAuthStore()
const { status: connStatus } = useConnectionStore()
const isEmergency = connStatus === 'emergency'
const [tables, setTables] = useState([])
const [groups, setGroups] = useState([])
const [orders, setOrders] = useState([])
const [flagDefs, setFlagDefs] = useState([])
const [flagAssignments, setFlagAssignments] = useState([])
const [waiters, setWaiters] = useState([]) // waiter objects for avatar lookup
const [offline, setOffline] = useState(false)
const [showNotifs, setShowNotifs] = useState(false)
const [showFilters, setShowFilters] = useState(false)
const [quickModal, setQuickModal] = useState(null)
const [emergencyPayModal, setEmergencyPayModal] = useState(null)
const [localPaidOrderIds, setLocalPaidOrderIds] = useState(new Set())
// pull-to-refresh state
const [pulling, setPulling] = useState(false)
const [pullY, setPullY] = useState(0)
const [refreshing, setRefreshing] = useState(false)
const pullStart = useRef(null)
const scrollRef = useRef(null)
const PULL_THRESHOLD = 72
const navigate = useNavigate()
const filterBtnRef = useRef(null)
const { unreadCount, recentMessages, fetchRecent } = useNotifications() || {}
const loadFromBackend = useTableColourStore(s => s.loadFromBackend)
const {
density, ownerFilter, statusFilter, zoneFilter, activeZoneTab, setActiveZoneTab,
} = useTableViewStore()
// ── Load from IndexedDB when offline ──────────────────────────────────────
const loadFromDB = useCallback(async () => {
const [dbTables, dbOrders] = await Promise.all([db.tables.toArray(), db.orders.toArray()])
setTables(dbTables.filter(t => t.is_active !== false))
setOrders(dbOrders)
setOffline(true)
}, [])
useEffect(() => { if (isEmergency) loadFromDB() }, [isEmergency])
useEffect(() => {
const handler = () => setOffline(true)
window.addEventListener('backend-offline', handler)
return () => window.removeEventListener('backend-offline', handler)
}, [])
useEffect(() => {
const handler = () => load()
window.addEventListener('sse-reconnected', handler)
return () => window.removeEventListener('sse-reconnected', handler)
}, [])
useEffect(() => { if (connStatus === 'online') setOffline(false) }, [connStatus])
async function load() {
try {
const [tablesRes, ordersRes, groupsRes, flagDefsRes, flagAssignRes, settingsRes, waitersRes] = await Promise.all([
client.get('/api/tables/'),
client.get('/api/orders/active'),
client.get('/api/tables/groups'),
client.get('/api/flags/defs'),
client.get('/api/flags/assignments'),
client.get('/api/settings/'),
client.get('/api/waiters/on-shift'),
])
setTables(tablesRes.data)
const fullOrders = await Promise.all(
ordersRes.data.map(o =>
client.get(`/api/orders/${o.id}`)
.then(r => ({ ...r.data, waiter_ids: r.data.waiters?.map(w => w.waiter_id) ?? o.waiter_ids ?? [] }))
.catch(() => o)
)
)
setOrders(fullOrders)
setGroups(groupsRes.data)
setFlagDefs(flagDefsRes.data)
setFlagAssignments(flagAssignRes.data)
setWaiters(waitersRes.data)
const raw = settingsRes.data?.['ui.table_colours']?.value
if (raw) loadFromBackend(raw)
setOffline(false)
} catch {}
}
useEffect(() => { load() }, [])
// ── SSE live updates ───────────────────────────────────────────────────────
useEffect(() => {
if (isEmergency) return
function onSSE(e) {
const { type, data } = e.detail
if (type === 'order_updated' || type === 'order_paid') {
client.get(`/api/orders/${data.order_id}`)
.then(r => {
const full = { ...r.data, waiter_ids: r.data.waiters?.map(w => w.waiter_id) ?? [] }
setOrders(prev => {
const exists = prev.find(o => o.id === data.order_id)
return exists ? prev.map(o => o.id === data.order_id ? full : o) : [...prev, full]
})
})
.catch(() => {
setOrders(prev => {
const existing = prev.find(o => o.id === data.order_id)
if (existing) return prev.map(o => o.id === data.order_id ? { ...o, status: data.status, table_id: data.table_id } : o)
return [...prev, { id: data.order_id, table_id: data.table_id, status: data.status, waiter_ids: [] }]
})
})
} else if (type === 'order_closed') {
setOrders(prev => prev.filter(o => o.id !== data.order_id))
} else if (type === 'table_flags_changed') {
client.get('/api/flags/assignments').then(r => setFlagAssignments(r.data)).catch(() => {})
} else if (type === 'table_list_changed') {
client.get('/api/tables/').then(r => setTables(r.data)).catch(() => {})
}
}
window.addEventListener('sse-event', onSSE)
return () => window.removeEventListener('sse-event', onSSE)
}, [isEmergency])
// ── Emergency payment ──────────────────────────────────────────────────────
async function handleEmergencyPay(orderId, itemIds, paymentMethod) {
await queueOfflinePayment({ orderId, itemIds, paymentMethod })
setLocalPaidOrderIds(prev => new Set([...prev, orderId]))
setOrders(prev => prev.map(o => o.id === orderId ? { ...o, status: 'paid' } : o))
await db.orders.where('id').equals(orderId).modify({ status: 'paid' })
}
// ── Derived maps ───────────────────────────────────────────────────────────
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)
})
const waiterMap = Object.fromEntries(waiters.map(w => [w.id, w]))
function getOrder(tableId) { return orders.find(o => o.table_id === tableId) }
function isMyOrder(order) { return !!(order && user && order.waiter_ids?.includes(user.id)) }
function getOrderWaiters(order) {
if (!order) return []
return (order.waiter_ids || []).map(id => waiterMap[id]).filter(Boolean)
}
// ── Filtering logic ────────────────────────────────────────────────────────
// Zones visible in top bar = those allowed by zoneFilter (or all if empty)
const allowedZoneIds = zoneFilter.length > 0 ? new Set(zoneFilter) : null
// visibleGroups = groups shown in the top bar
const visibleGroups = groups.filter(g => !allowedZoneIds || allowedZoneIds.has(g.id))
// Validate activeZoneTab against current allowedZoneIds
// If the active tab is no longer visible, reset to 'all'
const effectiveZoneTab = (
activeZoneTab === 'all' ||
visibleGroups.some(g => g.id === activeZoneTab)
) ? activeZoneTab : 'all'
const filtered = tables.filter(t => {
const order = getOrder(t.id)
// Status filter
if (statusFilter === 'free' && order) return false
if (statusFilter === 'open' && (!order || order.status === 'paid' || order.status === 'partially_paid')) return false
if (statusFilter === 'paid' && order?.status !== 'paid' && order?.status !== 'partially_paid') return false
// Owner filter
if (ownerFilter === 'mine' && !isMyOrder(order)) return false
// Zone filter from modal (multi-select restricts which zones are allowed)
if (allowedZoneIds && !allowedZoneIds.has(t.group_id ?? 'none')) return false
// Active zone tab (secondary, single-select within allowed)
if (effectiveZoneTab !== 'all' && t.group_id !== effectiveZoneTab) return false
return true
})
// ── Pull-to-refresh handlers ───────────────────────────────────────────────
function onPullTouchStart(e) {
if (scrollRef.current?.scrollTop > 0) return
pullStart.current = e.touches[0].clientY
}
function onPullTouchMove(e) {
if (pullStart.current === null) return
const dy = e.touches[0].clientY - pullStart.current
if (dy > 0 && scrollRef.current?.scrollTop <= 0) {
e.preventDefault()
setPulling(true)
setPullY(Math.min(dy, PULL_THRESHOLD * 1.5))
}
}
async function onPullTouchEnd() {
if (!pulling) return
if (pullY >= PULL_THRESHOLD) {
setRefreshing(true)
await load()
setRefreshing(false)
}
setPulling(false)
setPullY(0)
pullStart.current = null
}
// ── Grid columns per density ───────────────────────────────────────────────
const gridCols = {
'1x1': 'repeat(4, 1fr)',
'2x1': 'repeat(2, 1fr)',
'2x2': 'repeat(2, 1fr)',
'4x1': '1fr',
'4x2': '1fr',
'4x3': '1fr',
}[density] || 'repeat(2, 1fr)'
const hasActiveFilters = ownerFilter !== 'all' || statusFilter !== 'all' || zoneFilter.length > 0
function handleQuickAction(tableId, actionKey) {
navigate(`/tables/${tableId}?action=${actionKey}`)
}
return (
<div className="page">
<header className="top-bar">
<span className="top-bar__title">Τραπέζια</span>
<button
onClick={() => { setShowNotifs(true); fetchRecent?.() }}
style={{
position: 'relative', background: 'none', border: 'none',
color: 'var(--text)', fontSize: 22, cursor: 'pointer',
minWidth: 44, minHeight: 44, borderRadius: 8,
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
}}
>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
<path d="M19.3399 14.49L18.3399 12.83C18.1299 12.46 17.9399 11.76 17.9399 11.35V8.82C17.9399 6.47 16.5599 4.44 14.5699 3.49C14.0499 2.57 13.0899 2 11.9899 2C10.8999 2 9.91994 2.59 9.39994 3.52C7.44994 4.49 6.09994 6.5 6.09994 8.82V11.35C6.09994 11.76 5.90994 12.46 5.69994 12.82L4.68994 14.49C4.28994 15.16 4.19994 15.9 4.44994 16.58C4.68994 17.25 5.25994 17.77 5.99994 18.02C7.93994 18.68 9.97994 19 12.0199 19C14.0599 19 16.0999 18.68 18.0399 18.03C18.7399 17.8 19.2799 17.27 19.5399 16.58C19.7999 15.89 19.7299 15.13 19.3399 14.49Z" fill="currentColor"/>
<path d="M14.8297 20.01C14.4097 21.17 13.2997 22 11.9997 22C11.2097 22 10.4297 21.68 9.87969 21.11C9.55969 20.81 9.31969 20.41 9.17969 20C9.30969 20.02 9.43969 20.03 9.57969 20.05C9.80969 20.08 10.0497 20.11 10.2897 20.13C10.8597 20.18 11.4397 20.21 12.0197 20.21C12.5897 20.21 13.1597 20.18 13.7197 20.13C13.9297 20.11 14.1397 20.1 14.3397 20.07C14.4997 20.05 14.6597 20.03 14.8297 20.01Z" fill="currentColor"/>
</svg>
{(unreadCount || 0) > 0 && (
<span style={{
position: 'absolute', top: 6, right: 6,
background: '#ef4444', color: 'white', fontSize: 10, fontWeight: 700,
borderRadius: '50%', width: 16, height: 16,
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{unreadCount > 9 ? '9+' : unreadCount}
</span>
)}
</button>
<UserMenu />
</header>
{isEmergency ? <EmergencyBar /> : (offline && <ConnectionBanner />)}
{/* ── Zone tab bar ─────────────────────────────────────────────────────── */}
<div style={{
display: 'flex', alignItems: 'center', gap: 6,
padding: '10px 12px',
background: 'var(--bg)',
borderBottom: '1px solid var(--border)',
overflowX: 'auto', scrollbarWidth: 'none',
}}>
{/* ALL tab */}
<ZoneTab
label="Όλα"
active={effectiveZoneTab === 'all'}
onClick={() => setActiveZoneTab('all')}
/>
{/* Per-zone tabs */}
{visibleGroups.map(g => (
<ZoneTab
key={g.id}
label={g.name}
color={g.color}
active={effectiveZoneTab === g.id}
onClick={() => setActiveZoneTab(effectiveZoneTab === g.id ? 'all' : g.id)}
/>
))}
</div>
{/* ── Table grid ───────────────────────────────────────────────────────── */}
<div
ref={scrollRef}
style={{ flex: 1, overflowY: 'auto', minHeight: 0, overscrollBehavior: 'contain' }}
onTouchStart={onPullTouchStart}
onTouchMove={onPullTouchMove}
onTouchEnd={onPullTouchEnd}
>
{/* Pull-to-refresh indicator */}
{(pulling || refreshing) && (
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'center',
height: Math.min(pullY, PULL_THRESHOLD),
color: 'var(--muted)', fontSize: 13, fontWeight: 600,
overflow: 'hidden', transition: pulling ? 'none' : 'height 0.2s',
}}>
{refreshing ? '⟳ Ανανέωση…' : pullY >= PULL_THRESHOLD ? '↑ Αφήστε για ανανέωση' : '↓ Τραβήξτε για ανανέωση'}
</div>
)}
<div style={{
display: 'grid',
gridTemplateColumns: gridCols,
gap: density === '1x1' ? 8 : 10,
padding: '12px 12px 88px',
alignContent: 'start',
}}>
{filtered.map(t => {
const order = getOrder(t.id)
const tableFlags = tableFlagsMap[t.id] || []
const grp = groups.find(g => g.id === t.group_id)
const alreadyPaidLocally = order && localPaidOrderIds.has(order.id)
const orderWaiters = getOrderWaiters(order)
function handleClick() {
if (isEmergency) {
if (order && !alreadyPaidLocally && order.status !== 'paid' && order.status !== 'closed') {
setEmergencyPayModal({ table: t, order })
}
return
}
const destination = order ? `/tables/${t.id}` : `/tables/${t.id}/add?new=1`
navigate(destination)
}
return (
<TableCard
key={t.id}
table={t}
order={alreadyPaidLocally ? { ...order, status: 'paid' } : order}
isMine={isMyOrder(order)}
flags={tableFlags}
groupName={grp?.name || ''}
waiterObjects={orderWaiters}
density={density}
onClick={handleClick}
onLongPress={isEmergency ? undefined : () => setQuickModal({ table: t, order, flags: tableFlags })}
/>
)
})}
</div>
</div>
{/* ── Filter FAB ───────────────────────────────────────────────────────── */}
<button
ref={filterBtnRef}
onClick={() => setShowFilters(true)}
style={{
position: 'fixed', bottom: 24, right: 24,
width: 52, height: 52, borderRadius: '50%', border: 'none',
background: hasActiveFilters ? '#ea6c00' : '#f97316',
color: '#fff',
cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
boxShadow: '0 4px 16px rgba(0,0,0,0.35), 0 2px 6px rgba(0,0,0,0.2)',
zIndex: 40,
transition: 'background 0.12s',
}}
>
<FilterIcon size={20} />
{hasActiveFilters && (
<span style={{
position: 'absolute', top: 0, right: 0,
background: '#ef4444', color: '#fff',
fontSize: 9, fontWeight: 800,
borderRadius: '50%', width: 16, height: 16,
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{(ownerFilter !== 'all' ? 1 : 0) + (statusFilter !== 'all' ? 1 : 0) + (zoneFilter.length > 0 ? 1 : 0)}
</span>
)}
</button>
{/* ── Modals ────────────────────────────────────────────────────────────── */}
{showNotifs && (
<NotificationDrawer messages={recentMessages || []} onClose={() => setShowNotifs(false)} />
)}
{showFilters && (
<FiltersModal groups={groups} onClose={() => setShowFilters(false)} anchorRef={filterBtnRef} />
)}
{quickModal && (
<TableQuickModal
table={quickModal.table}
order={quickModal.order}
flags={quickModal.flags}
onClose={() => setQuickModal(null)}
onNavigate={() => navigate(`/tables/${quickModal.table.id}`)}
onAction={(key) => handleQuickAction(quickModal.table.id, key)}
/>
)}
{emergencyPayModal && (
<EmergencyPayModal
table={emergencyPayModal.table}
order={emergencyPayModal.order}
onClose={() => setEmergencyPayModal(null)}
onPay={handleEmergencyPay}
/>
)}
</div>
)
}
// ─── Zone tab pill ────────────────────────────────────────────────────────────
function ZoneTab({ label, color, active, onClick }) {
return (
<button
onClick={onClick}
style={{
display: 'flex', alignItems: 'center', gap: 6,
padding: '7px 12px', borderRadius: 20, border: 'none',
cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0,
fontWeight: 600, fontSize: 13,
background: active ? 'var(--accent)' : 'var(--bg3)',
color: active ? 'var(--accent-fg)' : 'var(--muted)',
transition: 'background 0.12s, color 0.12s',
}}
>
{color && (
<span style={{
width: 8, height: 8, borderRadius: '50%',
background: color, flexShrink: 0,
opacity: active ? 1 : 0.7,
}} />
)}
{label}
</button>
)
}