feat(manager): the setup wizard and the shell on v2; all of src on the v2 rules (platform-v2 step 6.14b)

- setup wizard (src/pages/setup): welcome (pick the language: the wizard switches at once), the owner's account, the venue
  (kind, name, staff language, time zone), an optional lock-screen PIN, finish -> sign in; English and Greek
- shell (src/shell): AppLayout (license banner in both languages, header, lock button, idle lock / sign-out), Sidebar on a
  new 'nav' token set in @xenia/ui (light + dark), ProfileDialog (name, username, password, 4-6 digit PIN), licenseContext;
  App.jsx loads the session and the setup state with react-query (no setState in effects); the header's dead search box gone
- Management -> Tables -> List (src/pages/tables, was TablesConfigTab): zones as tabs (drag to reorder), zone name / prefix /
  colour, add many numbered on, a table's name (6 chars) / zone / seats, twice-used names flagged, off / on / delete,
  pick several to move, rename in a series or delete (says how many failed)
- the old src/ui kit, layouts/, components/Sidebar + EditProfileModal, the 'primary' palette and the .btn/.card/.input classes deleted;
  NotificationBell / UserMenuButton on tokens; @xenia/ui: nav tokens, 'scrim' in the Tailwind preset
- v2.json paths = src (the guards cover all of it); npm run lint = eslint src; argsIgnorePattern for components in JSX
- tests: shell.test.mjs (3), e2e setup.mjs (new: a fresh install through the wizard in Greek to the overview, in run-all),
  manager.mjs 'tables list' (zone, 3 tables, rename series, profile PIN, rail tokens)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 20:01:23 +02:00
co-authored by Claude Opus 5.5
parent f6fcfb7736
commit 294b769850
40 changed files with 1680 additions and 2766 deletions
@@ -3,7 +3,7 @@
import { useState } from 'react'
import { useTranslation } from '@xenia/i18n'
import FloorPlansTab from '../floor/FloorPlansTab'
import TablesConfigTab from '../TablesConfigTab'
import TablesListTab from '../tables/TablesListTab'
const TABS = ['list', 'floor']
@@ -22,7 +22,7 @@ export default function TablesConfigPage() {
))}
</div>
<div className="flex-1 min-h-0 overflow-y-auto">
{tab === 'list' ? <TablesConfigTab /> : <FloorPlansTab />}
{tab === 'list' ? <TablesListTab /> : <FloorPlansTab />}
</div>
</div>
)
-542
View File
@@ -1,542 +0,0 @@
import { useState, useEffect, useRef } from 'react'
import { LANGUAGE_NAMES, useTranslation } from '@xenia/i18n'
import { browserTimeZone, timeZones } from './Settings/sections/timeZones'
import { useNavigate } from 'react-router-dom'
import {
ArrowRight, User, Mail, Lock, Building2, Coffee,
UtensilsCrossed, Beer, ShoppingBag, CheckCircle2, ChevronRight, Hash,
} from 'lucide-react'
import client from '../api/client'
import Button from '../ui/Button'
import { LabelledInput } from '../ui/Input'
// ─── Step indicator ───────────────────────────────────────────────────────────
function StepDots({ total, current }) {
return (
<div className="flex items-center gap-2">
{Array.from({ length: total }).map((_, i) => (
<div
key={i}
className={`rounded-full transition-all duration-300 ${
i < current
? 'w-2 h-2 bg-sky-400'
: i === current
? 'w-6 h-2 bg-sky-500'
: 'w-2 h-2 bg-slate-200'
}`}
/>
))}
</div>
)
}
// ─── Venue type selector (multi-select) ───────────────────────────────────────
const VENUE_TYPES = [
{ id: 'restaurant', label: 'Restaurant', Icon: UtensilsCrossed },
{ id: 'bar', label: 'Bar', Icon: Beer },
{ id: 'coffee_shop', label: 'Coffee Shop', Icon: Coffee },
{ id: 'fast_food', label: 'Fast Food', Icon: ShoppingBag },
]
function VenueTypeButton({ type, selected, onToggle }) {
const { label, Icon } = type
return (
<button
type="button"
onClick={() => onToggle(type.id)}
className={`relative flex flex-col items-center gap-2 rounded-xl border-2 p-4 text-[13px] font-medium transition-all ${
selected
? 'border-sky-500 bg-sky-50 text-sky-700'
: 'border-slate-200 bg-white text-slate-600 hover:border-slate-300 hover:bg-slate-50'
}`}
>
{selected && (
<div className="absolute top-2 right-2 flex h-4 w-4 items-center justify-center rounded-full bg-sky-500">
<CheckCircle2 className="h-3 w-3 text-white" />
</div>
)}
<Icon className={`h-6 w-6 ${selected ? 'text-sky-500' : 'text-slate-400'}`} />
{label}
</button>
)
}
// ─── PIN pad ──────────────────────────────────────────────────────────────────
const PIN_DIGITS = ['1','2','3','4','5','6','7','8','9','','0','⌫']
function PinPad({ pin, onChange }) {
function press(d) {
if (d === '⌫') { onChange(p => p.slice(0, -1)); return }
if (d === '') return
if (pin.length >= 6) return
onChange(p => p + d)
}
return (
<div className="space-y-3">
<div className="flex justify-center gap-3 py-1">
{Array.from({ length: 4 }).map((_, i) => (
<div
key={i}
className={`w-3.5 h-3.5 rounded-full border-2 transition-colors ${
i < pin.length ? 'bg-sky-500 border-sky-500' : 'border-slate-300'
}`}
/>
))}
</div>
<div className="grid grid-cols-3 gap-2">
{PIN_DIGITS.map((d, i) => (
<button
key={i}
type="button"
onClick={() => press(d)}
disabled={d === ''}
className={`h-12 rounded-xl text-lg font-semibold transition-colors ${
d === ''
? 'invisible'
: d === '⌫'
? 'bg-slate-100 hover:bg-slate-200 text-slate-600'
: 'bg-slate-100 hover:bg-sky-100 active:bg-sky-200 text-slate-800'
}`}
>
{d}
</button>
))}
</div>
</div>
)
}
// ─── Steps ───────────────────────────────────────────────────────────────────
function StepWelcome({ onNext }) {
return (
<div className="flex flex-col items-center text-center gap-6">
<div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-sky-500 shadow-lg shadow-sky-200">
<UtensilsCrossed className="h-10 w-10 text-white" />
</div>
<div className="space-y-2">
<h1 className="text-2xl font-bold text-slate-900">Welcome to Xenia POS</h1>
<p className="text-slate-500 text-[14px] leading-relaxed max-w-xs">
The complete point-of-sale system for your venue. Let's get you set up
in just a few steps — it won't take long.
</p>
</div>
<div className="w-full rounded-xl border border-slate-100 bg-slate-50 p-4 text-left space-y-2">
{[
'Create your manager account',
'Tell us about your venue',
'You\'re ready to go',
].map((s, i) => (
<div key={i} className="flex items-center gap-3 text-[13px] text-slate-600">
<div className="flex h-5 w-5 items-center justify-center rounded-full bg-sky-100 text-sky-600 text-[11px] font-semibold flex-shrink-0">
{i + 1}
</div>
{s}
</div>
))}
</div>
<Button variant="primary" className="w-full py-3 justify-center" onClick={onNext}>
Get Started <ArrowRight className="h-4 w-4" />
</Button>
<p className="text-[11px] text-slate-400">Thank you for choosing Xenia POS.</p>
</div>
)
}
function StepAccount({ data, onChange, onNext, onBack }) {
const [errors, setErrors] = useState({})
// Live password match: debounce 1s after confirm changes
const confirmTimer = useRef(null)
function handleConfirmChange(value) {
onChange('confirm', value)
clearTimeout(confirmTimer.current)
confirmTimer.current = setTimeout(() => {
if (value && data.password && value !== data.password) {
setErrors(e => ({ ...e, confirm: 'Passwords do not match' }))
} else {
setErrors(e => { const next = { ...e }; delete next.confirm; return next })
}
}, 1000)
}
// Also clear the error immediately if they now match
function handlePasswordChange(value) {
onChange('password', value)
if (data.confirm && value === data.confirm) {
setErrors(e => { const next = { ...e }; delete next.confirm; return next })
}
}
function validate() {
const e = {}
if (!data.username.trim()) e.username = 'Username is required'
if (!data.fullName.trim()) e.fullName = 'Full name is required'
if (!data.email.trim()) e.email = 'Email is required'
else if (!/\S+@\S+\.\S+/.test(data.email)) e.email = 'Enter a valid email'
if (data.password.length < 6) e.password = 'At least 6 characters'
if (data.password !== data.confirm) e.confirm = 'Passwords do not match'
setErrors(e)
return Object.keys(e).length === 0
}
return (
<div className="flex flex-col gap-5">
<div className="space-y-1">
<h2 className="text-xl font-bold text-slate-900">Create your manager account</h2>
<p className="text-[13px] text-slate-500">This will be the primary administrator account.</p>
</div>
<div className="space-y-3">
<div>
<LabelledInput
icon={User}
placeholder="Username"
value={data.username}
onChange={e => onChange('username', e.target.value)}
autoComplete="off"
autoFocus
/>
{errors.username && <p className="mt-1 text-[12px] text-rose-500">{errors.username}</p>}
</div>
<div>
<LabelledInput
icon={User}
placeholder="Full Name"
value={data.fullName}
onChange={e => onChange('fullName', e.target.value)}
autoComplete="off"
/>
{errors.fullName && <p className="mt-1 text-[12px] text-rose-500">{errors.fullName}</p>}
</div>
<div>
<LabelledInput
icon={Mail}
placeholder="Email address"
value={data.email}
onChange={e => onChange('email', e.target.value)}
type="email"
autoComplete="off"
/>
{errors.email && <p className="mt-1 text-[12px] text-rose-500">{errors.email}</p>}
</div>
<div>
<LabelledInput
icon={Lock}
placeholder="Password"
value={data.password}
onChange={e => handlePasswordChange(e.target.value)}
type="password"
autoComplete="new-password"
/>
{errors.password && <p className="mt-1 text-[12px] text-rose-500">{errors.password}</p>}
</div>
<div>
<LabelledInput
icon={Lock}
placeholder="Confirm Password"
value={data.confirm}
onChange={e => handleConfirmChange(e.target.value)}
type="password"
autoComplete="new-password"
/>
{errors.confirm && <p className="mt-1 text-[12px] text-rose-500">{errors.confirm}</p>}
</div>
</div>
<div className="flex gap-3">
<Button variant="ghost" className="flex-1 justify-center py-3" onClick={onBack}>
Back
</Button>
<Button variant="primary" className="flex-1 justify-center py-3" onClick={() => { if (validate()) onNext() }}>
Continue <ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)
}
function StepVenue({ data, onChange, onNext, onBack }) {
const { t } = useTranslation('manager')
const [errors, setErrors] = useState({})
function toggleType(id) {
const current = data.venueTypes
const next = current.includes(id)
? current.filter(v => v !== id)
: [...current, id]
onChange('venueTypes', next)
}
function validate() {
const e = {}
if (data.venueTypes.length === 0) e.venueType = 'Please select at least one type'
if (!data.venueName.trim()) e.venueName = 'Venue name is required'
setErrors(e)
return Object.keys(e).length === 0
}
return (
<div className="flex flex-col gap-5">
<div className="space-y-1">
<h2 className="text-xl font-bold text-slate-900">Tell us about your venue</h2>
<p className="text-[13px] text-slate-500">Select all that apply — you can always change this later.</p>
</div>
<div className="space-y-4">
<div>
<p className="text-[12px] font-medium text-slate-500 uppercase tracking-wider mb-2">Venue type</p>
<div className="grid grid-cols-2 gap-2">
{VENUE_TYPES.map(type => (
<VenueTypeButton
key={type.id}
type={type}
selected={data.venueTypes.includes(type.id)}
onToggle={toggleType}
/>
))}
</div>
{errors.venueType && <p className="mt-1 text-[12px] text-rose-500">{errors.venueType}</p>}
</div>
<div className="grid grid-cols-2 gap-3">
<label className="block">
<span className="block text-[12px] font-medium text-slate-500 uppercase tracking-wider mb-2">{t('setup.language')}</span>
<select value={data.language} onChange={e => onChange('language', e.target.value)} data-testid="setup-language"
className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-[14px]">
{Object.entries(LANGUAGE_NAMES).map(([code, name]) => <option key={code} value={code}>{name}</option>)}
</select>
</label>
<label className="block">
<span className="block text-[12px] font-medium text-slate-500 uppercase tracking-wider mb-2">{t('setup.timezone')}</span>
<select value={data.timezone} onChange={e => onChange('timezone', e.target.value)} data-testid="setup-timezone"
className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-[14px]">
{timeZones(data.timezone).map(z => <option key={z} value={z}>{z.replace(/_/g, ' ')}</option>)}
</select>
</label>
<p className="col-span-2 -mt-1 text-[12px] text-slate-500">
{t('setup.languageHint')}
</p>
</div>
<div>
<p className="text-[12px] font-medium text-slate-500 uppercase tracking-wider mb-2">Venue name</p>
<LabelledInput
icon={Building2}
placeholder="e.g. The Golden Fork"
value={data.venueName}
onChange={e => onChange('venueName', e.target.value)}
autoComplete="off"
/>
{errors.venueName && <p className="mt-1 text-[12px] text-rose-500">{errors.venueName}</p>}
</div>
</div>
<div className="flex gap-3">
<Button variant="ghost" className="flex-1 justify-center py-3" onClick={onBack}>
Back
</Button>
<Button variant="primary" className="flex-1 justify-center py-3" onClick={() => { if (validate()) onNext() }}>
Continue <ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)
}
function StepPin({ pin, onChange, onNext, onBack }) {
const hasPin = pin.length >= 4
return (
<div className="flex flex-col gap-5">
<div className="space-y-1">
<h2 className="text-xl font-bold text-slate-900">Set a quick-access PIN</h2>
<p className="text-[13px] text-slate-500">
Optional. Used to unlock the dashboard quickly when it's locked,
without typing your full password.
</p>
</div>
<div className="rounded-xl border border-slate-100 bg-slate-50 p-5">
<PinPad pin={pin} onChange={onChange} />
</div>
{hasPin && (
<p className="text-center text-[12px] text-emerald-600 font-medium">
PIN set — {pin.length} digits
</p>
)}
<div className="flex gap-3">
<Button variant="ghost" className="flex-1 justify-center py-3" onClick={onBack}>
Back
</Button>
<Button
variant={hasPin ? 'primary' : 'secondary'}
className="flex-1 justify-center py-3"
onClick={onNext}
>
{hasPin ? <>Continue <ChevronRight className="h-4 w-4" /></> : 'Skip for now'}
</Button>
</div>
</div>
)
}
function StepDone({ onGoToLogin, loading, error }) {
return (
<div className="flex flex-col items-center text-center gap-6">
<div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-emerald-500 shadow-lg shadow-emerald-200">
<CheckCircle2 className="h-10 w-10 text-white" />
</div>
<div className="space-y-2">
<h2 className="text-2xl font-bold text-slate-900">You're all set!</h2>
<p className="text-[14px] text-slate-500 leading-relaxed max-w-xs">
Your manager account is ready. Log in and start configuring your
products, tables, and staff.
</p>
</div>
<div className="w-full rounded-xl border border-emerald-100 bg-emerald-50 p-4 text-left space-y-2">
{['Add your menu and products', 'Set up tables and zones', 'Add your waiters'].map((tip, i) => (
<div key={i} className="flex items-center gap-3 text-[13px] text-slate-600">
<ChevronRight className="h-4 w-4 text-emerald-500 flex-shrink-0" />
{tip}
</div>
))}
</div>
{error && <p className="text-[13px] text-rose-500">{error}</p>}
<Button
variant="primary"
className="w-full py-3 justify-center"
onClick={onGoToLogin}
disabled={loading}
>
{loading ? 'Setting up…' : 'Go to Login'}
{!loading && <ArrowRight className="h-4 w-4" />}
</Button>
</div>
)
}
// ─── Main wizard ──────────────────────────────────────────────────────────────
// Steps: 0=welcome, 1=account, 2=venue, 3=pin, 4=done
const INNER_STEPS = 3 // steps 1-3 show the dot indicator
export default function SetupWizard() {
const navigate = useNavigate()
const [step, setStep] = useState(0)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [account, setAccount] = useState({
username: '', fullName: '', email: '', password: '', confirm: '',
})
// Staff language and time zone (2.6f): v2 defaults to English, so ask; start from the browser's
const [venue, setVenue] = useState(() => ({
venueTypes: [], venueName: '',
language: (typeof navigator !== 'undefined' && navigator.language?.toLowerCase().startsWith('el')) ? 'el' : 'en',
timezone: browserTimeZone(),
}))
const [pin, setPin] = useState('')
function updateAccount(key, value) {
setAccount(prev => ({ ...prev, [key]: value }))
}
function updateVenue(key, value) {
setVenue(prev => ({ ...prev, [key]: value }))
}
async function handleFinish() {
setLoading(true)
setError('')
try {
await client.post('/api/setup/init', {
username: account.username.trim(),
password: account.password,
email: account.email.trim(),
full_name: account.fullName.trim(),
venue_type: venue.venueTypes.join(','),
venue_name: venue.venueName.trim(),
language: venue.language,
timezone: venue.timezone,
pin: pin.length >= 4 ? pin : undefined,
})
navigate('/login', { replace: true })
} catch (err) {
setError(err.response?.data?.detail || 'Something went wrong. Please try again.')
setLoading(false)
}
}
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-sky-50 flex items-center justify-center p-4">
<div className="w-full max-w-md">
<div className="bg-white rounded-2xl shadow-xl shadow-slate-200/60 border border-slate-100 p-8">
{/* Dot indicator for inner steps only */}
{step >= 1 && step <= INNER_STEPS && (
<div className="flex justify-center mb-6">
<StepDots total={INNER_STEPS} current={step - 1} />
</div>
)}
{step === 0 && <StepWelcome onNext={() => setStep(1)} />}
{step === 1 && (
<StepAccount
data={account}
onChange={updateAccount}
onNext={() => setStep(2)}
onBack={() => setStep(0)}
/>
)}
{step === 2 && (
<StepVenue
data={venue}
onChange={updateVenue}
onNext={() => setStep(3)}
onBack={() => setStep(1)}
/>
)}
{step === 3 && (
<StepPin
pin={pin}
onChange={setPin}
onNext={() => setStep(4)}
onBack={() => setStep(2)}
/>
)}
{step === 4 && (
<StepDone
onGoToLogin={handleFinish}
loading={loading}
error={error}
/>
)}
</div>
<p className="text-center text-[11px] text-slate-400 mt-4">
Xenia POS · First-time Setup
</p>
</div>
</div>
)
}
@@ -1,825 +0,0 @@
import { useState, useRef } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../api/client'
import { ConfirmModal } from '../ui/Modal'
import Button from '../ui/Button'
const MAX_TABLE_NAME_LENGTH = 6
const ZONE_COLORS = ['#6366f1','#0ea5e9','#10b981','#f59e0b','#ef4444','#ec4899','#8b5cf6','#14b8a6','#f97316','#64748b']
function ZoneColorPicker({ value, onChange }) {
return (
<div className="flex flex-wrap gap-2 mt-1">
<button
type="button"
onClick={() => onChange(null)}
className="w-7 h-7 rounded-full border-2 bg-gray-200 transition-all"
style={{ borderColor: !value ? '#000' : 'transparent' }}
title="Χωρίς χρώμα"
/>
{ZONE_COLORS.map(c => (
<button
key={c}
type="button"
onClick={() => onChange(c)}
className="w-7 h-7 rounded-full border-2 transition-all"
style={{ background: c, borderColor: value === c ? '#000' : 'transparent' }}
/>
))}
</div>
)
}
export default function TablesPage() {
const qc = useQueryClient()
const [addModal, setAddModal] = useState(false)
const [editModal, setEditModal] = useState(null)
const [batchModal, setBatchModal] = useState(null) // group object or null
const [groupModal, setGroupModal] = useState(null) // null | {} | group object
const [confirmDelete, setConfirmDelete] = useState(null)
const [bulkMoveModal, setBulkMoveModal] = useState(false)
const [bulkRenameModal, setBulkRenameModal] = useState(false)
const [showInactive, setShowInactive] = useState(false)
const [selectMode, setSelectMode] = useState(false)
const [activeTab, setActiveTab] = useState('all') // 'all' | group.id
const [selected, setSelected] = useState(new Set())
const [anyHovered, setAnyHovered] = useState(false)
const dragGroupId = useRef(null)
const [dragOverGap, setDragOverGap] = useState(null) // index into groups array (0 = before first)
const { data: tables = [], isLoading } = useQuery({
queryKey: ['tables-all', showInactive],
queryFn: () => client.get(`/api/tables/?include_inactive=${showInactive}`).then(r => r.data),
})
const { data: groups = [] } = useQuery({
queryKey: ['table-groups'],
queryFn: () => client.get('/api/tables/groups').then(r => r.data),
})
const invalidate = () => {
qc.invalidateQueries({ queryKey: ['tables-all'] })
qc.invalidateQueries({ queryKey: ['tables'] })
}
const invalidateGroups = () => qc.invalidateQueries({ queryKey: ['table-groups'] })
const createTable = useMutation({
mutationFn: (body) => client.post('/api/tables/', body),
onSuccess: () => { toast.success('Τραπέζι δημιουργήθηκε'); setAddModal(false); invalidate() },
onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'),
})
const batchCreate = useMutation({
mutationFn: (body) => client.post('/api/tables/batch', body),
onSuccess: (res) => { toast.success(`${res.data.length} τραπέζια δημιουργήθηκαν`); setBatchModal(null); invalidate() },
onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'),
})
const updateTable = useMutation({
mutationFn: ({ id, ...body }) => client.put(`/api/tables/${id}`, body),
onSuccess: () => { toast.success('Αποθηκεύτηκε'); setEditModal(null); invalidate() },
onError: () => toast.error('Σφάλμα'),
})
const deleteTable = useMutation({
mutationFn: ({ id, hard }) => client.delete(`/api/tables/${id}?hard=${hard}`),
onSuccess: (_, vars) => {
toast.success(vars.hard ? 'Διαγράφηκε' : 'Απενεργοποιήθηκε')
setConfirmDelete(null)
invalidate()
},
onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'),
})
const saveGroup = useMutation({
mutationFn: (body) => groupModal?.id
? client.put(`/api/tables/groups/${groupModal.id}`, body)
: client.post('/api/tables/groups', body),
onSuccess: () => { toast.success('Ζώνη αποθηκεύτηκε'); setGroupModal(null); invalidateGroups(); invalidate() },
onError: (err) => toast.error(err.response?.data?.detail || 'Σφάλμα'),
})
const deleteGroup = useMutation({
mutationFn: (id) => client.delete(`/api/tables/groups/${id}`),
onSuccess: () => { toast.success('Ζώνη διαγράφηκε'); setGroupModal(null); invalidateGroups(); invalidate() },
onError: () => toast.error('Σφάλμα'),
})
const reorderGroups = useMutation({
mutationFn: (ids) => client.put('/api/tables/groups/reorder', ids),
onSuccess: invalidateGroups,
onError: () => toast.error('Σφάλμα αναδιάταξης'),
})
// Filter tables for the active tab
const visibleTables = activeTab === 'all'
? tables
: activeTab === 'ungrouped'
? tables.filter(t => !t.group_id)
: tables.filter(t => t.group_id === activeTab)
const toggleSelect = (id) => setSelected(prev => {
const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n
})
const clearSelect = () => setSelected(new Set())
const anySelected = selected.size > 0
const allVisibleSelected = visibleTables.length > 0 && visibleTables.every(t => selected.has(t.id))
function toggleSelectAll() {
if (allVisibleSelected) {
// Deselect all visible
setSelected(prev => {
const n = new Set(prev)
visibleTables.forEach(t => n.delete(t.id))
return n
})
} else {
// Select all visible
setSelected(prev => {
const n = new Set(prev)
visibleTables.forEach(t => n.add(t.id))
return n
})
}
}
function exitSelectMode() {
setSelectMode(false)
clearSelect()
}
function bulkDelete() {
setConfirmDelete({ type: 'bulk', ids: [...selected] })
}
async function handleBulkMove(groupId) {
const ids = [...selected]
await Promise.allSettled(ids.map(id => client.put(`/api/tables/${id}`, { group_id: groupId })))
toast.success(`${ids.length} τραπέζια μετακινήθηκαν`)
setBulkMoveModal(false)
exitSelectMode()
invalidate()
}
async function handleBulkRename(prefix, startNumber) {
const ids = [...selected]
// Apply names in the order tables appear in the visible list
const orderedIds = visibleTables.filter(t => selected.has(t.id)).map(t => t.id)
const patches = orderedIds.map((id, i) => ({
id,
label: `${prefix}${startNumber + i}`,
}))
await Promise.allSettled(patches.map(({ id, label }) => client.put(`/api/tables/${id}`, { label })))
toast.success(`${orderedIds.length} τραπέζια μετονομάστηκαν`)
setBulkRenameModal(false)
exitSelectMode()
invalidate()
}
if (isLoading) return <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
const zoneTabs = [
{ id: 'all', label: 'Όλα', color: null },
...groups.map(g => ({ id: g.id, label: g.prefix ? `${g.prefix} – ${g.name}` : g.name, color: g.color, group: g })),
...(tables.some(t => !t.group_id) ? [{ id: 'ungrouped', label: 'Χωρίς ζώνη', color: null }] : []),
]
const totalTables = tables.length
const inactiveTables = tables.filter(t => !t.is_active).length
const zoneCount = groups.length
return (
<div className="flex flex-col h-full min-h-0">
{/* Toolbar */}
<div className="flex gap-2 flex-wrap items-center border-b border-slate-200 px-6 flex-shrink-0" style={{ minHeight: 60 }}>
{/* Stats — left side */}
{!isLoading && !anySelected && !selectMode && (
<div className="flex items-center gap-3 text-[12px] text-slate-400 mr-2">
<span><strong className="text-slate-700 font-semibold">{totalTables}</strong> τραπέζια</span>
<span className="text-slate-200">·</span>
<span><strong className="text-slate-700 font-semibold">{zoneCount}</strong> {zoneCount === 1 ? 'ζώνη' : 'ζώνες'}</span>
{inactiveTables > 0 && (
<>
<span className="text-slate-200">·</span>
<span><strong className="text-amber-600 font-semibold">{inactiveTables}</strong> ανενεργά</span>
</>
)}
</div>
)}
{/* Multi-select action bar */}
{(selectMode || anySelected) && (
<>
{/* Select-all / deselect-all toggle + close */}
<button
onClick={exitSelectMode}
className="text-xs text-slate-500 hover:text-slate-700 flex items-center gap-1.5 mr-1"
>
<span className="w-4 h-4 rounded border border-slate-300 flex items-center justify-center text-[10px]">✕</span>
{anySelected ? `${selected.size} επιλεγμένα` : 'Επιλογή'}
</button>
<button
onClick={toggleSelectAll}
className="text-xs text-sky-600 hover:text-sky-800 underline"
>
{allVisibleSelected ? 'Αποεπιλογή όλων' : 'Επιλογή όλων'}
</button>
{anySelected && (
<>
<span className="w-px h-4 bg-slate-200 mx-1" />
<Button variant="secondary" size="sm" onClick={() => setBulkMoveModal(true)}>
Μετακίνηση ζώνης
</Button>
<Button variant="secondary" size="sm" onClick={() => setBulkRenameModal(true)}>
Μαζική μετονομασία
</Button>
<Button variant="danger" size="sm" onClick={bulkDelete}>
Διαγραφή
</Button>
</>
)}
<span className="flex-1" />
</>
)}
{!selectMode && !anySelected && <span className="flex-1" />}
<Button
variant={showInactive ? 'primary' : 'secondary'}
size="sm"
onClick={() => setShowInactive(v => !v)}
>
{showInactive ? '✓ ' : ''}Ανενεργά
</Button>
{!selectMode && (
<Button variant="secondary" size="sm" onClick={() => setSelectMode(true)}>
Επιλογή
</Button>
)}
<Button variant="secondary" size="sm" onClick={() => setGroupModal({})}>+ Νέα ζώνη</Button>
<Button variant="primary" size="sm" onClick={() => setAddModal(true)}>+ Νέο τραπέζι</Button>
</div>
{/* Zone tabs */}
<div className="flex gap-0 flex-wrap border-b border-slate-200 px-4 flex-shrink-0">
{zoneTabs.map(tab => {
const isGroup = tab.id !== 'all' && tab.id !== 'ungrouped'
const groupIdx = isGroup ? groups.findIndex(g => g.id === tab.id) : -1
function handleDragOver(e) {
e.preventDefault()
// Use mouse position within the tab to decide left-half vs right-half gap
const rect = e.currentTarget.getBoundingClientRect()
const isLeftHalf = e.clientX < rect.left + rect.width / 2
setDragOverGap(isLeftHalf ? groupIdx : groupIdx + 1)
}
function handleDrop(e) {
e.preventDefault()
const fromId = dragGroupId.current
dragGroupId.current = null
setDragOverGap(null)
if (!fromId) return
const groupIds = groups.map(g => g.id)
const fromIdx = groupIds.indexOf(fromId)
if (fromIdx === -1 || dragOverGap === null) return
const reordered = [...groupIds]
reordered.splice(fromIdx, 1)
// After removing the dragged item, adjust target index
const insertAt = dragOverGap > fromIdx ? dragOverGap - 1 : dragOverGap
reordered.splice(insertAt, 0, fromId)
if (reordered.join() !== groupIds.join()) reorderGroups.mutate(reordered)
}
const showLineLeft = isGroup && dragOverGap === groupIdx
const showLineRight = isGroup && dragOverGap === groupIdx + 1 && groupIdx === groups.length - 1
return (
<div key={tab.id} className="relative flex items-stretch">
{/* Drop indicator line — left side of this tab */}
{showLineLeft && (
<div className="absolute left-0 top-1 bottom-1 w-0.5 bg-sky-500 rounded-full z-10 -translate-x-px" />
)}
<button
onClick={() => { setActiveTab(tab.id); clearSelect() }}
draggable={isGroup}
onDragStart={isGroup ? () => { dragGroupId.current = tab.id } : undefined}
onDragOver={isGroup ? handleDragOver : undefined}
onDragLeave={isGroup ? () => setDragOverGap(null) : undefined}
onDrop={isGroup ? handleDrop : undefined}
onDragEnd={isGroup ? () => { dragGroupId.current = null; setDragOverGap(null) } : undefined}
className={`flex items-center gap-1.5 px-4 py-2.5 text-sm font-medium transition-colors border-b-2 -mb-px ${
activeTab === tab.id
? 'border-sky-500 text-sky-600'
: 'border-transparent text-slate-500 hover:text-slate-700 hover:border-slate-300'
} ${isGroup ? 'cursor-grab active:cursor-grabbing' : ''}`}
>
{isGroup && <span className="text-slate-300 text-xs mr-0.5 select-none">⠿</span>}
{tab.color && <span className="w-2 h-2 rounded-full shrink-0" style={{ background: tab.color }} />}
{tab.label}
<span className="ml-0.5 text-xs text-slate-400">
({tab.id === 'all' ? tables.length : tab.id === 'ungrouped' ? tables.filter(t => !t.group_id).length : tables.filter(t => t.group_id === tab.id).length})
</span>
</button>
{/* Drop indicator line — right side of the last group tab */}
{showLineRight && (
<div className="absolute right-0 top-1 bottom-1 w-0.5 bg-sky-500 rounded-full z-10 translate-x-px" />
)}
</div>
)
})}
</div>
{/* Zone action bar (when viewing a specific zone) */}
{activeTab !== 'all' && activeTab !== 'ungrouped' && (() => {
const g = groups.find(g => g.id === activeTab)
if (!g) return null
return (
<div className="flex items-center gap-3 px-6 py-2 border-b border-slate-100 flex-shrink-0">
<span className="font-semibold text-slate-700 text-sm">{g.name}</span>
{g.prefix && <span className="text-xs bg-white text-slate-500 border border-slate-200 px-2 py-0.5 rounded font-mono">{g.prefix}</span>}
<button onClick={() => setGroupModal(g)} className="text-xs text-slate-400 hover:text-slate-600 underline ml-1">Επεξεργασία</button>
<Button variant="secondary" size="sm" onClick={() => setBatchModal(g)} className="ml-auto">+ Μαζική προσθήκη</Button>
</div>
)
})()}
{/* Tables list */}
<div className="flex-1 overflow-y-auto p-6">
{visibleTables.length === 0 ? (
<p className="py-10 text-sm text-slate-400 text-center">
{showInactive ? 'Δεν υπάρχουν τραπέζια.' : 'Δεν υπάρχουν ενεργά τραπέζια.'}
</p>
) : (() => {
// Build a set of labels that appear more than once across ALL tables (not just visible)
const labelCounts = {}
tables.forEach(t => { if (t.label) labelCounts[t.label] = (labelCounts[t.label] || 0) + 1 })
const duplicateLabels = new Set(Object.keys(labelCounts).filter(l => labelCounts[l] > 1))
return (
<div className="rounded-xl border border-slate-200 bg-white overflow-hidden divide-y divide-slate-100">
{visibleTables.map((t, idx) => {
const isSelected = selected.has(t.id)
const isDuplicate = t.label && duplicateLabels.has(t.label)
const showCheckbox = selectMode || anySelected || isSelected
return (
<div
key={t.id}
className={`flex items-center gap-4 px-4 py-3 group transition-colors ${!t.is_active ? 'opacity-50' : ''} ${isSelected ? 'bg-sky-50' : 'hover:bg-slate-50'} ${selectMode ? 'cursor-pointer' : ''}`}
onClick={selectMode ? () => toggleSelect(t.id) : undefined}
onMouseEnter={() => setAnyHovered(true)}
onMouseLeave={() => setAnyHovered(false)}
>
{/* Number / Checkbox */}
<div className="w-6 shrink-0 flex items-center justify-center">
{showCheckbox ? (
<input
type="checkbox"
checked={isSelected}
onChange={() => toggleSelect(t.id)}
className="w-4 h-4 rounded accent-sky-500 cursor-pointer"
onClick={e => e.stopPropagation()}
/>
) : (
<span className="text-xs text-slate-400 font-mono group-hover:hidden">{idx + 1}</span>
)}
{!showCheckbox && (
<input
type="checkbox"
checked={false}
onChange={() => { setSelectMode(true); toggleSelect(t.id) }}
className="hidden group-hover:block w-4 h-4 rounded accent-sky-500 cursor-pointer"
onClick={e => e.stopPropagation()}
/>
)}
</div>
<p className="flex-1 font-medium text-slate-800">{t.label || `Τραπέζι ${t.number}`}</p>
{isDuplicate && (
<span className="text-xs font-semibold px-2 py-0.5 rounded-full bg-amber-100 text-amber-700 border border-amber-200">
Διπλό όνομα
</span>
)}
{t.seat_count != null && (
<span className="text-xs text-slate-400 hidden sm:inline" title="Αριθμός θέσεων">
{t.seat_count} θέσ.
</span>
)}
{t.group && (
<span className="text-xs bg-slate-100 text-slate-500 px-2 py-0.5 rounded hidden sm:inline">
{t.group.name}
</span>
)}
{!t.is_active && <span className="text-xs text-amber-600 font-medium">Ανενεργό</span>}
{!selectMode && (
<>
<Button variant="secondary" size="sm" onClick={() => setEditModal(t)}>Επεξεργασία</Button>
{t.is_active
? <Button
variant="ghost"
size="sm"
onClick={() => !t.has_active_order && setConfirmDelete({ type: 'single', id: t.id, hard: false })}
disabled={t.has_active_order}
title={t.has_active_order ? 'Υπάρχει ενεργή παραγγελία' : undefined}
className="text-amber-600 hover:bg-amber-50 disabled:opacity-40 disabled:cursor-not-allowed"
>Απενεργ.</Button>
: <Button
variant="ghost"
size="sm"
onClick={() => updateTable.mutate({ id: t.id, is_active: true })}
className="text-green-600 hover:bg-green-50"
>Ενεργοπ.</Button>
}
<Button
variant="danger"
size="sm"
onClick={() => !t.has_active_order && setConfirmDelete({ type: 'single', id: t.id, hard: true })}
disabled={t.has_active_order}
title={t.has_active_order ? 'Υπάρχει ενεργή παραγγελία' : undefined}
className="disabled:opacity-40 disabled:cursor-not-allowed"
>Διαγραφή</Button>
</>
)}
</div>
)
})}
</div>
)
})()}
</div>
{/* Add single table */}
{addModal && (
<TableModal
title="Νέο τραπέζι"
initial={{ label: '', group_id: activeTab !== 'all' && activeTab !== 'ungrouped' ? activeTab : '', seat_count: null }}
groups={groups}
onSave={(f) => createTable.mutate({ label: f.label || null, group_id: f.group_id ? Number(f.group_id) : null, seat_count: f.seat_count || null })}
onClose={() => setAddModal(false)}
/>
)}
{/* Edit table */}
{editModal && (
<TableModal
title="Επεξεργασία τραπεζιού"
initial={{ label: editModal.label || '', group_id: editModal.group_id || '', seat_count: editModal.seat_count ?? null }}
groups={groups}
onSave={(f) => updateTable.mutate({ id: editModal.id, label: f.label || null, group_id: f.group_id ? Number(f.group_id) : null, seat_count: f.seat_count || null })}
onClose={() => setEditModal(null)}
/>
)}
{/* Batch add */}
{batchModal !== null && (
<BatchModal
group={batchModal}
tables={tables}
onSave={(body) => batchCreate.mutate(body)}
onClose={() => setBatchModal(null)}
/>
)}
{/* Bulk move zone */}
{bulkMoveModal && (
<BulkMoveModal
count={selected.size}
groups={groups}
onSave={handleBulkMove}
onClose={() => setBulkMoveModal(false)}
/>
)}
{/* Bulk rename */}
{bulkRenameModal && (
<BulkRenameModal
selectedTables={visibleTables.filter(t => selected.has(t.id))}
onSave={handleBulkRename}
onClose={() => setBulkRenameModal(false)}
/>
)}
{/* Group/Zone form */}
{groupModal !== null && (
<GroupModal
group={groupModal}
onSave={(data) => saveGroup.mutate(data)}
onDelete={groupModal.id ? () => deleteGroup.mutate(groupModal.id) : null}
onClose={() => setGroupModal(null)}
/>
)}
{/* Delete confirmation */}
{confirmDelete && (
<ConfirmModal
title={
confirmDelete.type === 'bulk'
? `Διαγραφή ${confirmDelete.ids.length} τραπεζιών;`
: confirmDelete.hard ? 'Οριστική διαγραφή τραπεζιού;' : 'Απενεργοποίηση τραπεζιού;'
}
message={
confirmDelete.type === 'bulk'
? `${confirmDelete.ids.length} τραπέζια θα διαγραφούν οριστικά.`
: confirmDelete.hard
? 'Το τραπέζι θα διαγραφεί οριστικά. Αδύνατο αν έχει ενεργή παραγγελία.'
: 'Το τραπέζι θα κρυφτεί. Μπορείτε να το επανενεργοποιήσετε αργότερα.'
}
confirmLabel={confirmDelete.type === 'bulk' || confirmDelete.hard ? 'Διαγραφή' : 'Απενεργοποίηση'}
confirmVariant="danger"
onConfirm={async () => {
if (confirmDelete.type === 'bulk') {
await Promise.allSettled(confirmDelete.ids.map(id => client.delete(`/api/tables/${id}?hard=true`)))
toast.success(`${confirmDelete.ids.length} τραπέζια διαγράφηκαν`)
setConfirmDelete(null); exitSelectMode(); invalidate()
} else {
deleteTable.mutate({ id: confirmDelete.id, hard: confirmDelete.hard })
}
}}
onCancel={() => setConfirmDelete(null)}
/>
)}
</div>
)
}
function TableModal({ title, initial, groups, onSave, onClose }) {
const [form, setForm] = useState(initial)
const labelLen = (form.label || '').length
const labelTooLong = labelLen > MAX_TABLE_NAME_LENGTH
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-4">
<h2 className="font-bold text-gray-800">{title}</h2>
<div>
<label className="label">Όνομα τραπεζιού</label>
<input
className="input"
placeholder="π.χ. BS-1 ή Β3"
value={form.label}
maxLength={MAX_TABLE_NAME_LENGTH}
onChange={e => setForm(f => ({ ...f, label: e.target.value }))}
autoFocus
/>
<div className="flex justify-between mt-1">
<p className="text-xs text-gray-400">Αφήστε κενό για αυτόματη αρίθμηση.</p>
{form.label ? (
<p className={`text-xs font-mono ${labelLen >= MAX_TABLE_NAME_LENGTH ? 'text-red-500' : 'text-gray-400'}`}>
{labelLen}/{MAX_TABLE_NAME_LENGTH}
</p>
) : null}
</div>
{labelTooLong && (
<p className="text-xs text-red-500">Το όνομα δεν μπορεί να υπερβαίνει τους {MAX_TABLE_NAME_LENGTH} χαρακτήρες.</p>
)}
</div>
<div>
<label className="label">Ζώνη</label>
<select className="input" value={form.group_id} onChange={e => setForm(f => ({ ...f, group_id: e.target.value }))}>
<option value="">— Χωρίς ζώνη —</option>
{groups.map(g => <option key={g.id} value={g.id}>{g.name}{g.prefix ? ` (${g.prefix})` : ''}</option>)}
</select>
</div>
<div>
<label className="label">Αριθμός θέσεων</label>
<input
className="input"
type="number"
min="1"
max="99"
placeholder="π.χ. 4"
value={form.seat_count ?? ''}
onChange={e => setForm(f => ({ ...f, seat_count: e.target.value ? Number(e.target.value) : null }))}
/>
<p className="text-xs text-gray-400 mt-1">Αφήστε κενό αν δεν θέλετε να ορίσετε θέσεις.</p>
</div>
<div className="flex gap-3">
<button onClick={onClose} className="flex-1 btn btn-secondary">Ακύρωση</button>
<button
onClick={() => onSave(form)}
disabled={labelTooLong}
className="flex-1 btn btn-primary disabled:opacity-40 disabled:cursor-not-allowed"
>
Αποθήκευση
</button>
</div>
</div>
</div>
)
}
function BulkMoveModal({ count, groups, onSave, onClose }) {
const [groupId, setGroupId] = useState('')
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-4">
<h2 className="font-bold text-gray-800">Μετακίνηση σε ζώνη</h2>
<p className="text-sm text-slate-500">{count} {count === 1 ? 'τραπέζι' : 'τραπέζια'} επιλεγμένα.</p>
<div>
<label className="label">Νέα ζώνη</label>
<select className="input" value={groupId} onChange={e => setGroupId(e.target.value)} autoFocus>
<option value="">— Χωρίς ζώνη —</option>
{groups.map(g => (
<option key={g.id} value={g.id}>{g.name}{g.prefix ? ` (${g.prefix})` : ''}</option>
))}
</select>
</div>
<div className="flex gap-3">
<button onClick={onClose} className="flex-1 btn btn-secondary">Ακύρωση</button>
<button
onClick={() => onSave(groupId ? Number(groupId) : null)}
className="flex-1 btn btn-primary"
>
Μετακίνηση
</button>
</div>
</div>
</div>
)
}
function BulkRenameModal({ selectedTables, onSave, onClose }) {
const count = selectedTables.length
const [prefix, setPrefix] = useState('')
const [startNumber, setStartNumber] = useState(1)
const trimmedPrefix = prefix.trim()
const lastN = startNumber + count - 1
const worstCase = `${trimmedPrefix}${lastN}`
const lengthError = trimmedPrefix && worstCase.length > MAX_TABLE_NAME_LENGTH
? `Το τελευταίο όνομα θα είναι '${worstCase}' (${worstCase.length} χαρ.). Μικρύνετε το πρόθεμα ή αλλάξτε αριθμό εκκίνησης.`
: null
// Live preview — at most 5 names shown
const previewNames = Array.from({ length: Math.min(count, 5) }, (_, i) =>
trimmedPrefix ? `${trimmedPrefix}${startNumber + i}` : null
)
const hasMore = count > 5
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-4">
<h2 className="font-bold text-gray-800">Μαζική μετονομασία</h2>
<p className="text-sm text-slate-500">
{count} {count === 1 ? 'τραπέζι' : 'τραπέζια'} επιλεγμένα — θα μετονομαστούν με τη σειρά που εμφανίζονται στη λίστα.
</p>
<div>
<label className="label">Πρόθεμα</label>
<input
className="input font-mono"
placeholder="π.χ. BS-"
value={prefix}
maxLength={MAX_TABLE_NAME_LENGTH - 1}
onChange={e => setPrefix(e.target.value)}
autoFocus
/>
</div>
<div>
<label className="label">Αριθμός εκκίνησης</label>
<input
className="input"
type="number"
min="1"
max="999"
value={startNumber}
onChange={e => setStartNumber(Math.max(1, Number(e.target.value) || 1))}
/>
</div>
{/* Live preview */}
{trimmedPrefix && !lengthError && (
<div className="bg-slate-50 rounded-lg px-3 py-2 text-xs text-slate-500 space-y-1">
<p className="font-medium text-slate-600 mb-1">Προεπισκόπηση:</p>
<div className="flex flex-wrap gap-1.5">
{previewNames.map((name, i) => (
<span key={i} className="bg-white border border-slate-200 rounded px-2 py-0.5 font-mono text-slate-700">
{name}
</span>
))}
{hasMore && (
<span className="text-slate-400 self-center">… +{count - 5} ακόμα</span>
)}
</div>
</div>
)}
{lengthError && (
<p className="text-xs text-red-500">{lengthError}</p>
)}
<div className="flex gap-3">
<button onClick={onClose} className="flex-1 btn btn-secondary">Ακύρωση</button>
<button
onClick={() => onSave(trimmedPrefix, startNumber)}
disabled={!trimmedPrefix || !!lengthError}
className="flex-1 btn btn-primary disabled:opacity-40 disabled:cursor-not-allowed"
>
Μετονομασία {count} τραπεζιών
</button>
</div>
</div>
</div>
)
}
function computeStartNumber(tables, groupId, prefix) {
if (!prefix) return 1
const inGroup = groupId ? tables.filter(t => t.group_id === groupId) : []
const used = inGroup
.filter(t => t.label && t.label.startsWith(prefix))
.map(t => {
const suffix = t.label.slice(prefix.length)
return /^\d+$/.test(suffix) ? parseInt(suffix, 10) : null
})
.filter(n => n !== null)
return used.length > 0 ? Math.max(...used) + 1 : 1
}
function BatchModal({ group, tables, onSave, onClose }) {
const [count, setCount] = useState(5)
const [prefix, setPrefix] = useState(group?.prefix ? `${group.prefix}-` : '')
const trimmedPrefix = prefix.trim()
const startNumber = computeStartNumber(tables, group?.id ?? null, trimmedPrefix)
const lastN = startNumber + count - 1
const worstCase = `${trimmedPrefix}${lastN}`
const lengthError = trimmedPrefix && worstCase.length > MAX_TABLE_NAME_LENGTH
? `O τελευταίος πίνακας θα ονομαστεί '${worstCase}' (${worstCase.length} χαρ.). Μικρύνετε το πρόθεμα ή μειώστε τον αριθμό.`
: null
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-4">
<h2 className="font-bold text-gray-800">Μαζική προσθήκη τραπεζιών</h2>
{group && <p className="text-sm text-gray-500">Ζώνη: <span className="font-medium text-gray-700">{group.name}</span></p>}
<div>
<label className="label">Πρόθεμα ονόματος</label>
<input
className="input"
placeholder="π.χ. BS- → BS-1, BS-2…"
value={prefix}
onChange={e => setPrefix(e.target.value)}
autoFocus
/>
{lengthError ? (
<p className="text-xs text-red-500 mt-1">{lengthError}</p>
) : (
<p className="text-xs text-gray-400 mt-1">Τα ονόματα θα αριθμηθούν αυτόματα συνεχίζοντας από εκεί που σταμάτησαν.</p>
)}
</div>
<div>
<label className="label">Πλήθος</label>
<input className="input" type="number" min="1" max="200" value={count} onChange={e => setCount(Number(e.target.value))} />
</div>
<div className="flex gap-3">
<button onClick={onClose} className="flex-1 btn btn-secondary">Ακύρωση</button>
<button
onClick={() => onSave({ group_id: group?.id ?? null, count, name_prefix: trimmedPrefix })}
disabled={count < 1 || !trimmedPrefix || !!lengthError}
className="flex-1 btn btn-primary disabled:opacity-40 disabled:cursor-not-allowed"
>
Δημιουργία {count > 0 && trimmedPrefix && !lengthError ? `(${trimmedPrefix}${startNumber} … ${trimmedPrefix}${lastN})` : ''}
</button>
</div>
</div>
</div>
)
}
function GroupModal({ group, onSave, onDelete, onClose }) {
const [name, setName] = useState(group.name || '')
const [prefix, setPrefix] = useState(group.prefix || '')
const [color, setColor] = useState(group.color || null)
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-4">
<h2 className="font-bold text-gray-800">{group.id ? 'Επεξεργασία ζώνης' : 'Νέα ζώνη'}</h2>
<div>
<label className="label">Όνομα ζώνης *</label>
<input className="input" value={name} onChange={e => setName(e.target.value)} autoFocus placeholder="π.χ. Beachside" />
</div>
<div>
<label className="label">Πρόθεμα (για μαζική δημιουργία)</label>
<input className="input font-mono" value={prefix} onChange={e => setPrefix(e.target.value)} placeholder="π.χ. BS" />
<p className="text-xs text-gray-400 mt-1">Χρησιμοποιείται ως προτεινόμενο πρόθεμα στη μαζική προσθήκη.</p>
</div>
<div>
<label className="label">Χρώμα ζώνης</label>
<ZoneColorPicker value={color} onChange={setColor} />
</div>
<div className="flex gap-3">
{onDelete && <button onClick={onDelete} className="btn btn-danger px-3">Διαγραφή</button>}
<button onClick={onClose} className="flex-1 btn btn-secondary">Ακύρωση</button>
<button onClick={() => onSave({ name, prefix: prefix || null, color: color || null })} disabled={!name.trim()} className="flex-1 btn btn-primary">Αποθήκευση</button>
</div>
</div>
</div>
)
}
@@ -15,7 +15,7 @@ import { useCan, useModule } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, IconButton, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { LicenseContext } from '../../layouts/AppLayout'
import { LicenseContext } from '../../shell/licenseContext'
import { useLiveQuery } from '../../live/useLiveQuery'
import BookingsCard, { BookingDialog } from './BookingsCard'
import DaySummaryDialog from './DaySummaryDialog'
@@ -0,0 +1,189 @@
// First-run setup (plan step 6.14b; was the v1 SetupWizard): on a fresh install (no manager yet)
// the sign-in page sends here. Welcome → the owner's account (username, name, e-mail, password)
// → the venue (kind, name, staff language and time zone: the wizard switches to the language at
// once) → a PIN for the lock screen (optional) → done: the venue is set up and you sign in.
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { ArrowRight, Beer, CheckCircle2, ChevronLeft, Coffee, ShoppingBag, UtensilsCrossed } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { LANGUAGE_NAMES, useTranslation } from '@xenia/i18n'
import { Button, Field, Input, Select, cx } from '@xenia/ui'
import client from '../../api/client'
import { browserTimeZone, timeZones } from '../Settings/sections/timeZones'
import { VENUE_TYPES, accountProblems, pinProblems, setupBody, startLanguage, venueProblems } from './setupLogic'
const ICONS = { restaurant: UtensilsCrossed, bar: Beer, coffee_shop: Coffee, fast_food: ShoppingBag }
const STEPS = ['welcome', 'account', 'venue', 'pin', 'done']
export default function SetupWizard() {
const { t, i18n } = useTranslation('manager')
const navigate = useNavigate()
const qc = useQueryClient()
const [step, setStep] = useState(0)
const [tried, setTried] = useState(false)
const [account, setAccount] = useState({ username: '', fullName: '', email: '', password: '', confirm: '' })
const [venue, setVenue] = useState(() => ({ types: [], name: '', language: startLanguage(typeof navigator !== 'undefined' ? navigator.language : ''), timezone: browserTimeZone() }))
const [pin, setPin] = useState({ pin: '', again: '' })
const problems = [[], accountProblems(account), venueProblems(venue), pinProblems(pin.pin, pin.again), []][step]
const err = k => { const p = tried && problems.find(([f]) => f === k); return p ? t(`setup.wrong.${p[1]}`) : undefined }
const next = () => { setTried(true); if (!problems.length) { setTried(false); setStep(s => s + 1) } }
const back = () => { setTried(false); setStep(s => s - 1) }
const setLanguage = lang => { setVenue(v => ({ ...v, language: lang })); i18n.changeLanguage(lang) }
const finish = useMutation({
mutationFn: () => client.post('/api/setup/init', setupBody(account, venue, pin.pin)),
onSuccess: () => { qc.setQueryData(['setup-status'], { needs_setup: false }); navigate('/login', { replace: true }) },
})
const name = STEPS[step]
return (
<div className="min-h-screen bg-canvas flex items-center justify-center p-4" data-testid="setup-wizard" data-step={name}>
<div className="w-full max-w-md grid gap-4">
<div className="bg-surface rounded-dialog shadow-overlay border border-line p-8 grid gap-5">
{step >= 1 && step <= 3 && (
<div className="flex justify-center gap-2" aria-label={t('setup.stepOf', { n: step, of: 3 })}>
{[1, 2, 3].map(i => <span key={i} className={cx('h-2 rounded-full transition-all', i === step ? 'w-6 bg-accent' : i < step ? 'w-2 bg-accent' : 'w-2 bg-surface-3')} />)}
</div>
)}
{name === 'welcome' && (
<div className="grid justify-items-center text-center gap-5">
<span className="grid place-items-center w-20 h-20 rounded-card bg-accent text-accent-fg"><UtensilsCrossed size={40} aria-hidden="true" /></span>
<div className="grid gap-2">
<h1 className="text-heading font-bold text-ink">{t('setup.welcome')}</h1>
<p className="text-body text-ink-2 max-w-xs">{t('setup.welcomeIntro')}</p>
</div>
<ol className="w-full rounded-card bg-surface-2 p-4 grid gap-2 text-left">
{['account', 'venue', 'ready'].map((k, i) => (
<li key={k} className="flex items-center gap-3 text-label text-ink-2">
<span className="grid place-items-center w-5 h-5 rounded-full bg-accent-soft text-accent-ink text-caption font-semibold">{i + 1}</span>{t(`setup.plan.${k}`)}
</li>
))}
</ol>
<span className="flex flex-wrap justify-center gap-1">
{Object.entries(LANGUAGE_NAMES).map(([code, label]) => (
<Button key={code} size="sm" variant={venue.language === code ? 'primary' : 'ghost'} onClick={() => setLanguage(code)} data-testid={`setup-lang-${code}`}>{label}</Button>
))}
</span>
<Button size="lg" className="w-full" icon={<ArrowRight size={16} />} onClick={next} data-testid="setup-start">{t('setup.start')}</Button>
</div>
)}
{name === 'account' && (
<div className="grid gap-3">
<Header title={t('setup.accountTitle')} intro={t('setup.accountIntro')} />
<Field label={t('setup.username')} required error={err('username')}>
<Input value={account.username} autoFocus autoCapitalize="none" autoComplete="off" onChange={e => setAccount(a => ({ ...a, username: e.target.value }))} data-testid="setup-username" />
</Field>
<Field label={t('setup.fullName')} required error={err('fullName')}>
<Input value={account.fullName} onChange={e => setAccount(a => ({ ...a, fullName: e.target.value }))} data-testid="setup-full-name" />
</Field>
<Field label={t('setup.email')} hint={t('setup.emailHint')} error={err('email')}>
<Input type="email" value={account.email} onChange={e => setAccount(a => ({ ...a, email: e.target.value }))} />
</Field>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('setup.password')} required error={err('password')}>
<Input type="password" autoComplete="new-password" value={account.password} onChange={e => setAccount(a => ({ ...a, password: e.target.value }))} data-testid="setup-password" />
</Field>
<Field label={t('setup.confirm')} required error={err('confirm')}>
<Input type="password" autoComplete="new-password" value={account.confirm} onChange={e => setAccount(a => ({ ...a, confirm: e.target.value }))} data-testid="setup-confirm" />
</Field>
</div>
<Nav onBack={back} onNext={next} />
</div>
)}
{name === 'venue' && (
<div className="grid gap-3">
<Header title={t('setup.venueTitle')} intro={t('setup.venueIntro')} />
<Field label={t('setup.kind')} error={err('types')}>
<span className="grid grid-cols-2 gap-2">
{VENUE_TYPES.map(k => {
const Icon = ICONS[k]
const on = venue.types.includes(k)
return (
<button key={k} type="button" aria-pressed={on} data-testid={`setup-type-${k}`}
onClick={() => setVenue(v => ({ ...v, types: on ? v.types.filter(x => x !== k) : [...v.types, k] }))}
className={cx('relative grid justify-items-center gap-2 rounded-card border-2 p-4 text-label font-medium transition-colors',
on ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{on && <CheckCircle2 size={16} className="absolute top-2 right-2 text-accent" aria-hidden="true" />}
<Icon size={24} aria-hidden="true" />{t(`setup.kinds.${k}`)}
</button>
)
})}
</span>
</Field>
<Field label={t('setup.venueName')} required error={err('name')}>
<Input value={venue.name} placeholder={t('setup.venueNameExample')} onChange={e => setVenue(v => ({ ...v, name: e.target.value }))} data-testid="setup-venue-name" />
</Field>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('setup.language')}>
<Select value={venue.language} onChange={e => setLanguage(e.target.value)} data-testid="setup-language"
options={Object.entries(LANGUAGE_NAMES).map(([code, label]) => ({ value: code, label }))} />
</Field>
<Field label={t('setup.timezone')}>
<Select value={venue.timezone} onChange={e => setVenue(v => ({ ...v, timezone: e.target.value }))} data-testid="setup-timezone"
options={timeZones(venue.timezone).map(z => ({ value: z, label: z.replace(/_/g, ' ') }))} />
</Field>
</div>
<p className="text-label text-ink-2 -mt-1">{t('setup.languageHint')}</p>
<Nav onBack={back} onNext={next} />
</div>
)}
{name === 'pin' && (
<div className="grid gap-3">
<Header title={t('setup.pinTitle')} intro={t('setup.pinIntro')} />
<div className="grid gap-3 grid-cols-2">
<Field label={t('setup.pin')} error={err('pin')}>
<Input type="password" inputMode="numeric" autoComplete="new-password" value={pin.pin} onChange={e => setPin(p => ({ ...p, pin: e.target.value.replace(/\D/g, '').slice(0, 6) }))} data-testid="setup-pin" />
</Field>
<Field label={t('setup.pinAgain')} error={err('again')}>
<Input type="password" inputMode="numeric" autoComplete="new-password" value={pin.again} onChange={e => setPin(p => ({ ...p, again: e.target.value.replace(/\D/g, '').slice(0, 6) }))} data-testid="setup-pin-again" />
</Field>
</div>
<Nav onBack={back} onNext={next} next={pin.pin ? t('setup.next') : t('setup.skip')} />
</div>
)}
{name === 'done' && (
<div className="grid justify-items-center text-center gap-5">
<span className="grid place-items-center w-20 h-20 rounded-card bg-success text-success-fg"><CheckCircle2 size={40} aria-hidden="true" /></span>
<div className="grid gap-2">
<h2 className="text-heading font-bold text-ink">{t('setup.doneTitle')}</h2>
<p className="text-body text-ink-2 max-w-xs">{t('setup.doneIntro')}</p>
</div>
<ul className="w-full rounded-card bg-success-soft p-4 grid gap-2 text-left">
{['menu', 'tables', 'staff'].map(k => <li key={k} className="flex items-center gap-2 text-label text-ink-2"><ArrowRight size={14} className="text-success-ink" aria-hidden="true" />{t(`setup.next3.${k}`)}</li>)}
</ul>
{finish.error && <p className="text-label text-danger-ink" role="alert">{errorMessage(finish.error, t)}</p>}
<span className="flex gap-2 w-full">
<Button variant="ghost" icon={<ChevronLeft size={16} />} onClick={back} disabled={finish.isPending}>{t('setup.back')}</Button>
<Button size="lg" className="flex-1" loading={finish.isPending} onClick={() => finish.mutate()} data-testid="setup-finish">{t('setup.finish')}</Button>
</span>
</div>
)}
</div>
<p className="text-center text-caption text-ink-3">{t('setup.footer')}</p>
</div>
</div>
)
}
function Header({ title, intro }) {
return (
<div className="grid gap-1">
<h2 className="text-title font-bold text-ink">{title}</h2>
<p className="text-label text-ink-2">{intro}</p>
</div>
)
}
function Nav({ onBack, onNext, next }) {
const { t } = useTranslation('manager')
return (
<span className="flex gap-2 pt-1">
<Button variant="ghost" icon={<ChevronLeft size={16} />} onClick={onBack}>{t('setup.back')}</Button>
<Button className="flex-1" onClick={onNext} data-testid="setup-next">{next ?? t('setup.next')}</Button>
</span>
)
}
@@ -0,0 +1,45 @@
// The setup wizard's checks (plan step 6.14b), unit-tested in tests/shell.test.mjs.
export const VENUE_TYPES = ['restaurant', 'bar', 'coffee_shop', 'fast_food']
/** The account step: [field, problem] pairs. */
export function accountProblems(a) {
const out = []
if (!a.username.trim()) out.push(['username', 'required'])
else if (/\s/.test(a.username.trim())) out.push(['username', 'spaces'])
if (!a.fullName.trim()) out.push(['fullName', 'required'])
if (a.email.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.email.trim())) out.push(['email', 'email'])
if (a.password.length < 6) out.push(['password', 'short'])
if (a.password !== a.confirm) out.push(['confirm', 'mismatch'])
return out
}
/** The venue step. */
export function venueProblems(v) {
const out = []
if (!v.types.length) out.push(['types', 'pickOne'])
if (!v.name.trim()) out.push(['name', 'required'])
return out
}
/** The PIN step: empty (no PIN) or 4 to 6 digits, typed twice. */
export function pinProblems(pin, again) {
if (!pin && !again) return []
if (!/^\d{4,6}$/.test(pin)) return [['pin', 'pin']]
if (pin !== again) return [['again', 'pinMismatch']]
return []
}
/** What POST /api/setup/init takes. */
export function setupBody(a, v, pin) {
return {
username: a.username.trim(), password: a.password, email: a.email.trim() || null, full_name: a.fullName.trim(),
venue_type: v.types.join(','), venue_name: v.name.trim(), language: v.language, timezone: v.timezone,
pin: pin || undefined,
}
}
/** The staff language to start from: Greek when the browser is Greek, else English. */
export function startLanguage(browserLanguage) {
return String(browserLanguage ?? '').toLowerCase().startsWith('el') ? 'el' : 'en'
}
@@ -0,0 +1,180 @@
// The dialogs of Management → Tables → List (plan step 6.14b): a table, a zone, many tables at
// once, moving picked tables to a zone, renaming them in a series.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Select, cx } from '@xenia/ui'
import client from '../../api/client'
import { CATEGORY_COLOURS } from '../products/categoryColours'
import { MAX_NAME, nextNumber, series, tableBody, tableProblems } from './tablesLogic'
const ZONE_COLOURS = CATEGORY_COLOURS.slice(0, 10) // the venue's colours (data), as for categories
function useSave(fn, done, onSaved) {
const { t } = useTranslation('manager')
return useMutation({ mutationFn: fn, onSuccess: r => { toast.success(done(r)); onSaved() }, onError: e => toast.error(errorMessage(e, t)) })
}
const zoneOptions = (zones, t) => [{ value: '', label: t('tablesList.noZone') }, ...zones.map(z => ({ value: String(z.id), label: z.prefix ? `${z.name} (${z.prefix})` : z.name }))]
export function TableDialog({ table, zones, zoneId, onClose, onSaved }) {
const { t } = useTranslation('manager')
const isNew = !table
const [form, setForm] = useState({ label: table?.label ?? '', group_id: String(table?.group_id ?? zoneId ?? ''), seats: table?.seat_count != null ? String(table.seat_count) : '' })
const [tried, setTried] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const wrong = tableProblems(form)
const save = useSave(body => (isNew ? client.post('/api/tables/', body) : client.put(`/api/tables/${table.id}`, body)), () => t(isNew ? 'tablesList.added' : 'tablesList.saved'), onSaved)
const submit = () => { setTried(true); if (!wrong.length) save.mutate(tableBody(form)) }
return (
<Dialog open size="sm" onClose={onClose} title={isNew ? t('tablesList.newTable') : t('tablesList.edit', { name: table.label || t('tablesList.numbered', { n: table.number }) })}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('tablesList.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="table-save">{t('tablesList.save')}</Button>
</>}>
<div className="grid gap-3" data-testid="table-dialog">
<Field label={t('tablesList.name')} hint={t('tablesList.nameHint', { max: MAX_NAME })} error={tried && wrong.includes('label') ? t('tablesList.nameLong', { max: MAX_NAME }) : undefined}>
<Input value={form.label} autoFocus maxLength={MAX_NAME} placeholder={t('tablesList.nameExample')} onChange={e => set('label', e.target.value)} data-testid="table-name" />
</Field>
<Field label={t('tablesList.zone')}>
<Select value={form.group_id} onChange={e => set('group_id', e.target.value)} options={zoneOptions(zones, t)} data-testid="table-zone" />
</Field>
<Field label={t('tablesList.seatsLabel')} hint={t('tablesList.seatsHint')} error={tried && wrong.includes('seats') ? t('tablesList.seatsWrong') : undefined}>
<Input inputMode="numeric" value={form.seats} onChange={e => set('seats', e.target.value)} className="w-24" />
</Field>
</div>
</Dialog>
)
}
export function ZoneDialog({ zone, onClose, onSaved }) {
const { t } = useTranslation('manager')
const isNew = !zone.id
const [form, setForm] = useState({ name: zone.name ?? '', prefix: zone.prefix ?? '', color: zone.color ?? null })
const [tried, setTried] = useState(false)
const [removing, setRemoving] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const body = () => ({ name: form.name.trim(), prefix: form.prefix.trim() || null, color: form.color })
const save = useSave(b => (isNew ? client.post('/api/tables/groups', b) : client.put(`/api/tables/groups/${zone.id}`, b)), () => t('tablesList.zoneSaved'), onSaved)
const remove = useSave(() => client.delete(`/api/tables/groups/${zone.id}`), () => t('tablesList.zoneDeleted'), onSaved)
const submit = () => { setTried(true); if (form.name.trim()) save.mutate(body()) }
if (removing) {
return (
<Dialog open size="sm" onClose={() => setRemoving(false)} title={t('tablesList.zoneDeleteTitle', { name: zone.name })} description={t('tablesList.zoneDeleteBody')}
footer={<>
<Button variant="secondary" onClick={() => setRemoving(false)}>{t('tablesList.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate()}>{t('tablesList.deleteYes')}</Button>
</>} />
)
}
return (
<Dialog open size="sm" onClose={onClose} title={isNew ? t('tablesList.newZone') : zone.name}
footer={<>
{!isNew && <Button variant="ghost" icon={<Trash2 size={14} />} className="mr-auto" onClick={() => setRemoving(true)}>{t('tablesList.delete')}</Button>}
<Button variant="secondary" onClick={onClose}>{t('tablesList.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="zone-save">{t('tablesList.save')}</Button>
</>}>
<div className="grid gap-3" data-testid="zone-dialog">
<Field label={t('tablesList.zoneName')} required error={tried && !form.name.trim() ? t('tablesList.zoneNameNeeded') : undefined}>
<Input value={form.name} autoFocus placeholder={t('tablesList.zoneExample')} onChange={e => set('name', e.target.value)} data-testid="zone-name" />
</Field>
<Field label={t('tablesList.prefix')} hint={t('tablesList.prefixHint')}>
<Input value={form.prefix} className="font-mono w-32" onChange={e => set('prefix', e.target.value)} data-testid="zone-prefix" />
</Field>
<Field label={t('tablesList.colour')}>
<span className="flex flex-wrap gap-1.5">
<button type="button" onClick={() => set('color', null)} aria-pressed={!form.color} aria-label={t('tablesList.noColour')}
className={cx('w-7 h-7 rounded-full bg-surface-3 border-2', !form.color ? 'border-ink' : 'border-transparent')} />
{ZONE_COLOURS.map(c => (
<button key={c} type="button" onClick={() => set('color', c)} aria-pressed={form.color === c} aria-label={c}
className={cx('w-7 h-7 rounded-full border-2', form.color === c ? 'border-ink' : 'border-transparent')} style={{ background: c }} />
))}
</span>
</Field>
</div>
</Dialog>
)
}
export function BatchDialog({ zone, tables, onClose, onSaved }) {
const { t } = useTranslation('manager')
const [prefix, setPrefix] = useState(zone.prefix ? `${zone.prefix}-` : '')
const [count, setCount] = useState('5')
const n = Number(count)
const start = nextNumber(tables, zone.id, prefix.trim())
const s = series(prefix, start, n || 0)
const ok = prefix.trim() && n >= 1 && n <= 200 && !s.tooLong
const save = useSave(() => client.post('/api/tables/batch', { group_id: zone.id, count: n, name_prefix: prefix.trim() }).then(r => r.data),
r => t('tablesList.addedMany', { count: r.length }), onSaved)
return (
<Dialog open size="sm" onClose={onClose} title={t('tablesList.addMany')} description={t('tablesList.inZone', { name: zone.name })}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('tablesList.back')}</Button>
<Button disabled={!ok} loading={save.isPending} onClick={() => save.mutate()} data-testid="batch-save">
{ok ? t('tablesList.addSeries', { from: s.names[0], to: s.last }) : t('tablesList.add')}
</Button>
</>}>
<div className="grid gap-3" data-testid="batch-dialog">
<Field label={t('tablesList.prefix')} hint={s.tooLong ? undefined : t('tablesList.batchHint')} error={s.tooLong ? t('tablesList.seriesLong', { last: s.last, max: MAX_NAME }) : undefined}>
<Input value={prefix} autoFocus className="font-mono" onChange={e => setPrefix(e.target.value)} data-testid="batch-prefix" />
</Field>
<Field label={t('tablesList.howMany')}>
<Input inputMode="numeric" value={count} className="w-24" onChange={e => setCount(e.target.value.replace(/\D/g, ''))} data-testid="batch-count" />
</Field>
</div>
</Dialog>
)
}
export function MoveDialog({ count, zones, onClose, onMove }) {
const { t } = useTranslation('manager')
const [groupId, setGroupId] = useState('')
const [busy, setBusy] = useState(false)
return (
<Dialog open size="sm" onClose={onClose} title={t('tablesList.moveTitle', { count })}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('tablesList.back')}</Button>
<Button loading={busy} onClick={() => { setBusy(true); onMove(groupId ? Number(groupId) : null) }}>{t('tablesList.move')}</Button>
</>}>
<Field label={t('tablesList.toZone')}>
<Select value={groupId} autoFocus onChange={e => setGroupId(e.target.value)} options={zoneOptions(zones, t)} />
</Field>
</Dialog>
)
}
export function RenameDialog({ tables, onClose, onRename }) {
const { t } = useTranslation('manager')
const [prefix, setPrefix] = useState('')
const [start, setStart] = useState('1')
const [busy, setBusy] = useState(false)
const s = series(prefix, Math.max(1, Number(start) || 1), tables.length)
const ok = prefix.trim() && !s.tooLong
return (
<Dialog open size="sm" onClose={onClose} title={t('tablesList.renameTitle', { count: tables.length })} description={t('tablesList.renameIntro')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('tablesList.back')}</Button>
<Button disabled={!ok} loading={busy} onClick={() => { setBusy(true); onRename(s.names) }} data-testid="rename-save">{t('tablesList.renameYes', { count: tables.length })}</Button>
</>}>
<div className="grid gap-3" data-testid="rename-dialog">
<div className="grid gap-3 grid-cols-2">
<Field label={t('tablesList.prefix')} error={s.tooLong ? t('tablesList.seriesLong', { last: s.last, max: MAX_NAME }) : undefined}>
<Input value={prefix} autoFocus maxLength={MAX_NAME - 1} className="font-mono" onChange={e => setPrefix(e.target.value)} data-testid="rename-prefix" />
</Field>
<Field label={t('tablesList.startAt')}>
<Input inputMode="numeric" value={start} onChange={e => setStart(e.target.value.replace(/\D/g, ''))} />
</Field>
</div>
{ok && (
<p className="flex flex-wrap gap-1.5 text-label">
{s.names.slice(0, 5).map(x => <span key={x} className="rounded bg-surface-2 px-2 py-0.5 font-mono text-ink">{x}</span>)}
{s.names.length > 5 && <span className="text-ink-3">{t('tablesList.andMore', { count: s.names.length - 5 })}</span>}
</p>
)}
</div>
</Dialog>
)
}
@@ -0,0 +1,188 @@
// Management → Tables → List (plan step 6.14b; was the v1 TablesConfigTab, kept in 6.8a next to
// the floor plans): every table by zone, for typing and changes in bulk. Zones as tabs (drag to
// reorder; a zone's name, prefix and colour; add many tables at once with the zone's prefix,
// numbered on from the last), a table's name (up to 6 characters, empty = numbered by the server),
// zone and seats; names used twice stand out; turn a table off (kept, not used) or delete it (not
// while it has an open order); pick several to move them to a zone, rename them in a series, or
// delete them.
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { GripVertical, Pencil, Plus, Power, Trash2, X } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { BatchDialog, MoveDialog, RenameDialog, TableDialog, ZoneDialog } from './TableDialogs'
import { duplicateNames, reorder, tablesOf } from './tablesLogic'
const LIVE = ['table_list_changed'] // routers/tables.py
export default function TablesListTab() {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const [inactive, setInactive] = useState(false)
const [tab, setTab] = useState('all')
const [picking, setPicking] = useState(false)
const [picked, setPicked] = useState(() => new Set())
const [dialog, setDialog] = useState(null) // { kind, table | zone | ids }
const [drag, setDrag] = useState(null) // { id, gap }
const tablesQ = useLiveQuery({ queryKey: ['tables-all', inactive], events: LIVE, queryFn: () => client.get('/api/tables/', { params: { include_inactive: inactive } }).then(r => r.data) })
const zonesQ = useLiveQuery({ queryKey: ['table-groups'], events: LIVE, queryFn: () => client.get('/api/tables/groups').then(r => r.data) })
const tables = tablesQ.data ?? []
const zones = zonesQ.data ?? []
const changed = () => { for (const k of ['tables-all', 'tables', 'table-groups']) qc.invalidateQueries({ queryKey: [k] }) }
const onError = err => toast.error(errorMessage(err, t))
const close = () => setDialog(null)
const stopPicking = () => { setPicking(false); setPicked(new Set()) }
const shown = tablesOf(tables, tab)
const dupes = duplicateNames(tables)
const allPicked = shown.length > 0 && shown.every(x => picked.has(x.id))
const pick = id => setPicked(p => { const n = new Set(p); if (n.has(id)) n.delete(id); else n.add(id); return n })
const pickAll = () => setPicked(p => { const n = new Set(p); shown.forEach(x => (allPicked ? n.delete(x.id) : n.add(x.id))); return n })
const name = x => x.label || t('tablesList.numbered', { n: x.number })
const update = useMutation({ mutationFn: ({ id, ...body }) => client.put(`/api/tables/${id}`, body), onSuccess: () => { toast.success(t('tablesList.saved')); changed() }, onError })
const remove = useMutation({
mutationFn: ({ id, hard }) => client.delete(`/api/tables/${id}`, { params: { hard } }),
onSuccess: (_r, v) => { toast.success(t(v.hard ? 'tablesList.deleted' : 'tablesList.turnedOff')); close(); changed() }, onError,
})
const reorderZones = useMutation({ mutationFn: ids => client.put('/api/tables/groups/reorder', ids), onSuccess: changed, onError })
/** The same change to many tables, one request each; says how many didn't take. */
const each = async (ids, fn, done) => {
const res = await Promise.allSettled(ids.map(fn))
const failed = res.filter(r => r.status === 'rejected').length
if (failed) toast.error(t('tablesList.someFailed', { count: failed }))
else toast.success(done)
close(); stopPicking(); changed()
}
if (tablesQ.isPending || zonesQ.isPending) return <div className="py-10 flex justify-center"><Spinner /></div>
const tabs = [{ id: 'all', label: t('tablesList.all') }, ...zones.map(z => ({ id: z.id, label: z.prefix ? `${z.prefix} · ${z.name}` : z.name, color: z.color, zone: z })),
...(tables.some(x => !x.group_id) ? [{ id: 'none', label: t('tablesList.noZone') }] : [])]
const count = id => tablesOf(tables, id).length
const zone = zones.find(z => z.id === tab)
const dropOn = (e, i) => { e.preventDefault(); const r = e.currentTarget.getBoundingClientRect(); setDrag(d => d && { ...d, gap: e.clientX < r.left + r.width / 2 ? i : i + 1 }) }
const drop = () => {
if (drag?.gap != null) {
const ids = zones.map(z => z.id)
const next = reorder(ids, drag.id, drag.gap)
if (next.join() !== ids.join()) reorderZones.mutate(next)
}
setDrag(null)
}
return (
<div className="flex flex-col h-full min-h-0" data-testid="tables-list">
<div className="flex flex-wrap items-center gap-2 border-b border-line px-4 md:px-6 py-3 shrink-0">
{picking || picked.size ? (<>
<Button size="sm" variant="ghost" icon={<X size={14} />} onClick={stopPicking}>{picked.size ? t('tablesList.picked', { count: picked.size }) : t('tablesList.pick')}</Button>
<Button size="sm" variant="ghost" onClick={pickAll}>{t(allPicked ? 'tablesList.unpickAll' : 'tablesList.pickAll')}</Button>
{picked.size > 0 && (<>
<Button size="sm" variant="secondary" onClick={() => setDialog({ kind: 'move' })}>{t('tablesList.moveZone')}</Button>
<Button size="sm" variant="secondary" onClick={() => setDialog({ kind: 'rename' })} data-testid="tables-rename">{t('tablesList.renameSeries')}</Button>
<Button size="sm" variant="danger" onClick={() => setDialog({ kind: 'deleteMany' })}>{t('tablesList.delete')}</Button>
</>)}
</>) : (
<span className="text-label text-ink-2">
{t('tablesList.counts', { tables: tables.length, zones: zones.length })}
{tables.some(x => !x.is_active) && <> · <span className="text-warning-ink">{t('tablesList.offCount', { count: tables.filter(x => !x.is_active).length })}</span></>}
</span>
)}
<span className="flex-1" />
<Button size="sm" variant={inactive ? 'primary' : 'secondary'} aria-pressed={inactive} onClick={() => setInactive(v => !v)}>{t('tablesList.showOff')}</Button>
{!picking && <Button size="sm" variant="secondary" onClick={() => setPicking(true)} data-testid="tables-pick">{t('tablesList.pick')}</Button>}
<Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => setDialog({ kind: 'zone', zone: {} })} data-testid="zone-new">{t('tablesList.newZone')}</Button>
<Button size="sm" icon={<Plus size={14} />} onClick={() => setDialog({ kind: 'table', table: null })} data-testid="table-new">{t('tablesList.newTable')}</Button>
</div>
<div className="flex flex-wrap border-b border-line px-4 shrink-0" role="tablist" aria-label={t('tablesList.zones')}>
{tabs.map(x => {
const i = x.zone ? zones.indexOf(x.zone) : -1
return (
<button key={x.id} type="button" role="tab" aria-selected={tab === x.id} onClick={() => { setTab(x.id); setPicked(new Set()) }}
draggable={!!x.zone} onDragStart={x.zone ? () => setDrag({ id: x.id, gap: null }) : undefined}
onDragOver={x.zone ? e => dropOn(e, i) : undefined} onDrop={x.zone ? drop : undefined} onDragEnd={() => setDrag(null)}
className={cx('relative flex items-center gap-1.5 px-4 py-2.5 text-label font-medium border-b-2 -mb-px transition-colors',
tab === x.id ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink',
x.zone && 'cursor-grab', drag?.gap === i && x.zone && 'before:absolute before:left-0 before:top-1 before:bottom-1 before:w-0.5 before:bg-accent',
drag?.gap === i + 1 && x.zone && i === zones.length - 1 && 'after:absolute after:right-0 after:top-1 after:bottom-1 after:w-0.5 after:bg-accent')}
data-testid="zone-tab">
{x.zone && <GripVertical size={12} className="text-ink-3" aria-hidden="true" />}
{x.color && <span className="w-2 h-2 rounded-full shrink-0" style={{ background: x.color }} aria-hidden="true" />}
{x.label}<span className="text-caption text-ink-3">({count(x.id)})</span>
</button>
)
})}
</div>
{zone && (
<div className="flex flex-wrap items-center gap-3 px-4 md:px-6 py-2 border-b border-line shrink-0">
<span className="font-semibold text-ink text-label">{zone.name}</span>
{zone.prefix && <Pill>{zone.prefix}</Pill>}
<Button size="sm" variant="ghost" icon={<Pencil size={13} />} onClick={() => setDialog({ kind: 'zone', zone })}>{t('tablesList.editZone')}</Button>
<Button size="sm" variant="secondary" icon={<Plus size={14} />} className="ml-auto" onClick={() => setDialog({ kind: 'batch', zone })} data-testid="tables-batch">{t('tablesList.addMany')}</Button>
</div>
)}
<div className="flex-1 overflow-y-auto p-4 md:p-6">
{!shown.length ? <EmptyState title={t(inactive ? 'tablesList.none' : 'tablesList.noneActive')} /> : (
<ul className="rounded-card border border-line bg-surface divide-y divide-line overflow-hidden">
{shown.map((x, i) => {
const on = picked.has(x.id)
const busy = x.has_active_order
return (
<li key={x.id} className={cx('flex flex-wrap items-center gap-3 px-4 py-2.5', !x.is_active && 'opacity-60', on && 'bg-accent-soft')} data-testid="table-row" data-name={name(x)}>
{picking || picked.size
? <input type="checkbox" checked={on} onChange={() => pick(x.id)} aria-label={t('tablesList.pickOne', { name: name(x) })} className="w-4 h-4 accent-accent" />
: <span className="w-4 text-caption text-ink-3 tabular-nums text-center">{i + 1}</span>}
<span className="flex-1 min-w-24 font-semibold text-ink">{name(x)}</span>
{x.label && dupes.has(x.label) && <Pill tone="warning">{t('tablesList.duplicate')}</Pill>}
{x.seat_count != null && <span className="text-caption text-ink-2">{t('tablesList.seats', { count: x.seat_count })}</span>}
{tab === 'all' && x.group && <Pill>{x.group.name}</Pill>}
{!x.is_active && <Pill tone="warning">{t('tablesList.off')}</Pill>}
{!picking && !picked.size && (
<span className="flex gap-0.5">
<IconButton size="sm" variant="ghost" label={t('tablesList.edit', { name: name(x) })} onClick={() => setDialog({ kind: 'table', table: x })}><Pencil size={14} /></IconButton>
{x.is_active
? <IconButton size="sm" variant="ghost" disabled={busy} label={busy ? t('tablesList.hasOrder') : t('tablesList.turnOff', { name: name(x) })} onClick={() => setDialog({ kind: 'off', table: x })}><Power size={14} /></IconButton>
: <IconButton size="sm" variant="ghost" label={t('tablesList.turnOn', { name: name(x) })} onClick={() => update.mutate({ id: x.id, is_active: true })}><Power size={14} /></IconButton>}
<IconButton size="sm" variant="ghost" disabled={busy} label={busy ? t('tablesList.hasOrder') : t('tablesList.deleteOne', { name: name(x) })} onClick={() => setDialog({ kind: 'delete', table: x })}><Trash2 size={14} /></IconButton>
</span>
)}
</li>
)
})}
</ul>
)}
</div>
{dialog?.kind === 'table' && <TableDialog table={dialog.table} zones={zones} zoneId={zone?.id} onClose={close} onSaved={() => { close(); changed() }} />}
{dialog?.kind === 'zone' && <ZoneDialog zone={dialog.zone} onClose={close} onSaved={() => { close(); changed() }} />}
{dialog?.kind === 'batch' && <BatchDialog zone={dialog.zone} tables={tables} onClose={close} onSaved={() => { close(); changed() }} />}
{dialog?.kind === 'move' && <MoveDialog count={picked.size} zones={zones} onClose={close}
onMove={groupId => each([...picked], id => client.put(`/api/tables/${id}`, { group_id: groupId }), t('tablesList.moved', { count: picked.size }))} />}
{dialog?.kind === 'rename' && <RenameDialog tables={shown.filter(x => picked.has(x.id))} onClose={close}
onRename={names => { const ids = shown.filter(x => picked.has(x.id)).map(x => x.id); return each(ids, (id, k) => client.put(`/api/tables/${id}`, { label: names[k] }), t('tablesList.renamed', { count: ids.length })) }} />}
{(dialog?.kind === 'off' || dialog?.kind === 'delete') && (
<Dialog open size="sm" onClose={close} title={t(dialog.kind === 'off' ? 'tablesList.offTitle' : 'tablesList.deleteTitle', { name: name(dialog.table) })}
description={t(dialog.kind === 'off' ? 'tablesList.offBody' : 'tablesList.deleteBody')}
footer={<>
<Button variant="secondary" onClick={close}>{t('tablesList.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate({ id: dialog.table.id, hard: dialog.kind === 'delete' })} data-testid="table-delete-confirm">
{t(dialog.kind === 'off' ? 'tablesList.turnOffYes' : 'tablesList.deleteYes')}
</Button>
</>} />
)}
{dialog?.kind === 'deleteMany' && (
<Dialog open size="sm" onClose={close} title={t('tablesList.deleteManyTitle', { count: picked.size })} description={t('tablesList.deleteManyBody')}
footer={<>
<Button variant="secondary" onClick={close}>{t('tablesList.back')}</Button>
<Button variant="danger" onClick={() => each([...picked], id => client.delete(`/api/tables/${id}`, { params: { hard: true } }), t('tablesList.deletedMany', { count: picked.size }))}>{t('tablesList.deleteYes')}</Button>
</>} />
)}
</div>
)
}
@@ -0,0 +1,57 @@
// The rules of Management → Tables → List (plan step 6.14b), unit-tested in tests/tables.test.mjs.
/** A table's name is short, so it fits on the phones' table cards. */
export const MAX_NAME = 6
/** The tables of a tab: 'all', 'none' (no zone) or a zone id. */
export function tablesOf(tables, tab) {
if (tab === 'all') return tables
if (tab === 'none') return tables.filter(t => !t.group_id)
return tables.filter(t => t.group_id === tab)
}
/** Names used by more than one table (the phones couldn't tell them apart). */
export function duplicateNames(tables) {
const n = {}
for (const t of tables) if (t.label) n[t.label] = (n[t.label] ?? 0) + 1
return new Set(Object.keys(n).filter(k => n[k] > 1))
}
/** The next free number after `prefix` in a zone (BS-1, BS-2 → 3). */
export function nextNumber(tables, groupId, prefix) {
if (!prefix) return 1
const used = tables.filter(t => t.group_id === groupId && t.label?.startsWith(prefix))
.map(t => t.label.slice(prefix.length)).filter(s => /^\d+$/.test(s)).map(Number)
return used.length ? Math.max(...used) + 1 : 1
}
/** `count` names from `prefix` + `start`; `tooLong` when the last one is longer than MAX_NAME. */
export function series(prefix, start, count) {
const p = prefix.trim()
const names = Array.from({ length: Math.max(0, count) }, (_, i) => `${p}${start + i}`)
const last = names[names.length - 1] ?? ''
return { names, last, tooLong: last.length > MAX_NAME }
}
/** The order of the zones after dragging `from` (an id) onto position `to` (0 = first). */
export function reorder(ids, from, to) {
const i = ids.indexOf(from)
if (i < 0) return ids
const next = ids.filter(x => x !== from)
next.splice(Math.max(0, Math.min(to > i ? to - 1 : to, next.length)), 0, from)
return next
}
/** What the table form sends: an empty name lets the server number it; seats optional. */
export function tableBody(form) {
const seats = String(form.seats ?? '').trim()
return { label: form.label.trim() || null, group_id: form.group_id ? Number(form.group_id) : null, seat_count: seats ? Number(seats) : null }
}
export function tableProblems(form) {
const out = []
if (form.label.trim().length > MAX_NAME) out.push('label')
const seats = String(form.seats ?? '').trim()
if (seats && !(/^\d+$/.test(seats) && Number(seats) >= 1 && Number(seats) <= 99)) out.push('seats')
return out
}