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
+2 -1
View File
@@ -32,7 +32,8 @@ export default defineConfig([
}, },
}, },
rules: { rules: {
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }], // components in JSX (`icon: Icon` props) count as used
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]', argsIgnorePattern: '^[A-Z_]' }],
// The v2 pages load their data with `useEffect(() => { load() }, [load])` (setState after // The v2 pages load their data with `useEffect(() => { load() }, [load])` (setState after
// a fetch). A warning until phase 6 moves page loading to react-query (already a dependency). // a fetch). A warning until phase 6 moves page loading to react-query (already a dependency).
'react-hooks/set-state-in-effect': 'warn', 'react-hooks/set-state-in-effect': 'warn',
+3 -5
View File
@@ -1,8 +1,6 @@
// `npm run lint` (plan step 6.1): ESLint over the code on the v2 rules (v2.json `paths`), the // `npm run lint` (plan step 6.1; 6.14b: all of src is v2): ESLint over src, the config, the
// config and the tests. `npx eslint src` shows everything, older pages included. // scripts and the tests. v2.json `strict` (eslint.config.js) adds the no-setState-in-effect rule.
import { spawnSync } from 'node:child_process' import { spawnSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
const v2 = JSON.parse(readFileSync(new URL('../v2.json', import.meta.url), 'utf8')) const r = spawnSync('npx', ['eslint', 'eslint.config.js', 'scripts', 'tests', 'src'], { stdio: 'inherit', shell: process.platform === 'win32' })
const r = spawnSync('npx', ['eslint', 'eslint.config.js', 'scripts', 'tests', ...v2.paths], { stdio: 'inherit', shell: process.platform === 'win32' })
process.exit(r.status ?? 1) process.exit(r.status ?? 1)
+25 -40
View File
@@ -1,16 +1,21 @@
import { lazy, Suspense, useEffect, useState } from 'react' // The manager's routes (plan step 6.14b: the shell on v2). Every page sits in the platform
import { BrowserRouter, Routes, Route, Navigate, Outlet, useNavigate } from 'react-router-dom' // bootstrap (modules, keys, venue, language: @xenia/access); signed-in pages in the frame
// (shell/AppLayout) with the live connection. A fresh install (no manager yet) goes to the setup
// wizard; the sign-in page sends you there too.
import { lazy, Suspense } from 'react'
import { useQuery } from '@tanstack/react-query'
import { BrowserRouter, Routes, Route, Navigate, Outlet } from 'react-router-dom'
import { AccessProvider } from '@xenia/access' import { AccessProvider } from '@xenia/access'
import RouteGuard from './shell/RouteGuard'
import { createI18n } from '@xenia/i18n' import { createI18n } from '@xenia/i18n'
import { Spinner } from '@xenia/ui'
import useAuthStore from './store/authStore' import useAuthStore from './store/authStore'
import AppLayout from './layouts/AppLayout' import AppLayout from './shell/AppLayout'
import LiveProvider from './live/LiveProvider' import LiveProvider from './live/LiveProvider'
import client from './api/client' import client from './api/client'
// Auth / setup // Auth / setup
import LoginPage from './pages/LoginPage' import LoginPage from './pages/LoginPage'
import SetupWizard from './pages/SetupWizard' import SetupWizard from './pages/setup/SetupWizard'
// Operation // Operation
import OverviewPage from './pages/overview/OverviewPage' import OverviewPage from './pages/overview/OverviewPage'
@@ -63,37 +68,26 @@ import SettingsPage from './pages/Settings/SettingsPage'
import NotesPage from './pages/notes/NotesPage' import NotesPage from './pages/notes/NotesPage'
// Texts for the shared parts (approval dialog, "feature off" screens, component labels). // Texts for the shared parts (approval dialog, "feature off" screens, component labels).
// The language follows bootstrap (user -> venue); the current pages are still Greek (phase 6). // The language follows bootstrap (user -> venue).
const i18n = createI18n() const i18n = createI18n()
// Visual check pages for the shared packages, dev builds only (left out of production bundles) // Visual check pages for the shared packages, dev builds only (left out of production bundles)
const UiGallery = import.meta.env.DEV ? lazy(() => import('@xenia/ui/gallery')) : null const UiGallery = import.meta.env.DEV ? lazy(() => import('@xenia/ui/gallery')) : null
const I18nSample = import.meta.env.DEV ? lazy(() => import('@xenia/i18n/sample')) : null const I18nSample = import.meta.env.DEV ? lazy(() => import('@xenia/i18n/sample')) : null
function Spinner() { function Loading() {
return ( return <div className="min-h-screen bg-canvas grid place-items-center"><Spinner /></div>
<div className="min-h-screen bg-slate-50 flex items-center justify-center">
<div className="w-6 h-6 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
</div>
)
} }
/** A token kept from an earlier visit: who it belongs to (else it is dropped and you sign in again). */
function AuthRehydrator({ children }) { function AuthRehydrator({ children }) {
const { token, user, rehydrate, logout } = useAuthStore() const { token, user, rehydrate, logout } = useAuthStore()
const [ready, setReady] = useState(false) const needed = !!token && !user
const { isPending } = useQuery({
useEffect(() => { queryKey: ['auth-me', token], enabled: needed, retry: false, staleTime: Infinity,
if (token && !user) { queryFn: () => client.get('/api/auth/me').then(r => { rehydrate(r.data, token); return r.data }).catch(e => { logout(); throw e }),
client.get('/api/auth/me') })
.then(r => { rehydrate(r.data, token) }) if (needed && isPending) return <Loading />
.catch(() => { logout() })
.finally(() => setReady(true))
} else {
setReady(true)
}
}, []) // intentionally runs once on mount
if (!ready) return <Spinner />
return children return children
} }
@@ -102,20 +96,11 @@ function RequireAuth({ children }) {
return token ? children : <Navigate to="/login" replace /> return token ? children : <Navigate to="/login" replace />
} }
/** The sign-in page, unless nobody can sign in yet (a fresh install): then the setup wizard. */
function SetupGuard({ children }) { function SetupGuard({ children }) {
const [checked, setChecked] = useState(false) const { data, isPending } = useQuery({ queryKey: ['setup-status'], retry: false, queryFn: () => client.get('/api/setup/status').then(r => r.data) })
const navigate = useNavigate() if (isPending) return <Loading />
if (data?.needs_setup) return <Navigate to="/setup" replace />
useEffect(() => {
client.get('/api/setup/status')
.then(({ data }) => {
if (data.needs_setup) navigate('/setup', { replace: true })
})
.catch(() => {})
.finally(() => setChecked(true))
}, [navigate])
if (!checked) return <Spinner />
return children return children
} }
@@ -124,7 +109,7 @@ function SetupGuard({ children }) {
function ManagerRoot() { function ManagerRoot() {
const token = useAuthStore(s => s.token) const token = useAuthStore(s => s.token)
return ( return (
<AccessProvider client={client} token={token} i18n={i18n} loading={<Spinner />}> <AccessProvider client={client} token={token} i18n={i18n} loading={<Loading />}>
<AuthRehydrator> <AuthRehydrator>
<Outlet /> <Outlet />
</AuthRehydrator> </AuthRehydrator>
@@ -1,166 +0,0 @@
import { useState } from 'react'
import Modal from '../ui/Modal'
import Button from '../ui/Button'
import { LabelledInput } from '../ui/Input'
import client from '../api/client'
import useAuthStore from '../store/authStore'
export default function EditProfileModal({ onClose }) {
const { user, updateUser } = useAuthStore()
const [fullName, setFullName] = useState(user?.full_name || '')
const [username, setUsername] = useState(user?.username || '')
const [currentPassword, setCurrentPassword] = useState('')
const [newPassword, setNewPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [newPin, setNewPin] = useState('')
const [confirmPin, setConfirmPin] = useState('')
const [error, setError] = useState('')
const [saving, setSaving] = useState(false)
const passwordTouched = currentPassword || newPassword || confirmPassword
const pinTouched = newPin || confirmPin
function validate() {
if (passwordTouched) {
if (!currentPassword) return 'Enter your current password.'
if (!newPassword) return 'Enter a new password.'
if (newPassword.length < 6) return 'New password must be at least 6 characters.'
if (newPassword !== confirmPassword) return 'New passwords do not match.'
}
if (pinTouched) {
if (newPin.length < 4) return 'PIN must be 4 digits.'
if (newPin !== confirmPin) return 'PINs do not match.'
}
if (!username.trim()) return 'Username cannot be empty.'
return null
}
async function handleSave() {
const validationError = validate()
if (validationError) { setError(validationError); return }
const body = {}
if (fullName !== (user?.full_name || '')) body.full_name = fullName
if (username !== user?.username) body.username = username
if (passwordTouched) {
body.current_password = currentPassword
body.new_password = newPassword
}
if (pinTouched) {
body.new_pin = newPin
}
if (Object.keys(body).length === 0) { onClose(); return }
setError('')
setSaving(true)
try {
const { data } = await client.patch('/api/auth/me', body)
updateUser(data)
onClose()
} catch (err) {
const detail = err.response?.data?.detail
setError(typeof detail === 'string' ? detail : 'Failed to save changes.')
} finally {
setSaving(false)
}
}
function onlyDigits(val, max) {
return val.replace(/\D/g, '').slice(0, max)
}
return (
<Modal title="Edit Profile" onClose={onClose} maxWidth="max-w-lg">
<div className="space-y-4">
<div className="space-y-2">
<LabelledInput
label="Display Name"
value={fullName}
onChange={e => setFullName(e.target.value)}
placeholder="e.g. Maria Papadopoulou"
/>
<LabelledInput
label="Username"
value={username}
onChange={e => setUsername(e.target.value)}
autoComplete="off"
/>
</div>
<div className="border-t border-slate-100" />
<div className="space-y-2">
<p className="text-[11px] font-semibold uppercase tracking-wider text-slate-400">
Change Password <span className="normal-case font-normal">(leave blank to keep current)</span>
</p>
<LabelledInput
label="Current Password"
type="password"
value={currentPassword}
onChange={e => setCurrentPassword(e.target.value)}
autoComplete="current-password"
/>
<LabelledInput
label="New Password"
type="password"
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
autoComplete="new-password"
/>
<LabelledInput
label="Confirm New Password"
type="password"
value={confirmPassword}
onChange={e => setConfirmPassword(e.target.value)}
autoComplete="new-password"
/>
</div>
<div className="border-t border-slate-100" />
<div className="space-y-2">
<p className="text-[11px] font-semibold uppercase tracking-wider text-slate-400">
Change PIN <span className="normal-case font-normal">(leave blank to keep current)</span>
</p>
<div className="flex gap-2">
<LabelledInput
label="New PIN"
type="password"
inputMode="numeric"
value={newPin}
onChange={e => setNewPin(onlyDigits(e.target.value, 4))}
placeholder="••••"
className="flex-1"
/>
<LabelledInput
label="Confirm PIN"
type="password"
inputMode="numeric"
value={confirmPin}
onChange={e => setConfirmPin(onlyDigits(e.target.value, 4))}
placeholder="••••"
className="flex-1"
/>
</div>
</div>
{error && (
<p className="text-[12px] text-rose-500">{error}</p>
)}
</div>
<Modal.Footer>
<Button variant="secondary" onClick={onClose} disabled={saving}>Cancel</Button>
<Button variant="primary" onClick={handleSave} disabled={saving}>
{saving ? 'Saving…' : 'Save Changes'}
</Button>
</Modal.Footer>
</Modal>
)
}
@@ -80,7 +80,7 @@ export default function NotificationBell() {
<div className="relative" ref={ref}> <div className="relative" ref={ref}>
<button <button
onClick={() => { setOpen(o => !o); if (!open) load() }} onClick={() => { setOpen(o => !o); if (!open) load() }}
className="relative flex h-8 w-8 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-700" className="relative flex h-8 w-8 items-center justify-center rounded-lg border border-line bg-surface text-ink-3 transition hover:bg-surface-2 hover:text-ink"
aria-label={data.unread ? t('notifications.bellUnread', { count: data.unread }) : t('notifications.bell')} aria-label={data.unread ? t('notifications.bellUnread', { count: data.unread }) : t('notifications.bell')}
aria-haspopup="dialog" aria-haspopup="dialog"
aria-expanded={open} aria-expanded={open}
@@ -1,220 +0,0 @@
import { NavLink, useLocation } from 'react-router-dom'
import { useState, useEffect } from 'react'
import { ChevronDown } from 'lucide-react'
import { useAccess } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { getIncomingOrders } from '../api/client'
import { NAV, NAV_BOTTOM, canSee } from '../shell/nav'
// The sidebar is drawn from shell/nav.js: an item shows when its module is on and the user
// holds its key (platform bootstrap, @xenia/access). Plan step 2.6a; this replaces the
// browser-only feature toggles (F-033).
// ─── Helpers ──────────────────────────────────────────────────────────────────
function isChildActive(children, pathname) {
return children.some(c => pathname === c.to || pathname.startsWith(c.to + '/'))
}
// ─── Child link ───────────────────────────────────────────────────────────────
function ChildLink({ to, icon: Icon, label, placeholder }) {
const { t } = useTranslation('manager')
if (placeholder) {
return (
<div className="flex items-center gap-2.5 px-3 py-2 mx-2 rounded-md text-[13px] text-primary-400 cursor-default select-none">
<Icon size={14} className="shrink-0 opacity-50" />
<span>{t(label)}</span>
<span className="ml-auto text-[10px] font-semibold bg-primary-700 text-primary-300 px-1.5 py-0.5 rounded">{t('nav.soon')}</span>
</div>
)
}
return (
<NavLink
to={to}
end
className={({ isActive }) =>
`flex items-center gap-2.5 px-3 py-2 mx-2 rounded-md text-[13px] font-medium transition-colors ` +
(isActive
? 'bg-primary-600 text-white'
: 'text-primary-200 hover:bg-primary-700 hover:text-white')
}
>
{({ isActive }) => (
<>
<Icon size={14} className="shrink-0" />
<span>{t(label)}</span>
{isActive && <span className="ml-auto w-1 h-1 rounded-full bg-sky-400 shrink-0" />}
</>
)}
</NavLink>
)
}
// ─── Group item (collapsible parent) ─────────────────────────────────────────
function GroupItem({ group, icon: Icon, label, children, openGroup, onToggle }) {
const { t } = useTranslation('manager')
const location = useLocation()
const hasActive = isChildActive(children, location.pathname)
const isOpen = openGroup === group
return (
<div>
<button
onClick={() => onToggle(group)}
className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ` +
(hasActive
? 'text-white bg-primary-700'
: 'text-primary-100 hover:bg-primary-700 hover:text-white')}
>
<Icon size={18} className="shrink-0" />
<span className="flex-1 text-left">{t(label)}</span>
<ChevronDown
size={14}
className={`shrink-0 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}
/>
</button>
{isOpen && (
<div className="mt-0.5 mb-1 space-y-0.5 py-1 border-l border-primary-600 ml-5">
{children.map(child => (
<ChildLink key={child.to} {...child} />
))}
</div>
)}
</div>
)
}
// ─── Solo item (direct link) ──────────────────────────────────────────────────
function SoloItem({ to, icon: Icon, label, badge, onNavigate }) {
const { t } = useTranslation('manager')
return (
<NavLink
to={to}
end
onClick={onNavigate}
className={({ isActive }) =>
`flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ` +
(isActive ? 'bg-primary-600 text-white' : 'text-primary-100 hover:bg-primary-700 hover:text-white')
}
>
<div className="relative shrink-0">
<Icon size={18} />
{badge > 0 && (
<span className="absolute -top-1.5 -right-1.5 bg-red-500 text-white text-[10px] font-bold w-4 h-4 rounded-full flex items-center justify-center leading-none">
{badge > 9 ? '9+' : badge}
</span>
)}
</div>
<span>{t(label)}</span>
</NavLink>
)
}
// ─── Sidebar ──────────────────────────────────────────────────────────────────
/** The sections with only what this user may see (empty groups and sections dropped). */
function visibleNav(access) {
return NAV
.map(section => ({
...section,
items: section.items
.map(item => (item.children
? { ...item, children: item.children.filter(c => canSee(c, access)) }
: item))
.filter(item => (item.children ? item.children.length > 0 : canSee(item, access))),
}))
.filter(section => section.items.length > 0)
}
export default function Sidebar() {
const { t } = useTranslation('manager')
const access = useAccess()
const [pendingCount, setPendingCount] = useState(0)
const [openGroup, setOpenGroup] = useState(null)
const location = useLocation()
const nav = visibleNav(access)
const onlineOrdersShown = nav.some(s => s.items.some(i => i.badge === 'onlineOrders'))
// Online orders badge (only while that page is available)
useEffect(() => {
if (!onlineOrdersShown) return undefined
async function fetchPending() {
try {
const { data } = await getIncomingOrders()
setPendingCount(data.length)
} catch { /* non-critical */ }
}
fetchPending()
const timer = setInterval(fetchPending, 20_000)
return () => clearInterval(timer)
}, [onlineOrdersShown])
// Auto-open the group that contains the active route on location change
useEffect(() => {
for (const section of NAV) {
for (const item of section.items) {
if (item.children && isChildActive(item.children, location.pathname)) {
setOpenGroup(item.group)
return
}
}
}
}, [location.pathname])
function handleGroupToggle(id) {
setOpenGroup(prev => (prev === id ? null : id))
}
function handleSoloClick() {
setOpenGroup(null)
}
return (
<aside className="flex flex-col bg-primary-800 text-white shrink-0 w-56 h-full sidebar-scroll" data-testid="sidebar">
{/* Brand */}
<div className="flex items-center px-4 py-4 border-b border-primary-700 shrink-0">
<span className="font-bold text-lg tracking-wide">XeniaPOS</span>
</div>
{/* Main nav */}
<nav className="flex-1 py-3 px-2 space-y-4">
{nav.map(({ section, items }) => (
<div key={section}>
<div className="flex items-center gap-2 px-3 mb-1.5 select-none" style={{ opacity: 0.45 }}>
<span className="text-[9.5px] font-bold uppercase tracking-widest text-primary-100 whitespace-nowrap">
{t(section)}
</span>
<div className="flex-1" style={{ height: 1, background: 'rgba(255,255,255,0.2)' }} />
</div>
<div className="space-y-0.5">
{items.map(item =>
item.children ? (
<GroupItem key={item.group} {...item} openGroup={openGroup} onToggle={handleGroupToggle} />
) : (
<SoloItem
key={item.to}
{...item}
badge={item.badge === 'onlineOrders' ? pendingCount : undefined}
onNavigate={handleSoloClick}
/>
)
)}
</div>
</div>
))}
</nav>
{/* Divider + bottom items */}
<div className="shrink-0 px-2 pb-3 border-t border-primary-700 pt-3 space-y-0.5">
{NAV_BOTTOM.filter(item => canSee(item, access)).map(item => (
<SoloItem key={item.to} {...item} onNavigate={handleSoloClick} />
))}
</div>
</aside>
)
}
@@ -50,28 +50,28 @@ export default function UserMenuButton({ displayName, onEditProfile, onSignOut }
<div className="relative" ref={ref}> <div className="relative" ref={ref}>
<button <button
onClick={() => setOpen(o => !o)} onClick={() => setOpen(o => !o)}
className="flex items-center gap-1 text-[13px] text-slate-600 font-medium hover:text-slate-900 transition-colors" className="flex items-center gap-1 text-[13px] text-ink-2 font-medium hover:text-ink transition-colors"
aria-haspopup="menu" aria-haspopup="menu"
aria-expanded={open} aria-expanded={open}
data-testid="user-menu" data-testid="user-menu"
> >
{displayName} {displayName}
<ChevronDown className={`h-3.5 w-3.5 text-slate-400 transition-transform ${open ? 'rotate-180' : ''}`} /> <ChevronDown className={`h-3.5 w-3.5 text-ink-3 transition-transform ${open ? 'rotate-180' : ''}`} />
</button> </button>
{open && ( {open && (
<div className="absolute right-0 top-full mt-1.5 w-52 rounded-xl border border-slate-200 bg-white shadow-lg py-1 z-50" role="menu"> <div className="absolute right-0 top-full mt-1.5 w-52 rounded-xl border border-line bg-surface shadow-lg py-1 z-50" role="menu">
<button <button
role="menuitem" role="menuitem"
onClick={() => { setOpen(false); onEditProfile() }} onClick={() => { setOpen(false); onEditProfile() }}
className="flex w-full items-center gap-2.5 px-3.5 py-2 text-[13px] text-slate-700 hover:bg-slate-50 transition-colors" className="flex w-full items-center gap-2.5 px-3.5 py-2 text-[13px] text-ink hover:bg-surface-2 transition-colors"
> >
<User className="h-3.5 w-3.5 text-slate-400" /> <User className="h-3.5 w-3.5 text-ink-3" />
{t('profile.edit')} {t('profile.edit')}
</button> </button>
<div className="my-1 border-t border-slate-100" /> <div className="my-1 border-t border-line" />
<div className="flex items-center gap-2.5 px-3.5 pt-1.5 pb-1 text-[11px] font-semibold uppercase tracking-wide text-slate-400"> <div className="flex items-center gap-2.5 px-3.5 pt-1.5 pb-1 text-[11px] font-semibold uppercase tracking-wide text-ink-3">
<Languages className="h-3.5 w-3.5" /> <Languages className="h-3.5 w-3.5" />
{t('profile.language')} {t('profile.language')}
</div> </div>
@@ -82,18 +82,18 @@ export default function UserMenuButton({ displayName, onEditProfile, onSignOut }
aria-checked={lng === language} aria-checked={lng === language}
lang={lng} lang={lng}
onClick={() => chooseLanguage(lng)} onClick={() => chooseLanguage(lng)}
className="flex w-full items-center gap-2.5 px-3.5 py-2 pl-9 text-[13px] text-slate-700 hover:bg-slate-50 transition-colors" className="flex w-full items-center gap-2.5 px-3.5 py-2 pl-9 text-[13px] text-ink hover:bg-surface-2 transition-colors"
> >
<span className="flex-1 text-left">{LANGUAGE_NAMES[lng]}</span> <span className="flex-1 text-left">{LANGUAGE_NAMES[lng]}</span>
{lng === language && <Check className="h-3.5 w-3.5 text-primary-700" />} {lng === language && <Check className="h-3.5 w-3.5 text-accent-ink" />}
</button> </button>
))} ))}
<div className="my-1 border-t border-slate-100" /> <div className="my-1 border-t border-line" />
<button <button
role="menuitem" role="menuitem"
onClick={() => { setOpen(false); onSignOut() }} onClick={() => { setOpen(false); onSignOut() }}
className="flex w-full items-center gap-2.5 px-3.5 py-2 text-[13px] text-rose-500 hover:bg-rose-50 transition-colors" className="flex w-full items-center gap-2.5 px-3.5 py-2 text-[13px] text-danger-ink hover:bg-danger-soft transition-colors"
> >
<LogOut className="h-3.5 w-3.5" /> <LogOut className="h-3.5 w-3.5" />
{t('profile.signOut')} {t('profile.signOut')}
+7 -45
View File
@@ -19,38 +19,11 @@
@layer base { @layer base {
body { body {
@apply bg-slate-50 text-slate-900 text-base antialiased; @apply bg-canvas text-ink text-base antialiased;
} }
} }
@layer components { /* The side rail's scrollbar (shell/Sidebar): room kept so nothing shifts, it shows on hover */
.btn {
@apply inline-flex items-center justify-center px-4 py-2.5 rounded-xl font-semibold text-sm transition-colors min-h-[44px] disabled:opacity-40 disabled:cursor-not-allowed;
}
.btn-primary {
@apply bg-primary-700 hover:bg-primary-800 text-white;
}
.btn-secondary {
@apply bg-gray-200 hover:bg-gray-300 text-gray-700;
}
.btn-danger {
@apply bg-red-600 hover:bg-red-700 text-white;
}
.btn-ghost {
@apply bg-transparent hover:bg-gray-100 text-gray-600;
}
.card {
@apply bg-white rounded-2xl shadow-sm border border-gray-100;
}
.input {
@apply w-full border border-gray-300 rounded-xl px-4 py-2.5 text-base focus:outline-none focus:ring-2 focus:ring-primary-600 disabled:bg-gray-50;
}
.label {
@apply block text-sm font-medium text-gray-700 mb-1;
}
}
/* Sidebar scrollbar — pre-allocates gutter so content never shifts, fades in on hover */
.sidebar-scroll { .sidebar-scroll {
overflow-y: auto; overflow-y: auto;
overflow-x: hidden; overflow-x: hidden;
@@ -60,20 +33,9 @@
transition: scrollbar-color 0.25s; transition: scrollbar-color 0.25s;
} }
.sidebar-scroll:hover { .sidebar-scroll:hover {
scrollbar-color: rgba(255,255,255,0.22) transparent; scrollbar-color: rgb(var(--x-nav-ink-rgb) / 0.22) transparent;
}
/* Webkit */
.sidebar-scroll::-webkit-scrollbar {
width: 4px;
}
.sidebar-scroll::-webkit-scrollbar-track {
background: transparent;
}
.sidebar-scroll::-webkit-scrollbar-thumb {
background: transparent;
border-radius: 99px;
transition: background 0.25s;
}
.sidebar-scroll:hover::-webkit-scrollbar-thumb {
background: rgba(255,255,255,0.22);
} }
.sidebar-scroll::-webkit-scrollbar { width: 4px; }
.sidebar-scroll::-webkit-scrollbar-track { background: transparent; }
.sidebar-scroll::-webkit-scrollbar-thumb { background: transparent; border-radius: 99px; transition: background 0.25s; }
.sidebar-scroll:hover::-webkit-scrollbar-thumb { background: rgb(var(--x-nav-ink-rgb) / 0.22); }
-309
View File
@@ -1,309 +0,0 @@
import { Outlet, useNavigate, useLocation } from 'react-router-dom'
import { useState, useEffect, useRef, createContext } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Lock, AlertTriangle, ShieldAlert, Search, ChevronRight } from 'lucide-react'
import NotificationBell from '../components/NotificationBell'
import Sidebar from '../components/Sidebar'
import useAuthStore from '../store/authStore'
import client from '../api/client'
import UserMenuButton from '../components/UserMenuButton'
import EditProfileModal from '../components/EditProfileModal'
import useLicenseStatus from '../hooks/useLicenseStatus'
import PhoneListener from '../components/PhoneListener'
import { useTranslation } from '@xenia/i18n'
import { pageFor } from '../shell/nav'
import RouteGuard from '../shell/RouteGuard'
import { errorMessage, isError } from '@xenia/api'
import { PinPad } from '@xenia/ui'
export const LicenseContext = createContext(null)
// ─── Page title / breadcrumb (from shell/nav.js) ─────────────────────────────
function PageTitle() {
const { pathname } = useLocation()
const { t } = useTranslation('manager')
const page = pageFor(pathname)
if (!page) return <span className="text-[15px] font-semibold text-slate-800">XeniaPOS</span>
if (!page.parent) return <span className="text-[15px] font-semibold text-slate-800">{t(page.label)}</span>
return (
<nav className="flex items-center gap-1.5">
<span className="text-[13px] text-slate-400 font-medium">{t(page.parent)}</span>
<ChevronRight size={13} className="text-slate-300 shrink-0" />
<span className="text-[14px] font-semibold text-slate-800">{t(page.label)}</span>
</nav>
)
}
// ─── License Banner ───────────────────────────────────────────────────────────
function LicenseBanner({ license }) {
const { lock_reason, locked, lock_pending, days_until_expiry, expires_at,
grace_days_remaining, showExpiryWarning, inGracePeriod, isBlocked,
sync_failed, offline_days, longOffline } = license
// Renewal needs the cloud: say so whenever the site can't reach it right now
const connectHint = sync_failed ? ' Συνδέστε τον server στο internet για να ανανεωθεί.' : ''
function fmtDate(iso) {
if (!iso) return ''
try {
return new Date(iso).toLocaleDateString('el-GR', { day: '2-digit', month: '2-digit', year: 'numeric' })
} catch { return iso }
}
if (lock_reason === 'admin') {
return (
<div className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white text-[13px] font-medium">
<ShieldAlert className="h-4 w-4 shrink-0" />
{locked
? 'Το σύστημα έχει κλειδωθεί από διαχειριστή. Επικοινωνήστε με την υποστήριξη.'
: 'Εκκρεμεί κλείδωμα από διαχειριστή — θα ενεργοποιηθεί μετά το κλείσιμο της τρέχουσας ημέρας.'}
</div>
)
}
if (lock_reason === 'clock') {
return (
<div className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white text-[13px] font-medium">
<ShieldAlert className="h-4 w-4 shrink-0" />
Η ώρα του server έχει γυρίσει πίσω. Διορθώστε την ημερομηνία/ώρα του server ή συνδέστε τον στο internet.
</div>
)
}
if (lock_reason === 'unverified') {
return (
<div className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white text-[13px] font-medium">
<ShieldAlert className="h-4 w-4 shrink-0" />
Δεν υπάρχει επιβεβαιωμένη άδεια χρήσης. Συνδέστε τον server στο internet για να ενεργοποιηθεί.
</div>
)
}
if (isBlocked && lock_reason === 'expired') {
const daysAgo = days_until_expiry != null ? Math.abs(days_until_expiry) : '?'
return (
<div className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white text-[13px] font-medium">
<ShieldAlert className="h-4 w-4 shrink-0" />
Η άδεια χρήσης έληξε πριν {daysAgo} {daysAgo === 1 ? 'μέρα' : 'μέρες'} ({fmtDate(expires_at)}). Ανανεώστε την άδεια ή επικοινωνήστε με την υποστήριξη.{connectHint}
</div>
)
}
if (inGracePeriod) {
const daysAgo = days_until_expiry != null ? Math.abs(days_until_expiry) : '?'
const remaining = grace_days_remaining ?? '?'
return (
<div className="flex items-center gap-2 px-4 py-2 bg-orange-500 text-white text-[13px] font-medium">
<AlertTriangle className="h-4 w-4 shrink-0" />
Η άδεια χρήσης έληξε στις {fmtDate(expires_at)} (πριν {daysAgo} {daysAgo === 1 ? 'μέρα' : 'μέρες'}). Απομένουν {remaining} {remaining === 1 ? 'μέρα' : 'μέρες'} περιόδου χάριτος. Ανανεώστε την άδεια για να αποφύγετε το κλείδωμα.{connectHint}
</div>
)
}
if (showExpiryWarning) {
const days = days_until_expiry
return (
<div className="flex items-center gap-2 px-4 py-2 bg-amber-50 border-b border-amber-200 text-amber-700 text-[13px] font-medium">
<AlertTriangle className="h-4 w-4 shrink-0" />
Η άδεια χρήσης λήγει σε {days} {days === 1 ? 'μέρα' : 'μέρες'} ({fmtDate(expires_at)}). Ανανεώστε έγκαιρα.{connectHint}
</div>
)
}
// Informational: the license keeps working offline, but renewal needs the cloud
if (longOffline) {
return (
<div className="flex items-center gap-2 px-4 py-2 bg-slate-50 border-b border-slate-200 text-slate-600 text-[13px] font-medium">
<AlertTriangle className="h-4 w-4 shrink-0" />
Χωρίς σύνδεση με το cloud εδώ και {offline_days} μέρες. Το σύστημα λειτουργεί κανονικά — η άδεια ισχύει έως {fmtDate(expires_at)}.
</div>
)
}
return null
}
// ─── Lock Screen ──────────────────────────────────────────────────────────────
// The lock screen checks the PIN of the user who owns THIS session (POST /api/auth/unlock,
// plan step 2.6b): no new login, no new token. Five wrong tries end the session.
function LockScreen({ displayName, onUnlock, onLogout }) {
const { t } = useTranslation('manager')
const [error, setError] = useState('')
async function tryPin(pin) {
try {
const { data } = await client.post('/api/auth/unlock', { pin }, { xenia: { ignoreUnauthorized: true } })
setError('')
onUnlock(data.user)
return true
} catch (err) {
if (isError(err, 'auth.session_ended')) { onLogout(); return true }
setError(errorMessage(err, t))
return false
}
}
return (
<div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/80 backdrop-blur-md" data-testid="lock-screen">
<div className="bg-surface rounded-dialog shadow-overlay p-8 w-full max-w-xs text-center grid gap-4">
<div className="grid gap-1 justify-items-center">
<div className="flex h-12 w-12 items-center justify-center rounded-card bg-surface-2">
<Lock className="h-6 w-6 text-ink-3" />
</div>
<p className="text-body-lg font-bold text-ink">{t('lock.title')}</p>
<p className="text-label text-ink-2">{displayName}</p>
</div>
<PinPad minLength={4} maxLength={8} error={error || undefined} onComplete={tryPin} />
<button onClick={onLogout} className="text-label text-ink-3 hover:text-ink-2 transition-colors">
{t('lock.signOutInstead')}
</button>
</div>
</div>
)
}
// ─── AppLayout ────────────────────────────────────────────────────────────────
export default function AppLayout() {
const { user, savedUsername, logout, lock, unlock, locked } = useAuthStore()
const [profileOpen, setProfileOpen] = useState(false)
const navigate = useNavigate()
const license = useLicenseStatus()
const { data: securitySettings = null } = useQuery({
queryKey: ['pos-settings'],
queryFn: () => client.get('/api/settings/').then(r => r.data),
staleTime: 10_000,
})
const stateRef = useRef({})
stateRef.current = { user, locked, securitySettings, logout, lock, navigate }
const lastActivityRef = useRef(Date.now())
useEffect(() => {
function onActivity() { lastActivityRef.current = Date.now() }
const EVENTS = ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll', 'click']
EVENTS.forEach(ev => window.addEventListener(ev, onActivity, { passive: true }))
const id = setInterval(() => {
const { user, locked, securitySettings, logout, lock, navigate } = stateRef.current
const idle = (Date.now() - lastActivityRef.current) / 1000
if (!user || !securitySettings) return
const get = (key, fb) => securitySettings?.[key]?.value ?? fb
const autoLock = get('security.auto_lock', 'false') === 'true'
const autoLogout = get('security.auto_logout', 'false') === 'true'
if (!autoLock && !autoLogout) return
const lockSecs = autoLock ? parseInt(get('security.auto_lock_seconds', '300'), 10) : Infinity
const logoutSecs = autoLogout ? parseInt(get('security.auto_logout_seconds', '1800'), 10) : Infinity
if (idle >= logoutSecs) {
logout()
navigate('/login', { replace: true, state: { manualLogout: true } })
return
}
if (!locked && idle >= lockSecs) {
lock()
}
}, 1_000)
return () => {
clearInterval(id)
EVENTS.forEach(ev => window.removeEventListener(ev, onActivity))
}
}, [])
function handleLogout() {
logout()
navigate('/login', { replace: true, state: { manualLogout: true } })
}
function handleUnlock(u) {
unlock(u)
lastActivityRef.current = Date.now()
}
const loginUsername = user?.username || savedUsername || ''
const displayName = user?.full_name || loginUsername
return (
<LicenseContext.Provider value={license}>
<div className="flex h-screen overflow-hidden">
{locked && loginUsername && (
<LockScreen
username={loginUsername}
displayName={displayName || loginUsername}
onUnlock={handleUnlock}
onLogout={handleLogout}
/>
)}
<Sidebar />
<div className="flex flex-col flex-1 min-w-0">
<LicenseBanner license={license} />
{/* ── Header ── */}
<header className="flex items-center justify-between px-6 py-3 bg-white border-b border-slate-200 shrink-0 gap-4">
{/* Left: page title / breadcrumbs */}
<div className="flex items-center min-w-0">
<PageTitle />
</div>
{/* Right: search + bell + lock + user */}
<div className="flex items-center gap-2 shrink-0">
{/* Search (placeholder) */}
<div className="relative hidden sm:flex items-center">
<Search className="absolute left-2.5 h-3.5 w-3.5 text-slate-400 pointer-events-none" />
<input
type="text"
placeholder="Search…"
className="pl-8 pr-3 py-1.5 text-[13px] bg-slate-50 border border-slate-200 rounded-lg w-44 focus:outline-none focus:ring-2 focus:ring-sky-500/30 focus:border-sky-400 transition placeholder:text-slate-400"
readOnly
/>
</div>
{/* Platform notifications (2.6f) */}
<NotificationBell />
{/* Divider */}
<div className="h-5 w-px bg-slate-200" />
{/* Lock */}
<button
onClick={lock}
title="Lock"
className="flex h-8 w-8 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-700"
>
<Lock className="h-3.5 w-3.5" />
</button>
{/* User menu */}
<UserMenuButton
displayName={displayName}
onEditProfile={() => setProfileOpen(true)}
onSignOut={handleLogout}
/>
{profileOpen && <EditProfileModal onClose={() => setProfileOpen(false)} />}
</div>
</header>
<main className="flex-1 overflow-hidden flex flex-col min-h-0">
<RouteGuard><Outlet /></RouteGuard>
</main>
</div>
<PhoneListener />
</div>
</LicenseContext.Provider>
)
}
@@ -3,7 +3,7 @@
import { useState } from 'react' import { useState } from 'react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import FloorPlansTab from '../floor/FloorPlansTab' import FloorPlansTab from '../floor/FloorPlansTab'
import TablesConfigTab from '../TablesConfigTab' import TablesListTab from '../tables/TablesListTab'
const TABS = ['list', 'floor'] const TABS = ['list', 'floor']
@@ -22,7 +22,7 @@ export default function TablesConfigPage() {
))} ))}
</div> </div>
<div className="flex-1 min-h-0 overflow-y-auto"> <div className="flex-1 min-h-0 overflow-y-auto">
{tab === 'list' ? <TablesConfigTab /> : <FloorPlansTab />} {tab === 'list' ? <TablesListTab /> : <FloorPlansTab />}
</div> </div>
</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 { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, IconButton, Spinner, cx } from '@xenia/ui' import { Button, Dialog, IconButton, Spinner, cx } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { LicenseContext } from '../../layouts/AppLayout' import { LicenseContext } from '../../shell/licenseContext'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import BookingsCard, { BookingDialog } from './BookingsCard' import BookingsCard, { BookingDialog } from './BookingsCard'
import DaySummaryDialog from './DaySummaryDialog' 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
}
+165
View File
@@ -0,0 +1,165 @@
// The manager's frame (plan step 6.14b; was layouts/AppLayout): the side rail, a license banner
// when something needs doing (locked, expired, in its grace days, expiring soon, long without the
// cloud), the header (where you are, notifications, lock, your menu), the page, the lock screen
// (this session's own PIN, 2.6b) and locking / signing out after a while without use (Settings →
// Sign-in & security). Dropped from v1: a search box in the header that did nothing.
import { useEffect, useRef, useState } from 'react'
import { Outlet, useLocation, useNavigate } from 'react-router-dom'
import { AlertTriangle, ChevronRight, Lock, ShieldAlert } from 'lucide-react'
import { errorMessage, isError } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { IconButton, PinPad, cx } from '@xenia/ui'
import client from '../api/client'
import NotificationBell from '../components/NotificationBell'
import PhoneListener from '../components/PhoneListener'
import UserMenuButton from '../components/UserMenuButton'
import useLicenseStatus from '../hooks/useLicenseStatus'
import { useSettings } from '../pages/Settings/sections/useSettings'
import useAuthStore from '../store/authStore'
import { LicenseContext } from './licenseContext'
import { pageFor } from './nav'
import ProfileDialog from './ProfileDialog'
import RouteGuard from './RouteGuard'
import Sidebar from './Sidebar'
function PageTitle() {
const { pathname } = useLocation()
const { t } = useTranslation('manager')
const page = pageFor(pathname)
if (!page) return <span className="text-body font-semibold text-ink">XeniaPOS</span>
if (!page.parent) return <h1 className="text-body font-semibold text-ink">{t(page.label)}</h1>
return (
<nav className="flex items-center gap-1.5" aria-label={t('shell.where')}>
<span className="text-label text-ink-3 font-medium">{t(page.parent)}</span>
<ChevronRight size={13} className="text-ink-3 shrink-0" aria-hidden="true" />
<h1 className="text-body font-semibold text-ink">{t(page.label)}</h1>
</nav>
)
}
/** Which banner the license needs, or null: [tone, key, values]. */
function bannerOf(l) {
if (l.lock_reason === 'admin') return ['danger', l.locked ? 'adminLocked' : 'adminPending']
if (l.lock_reason === 'clock') return ['danger', 'clock']
if (l.lock_reason === 'unverified') return ['danger', 'unverified']
if (l.isBlocked && l.lock_reason === 'expired') return ['danger', 'expired', { count: Math.abs(l.days_until_expiry ?? 0) }]
if (l.inGracePeriod) return ['warning', 'grace', { count: Math.abs(l.days_until_expiry ?? 0), left: l.grace_days_remaining ?? 0 }]
if (l.showExpiryWarning) return ['warning', 'expiring', { count: l.days_until_expiry }]
if (l.longOffline) return ['neutral', 'offline', { count: l.offline_days }]
return null
}
const BANNER = { danger: 'bg-danger text-danger-fg', warning: 'bg-warning-soft text-warning-ink border-b border-line', neutral: 'bg-surface-2 text-ink-2 border-b border-line' }
function LicenseBanner({ license }) {
const { t } = useTranslation('manager')
const { formatDate } = useFormat()
const b = bannerOf(license)
if (!b) return null
const [tone, key, values = {}] = b
const Icon = tone === 'danger' ? ShieldAlert : AlertTriangle
return (
<div className={cx('flex items-center gap-2 px-4 py-2 text-label font-medium', BANNER[tone])} role="alert" data-testid="license-banner">
<Icon size={16} className="shrink-0" aria-hidden="true" />
<span>
{t(`shell.banner.${key}`, { ...values, date: license.expires_at ? formatDate(license.expires_at) : '' })}
{license.sync_failed && ['expired', 'grace', 'expiring'].includes(key) && ` ${t('shell.banner.connect')}`}
</span>
</div>
)
}
// The lock screen checks the PIN of the user who owns THIS session (POST /api/auth/unlock, 2.6b):
// no new sign-in, no new token. Five wrong tries end the session.
function LockScreen({ displayName, onUnlock, onLogout }) {
const { t } = useTranslation('manager')
const [error, setError] = useState('')
async function tryPin(pin) {
try {
const { data } = await client.post('/api/auth/unlock', { pin }, { xenia: { ignoreUnauthorized: true } })
setError('')
onUnlock(data.user)
return true
} catch (err) {
if (isError(err, 'auth.session_ended')) { onLogout(); return true }
setError(errorMessage(err, t))
return false
}
}
return (
<div className="fixed inset-0 z-[9999] flex items-center justify-center bg-scrim/80 backdrop-blur-md" data-testid="lock-screen">
<div className="bg-surface rounded-dialog shadow-overlay p-8 w-full max-w-xs text-center grid gap-4">
<div className="grid gap-1 justify-items-center">
<div className="flex h-12 w-12 items-center justify-center rounded-card bg-surface-2"><Lock className="h-6 w-6 text-ink-3" aria-hidden="true" /></div>
<p className="text-body-lg font-bold text-ink">{t('lock.title')}</p>
<p className="text-label text-ink-2">{displayName}</p>
</div>
<PinPad minLength={4} maxLength={8} error={error || undefined} onComplete={tryPin} />
<button type="button" onClick={onLogout} className="text-label text-ink-3 hover:text-ink-2 transition-colors">{t('lock.signOutInstead')}</button>
</div>
</div>
)
}
/** Lock and sign out after the venue's idle times (security.auto_lock*, security.auto_logout*). */
function useIdle(onLock, onSignOut) {
const s = useSettings()
const last = useRef(0)
const ref = useRef({})
useEffect(() => {
ref.current = {
lock: s.get('security.auto_lock', 'false') === 'true' ? Number(s.get('security.auto_lock_seconds', '300')) : Infinity,
out: s.get('security.auto_logout', 'false') === 'true' ? Number(s.get('security.auto_logout_seconds', '1800')) : Infinity,
onLock, onSignOut,
}
})
useEffect(() => {
last.current = Date.now()
const seen = () => { last.current = Date.now() }
const EVENTS = ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll', 'click']
EVENTS.forEach(ev => window.addEventListener(ev, seen, { passive: true }))
const id = setInterval(() => {
const idle = (Date.now() - last.current) / 1000
const { lock, out, onLock: lockNow, onSignOut: outNow } = ref.current
if (idle >= out) outNow?.()
else if (idle >= lock) lockNow?.()
}, 1000)
return () => { clearInterval(id); EVENTS.forEach(ev => window.removeEventListener(ev, seen)) }
}, [])
return () => { last.current = Date.now() }
}
export default function AppLayout() {
const { t } = useTranslation('manager')
const { user, savedUsername, logout, lock, unlock, locked } = useAuthStore()
const [profileOpen, setProfileOpen] = useState(false)
const navigate = useNavigate()
const license = useLicenseStatus()
const signOut = () => { logout(); navigate('/login', { replace: true, state: { manualLogout: true } }) }
const touched = useIdle(() => { if (user && !useAuthStore.getState().locked) lock() }, () => { if (user) signOut() })
const loginUsername = user?.username || savedUsername || ''
const displayName = user?.full_name || loginUsername
return (
<LicenseContext.Provider value={license}>
<div className="flex h-screen overflow-hidden bg-canvas">
{locked && loginUsername && <LockScreen displayName={displayName} onUnlock={u => { unlock(u); touched() }} onLogout={signOut} />}
<Sidebar />
<div className="flex flex-col flex-1 min-w-0">
<LicenseBanner license={license} />
<header className="flex items-center justify-between px-6 py-3 bg-surface border-b border-line shrink-0 gap-4">
<div className="flex items-center min-w-0"><PageTitle /></div>
<div className="flex items-center gap-2 shrink-0">
<NotificationBell />
<span className="h-5 w-px bg-line" aria-hidden="true" />
<IconButton size="sm" variant="secondary" label={t('shell.lock')} onClick={lock} data-testid="lock-now"><Lock size={14} /></IconButton>
<UserMenuButton displayName={displayName} onEditProfile={() => setProfileOpen(true)} onSignOut={signOut} />
{profileOpen && <ProfileDialog onClose={() => setProfileOpen(false)} />}
</div>
</header>
<main className="flex-1 overflow-hidden flex flex-col min-h-0"><RouteGuard><Outlet /></RouteGuard></main>
</div>
<PhoneListener />
</div>
</LicenseContext.Provider>
)
}
@@ -0,0 +1,70 @@
// Your profile (plan step 6.14b; was components/EditProfileModal): your name and username, a new
// password (with the current one) and a new PIN (4 to 6 digits, for the lock screen). Left empty,
// the password and the PIN stay as they are.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input } from '@xenia/ui'
import client from '../api/client'
import useAuthStore from '../store/authStore'
import { profileProblems } from './profileLogic'
export default function ProfileDialog({ onClose }) {
const { t } = useTranslation('manager')
const { user, updateUser } = useAuthStore()
const [f, setF] = useState({ fullName: user?.full_name ?? '', username: user?.username ?? '', current: '', next: '', again: '', pin: '', pin2: '' })
const [tried, setTried] = useState(false)
const set = (k, v) => setF(x => ({ ...x, [k]: v }))
const wrong = profileProblems(f)
const err = k => { const w = tried && wrong.find(([field]) => field === k); return w ? t(`profile.wrong.${w[1]}`) : undefined }
const save = useMutation({
mutationFn: body => client.patch('/api/auth/me', body).then(r => r.data),
onSuccess: u => { updateUser(u); toast.success(t('profile.saved')); onClose() },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => {
setTried(true)
if (wrong.length) return
const body = {}
if (f.fullName.trim() !== (user?.full_name ?? '')) body.full_name = f.fullName.trim()
if (f.username.trim() !== user?.username) body.username = f.username.trim()
if (f.next) { body.current_password = f.current; body.new_password = f.next }
if (f.pin) body.new_pin = f.pin
if (!Object.keys(body).length) { onClose(); return }
save.mutate(body)
}
const digits = v => v.replace(/\D/g, '').slice(0, 6)
return (
<Dialog open size="md" onClose={onClose} title={t('profile.edit')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('profile.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="profile-save">{t('profile.save')}</Button>
</>}>
<div className="grid gap-4" data-testid="profile-dialog">
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('profile.name')}><Input value={f.fullName} onChange={e => set('fullName', e.target.value)} data-testid="profile-name" /></Field>
<Field label={t('profile.username')} error={err('username')}><Input value={f.username} autoCapitalize="none" autoComplete="off" onChange={e => set('username', e.target.value)} /></Field>
</div>
<fieldset className="grid gap-3 rounded-card bg-surface-2 p-3">
<legend className="text-caption font-semibold uppercase tracking-wide text-ink-3 px-1">{t('profile.password')}</legend>
<p className="text-label text-ink-2 -mt-1">{t('profile.keepHint')}</p>
<Field label={t('profile.current')} error={err('current')}><Input type="password" autoComplete="current-password" value={f.current} onChange={e => set('current', e.target.value)} /></Field>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('profile.next')} error={err('next')}><Input type="password" autoComplete="new-password" value={f.next} onChange={e => set('next', e.target.value)} /></Field>
<Field label={t('profile.again')} error={err('again')}><Input type="password" autoComplete="new-password" value={f.again} onChange={e => set('again', e.target.value)} /></Field>
</div>
</fieldset>
<fieldset className="grid gap-3 rounded-card bg-surface-2 p-3">
<legend className="text-caption font-semibold uppercase tracking-wide text-ink-3 px-1">{t('profile.pin')}</legend>
<p className="text-label text-ink-2 -mt-1">{t('profile.pinHint')}</p>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('profile.newPin')} error={err('pin')}><Input type="password" inputMode="numeric" autoComplete="new-password" value={f.pin} onChange={e => set('pin', digits(e.target.value))} data-testid="profile-pin" /></Field>
<Field label={t('profile.pinAgain')} error={err('pin2')}><Input type="password" inputMode="numeric" autoComplete="new-password" value={f.pin2} onChange={e => set('pin2', digits(e.target.value))} data-testid="profile-pin2" /></Field>
</div>
</fieldset>
</div>
</Dialog>
)
}
+127
View File
@@ -0,0 +1,127 @@
// The manager's side rail (plan step 6.14b; was components/Sidebar): drawn from shell/nav.js, an
// item shows when its module is on and the user holds its key (2.6a). Groups open and close; the
// group holding the open page opens by itself. Online orders waiting carry a badge. Colours are
// the `nav` token set (@xenia/ui), so the rail keeps the product's teal in light and dark.
import { useState } from 'react'
import { NavLink, useLocation } from 'react-router-dom'
import { ChevronDown } from 'lucide-react'
import { useAccess } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { cx } from '@xenia/ui'
import client from '../api/client'
import { useLiveQuery } from '../live/useLiveQuery'
import { NAV, NAV_BOTTOM, canSee } from './nav'
const inGroup = (children, pathname) => children.some(c => pathname === c.to || pathname.startsWith(`${c.to}/`))
/** The sections with only what this user may see (empty groups and sections dropped). */
function visibleNav(access) {
return NAV
.map(section => ({
...section,
items: section.items
.map(item => (item.children ? { ...item, children: item.children.filter(c => canSee(c, access)) } : item))
.filter(item => (item.children ? item.children.length > 0 : canSee(item, access))),
}))
.filter(section => section.items.length > 0)
}
const link = active => cx('flex items-center gap-3 rounded-control font-medium transition-colors duration-fast',
active ? 'bg-nav-active text-nav-ink' : 'text-nav-ink-2 hover:bg-nav-raised hover:text-nav-ink')
function Child({ to, icon: Icon, label, placeholder }) {
const { t } = useTranslation('manager')
if (placeholder) {
return (
<NavLink to={to} end className={({ isActive }) => cx(link(isActive), 'gap-2.5 px-3 py-2 mx-2 text-label opacity-70')}>
<Icon size={14} className="shrink-0" aria-hidden="true" /><span>{t(label)}</span>
<span className="ml-auto text-caption font-semibold bg-nav-raised text-nav-ink-3 px-1.5 rounded">{t('nav.soon')}</span>
</NavLink>
)
}
return (
<NavLink to={to} end className={({ isActive }) => cx(link(isActive), 'gap-2.5 px-3 py-2 mx-2 text-label')}>
{({ isActive }) => (<>
<Icon size={14} className="shrink-0" aria-hidden="true" /><span>{t(label)}</span>
{isActive && <span className="ml-auto w-1.5 h-1.5 rounded-full bg-nav-dot shrink-0" aria-hidden="true" />}
</>)}
</NavLink>
)
}
function Group({ group, icon: Icon, label, children, open, onToggle }) {
const { t } = useTranslation('manager')
const { pathname } = useLocation()
const here = inGroup(children, pathname)
return (
<div>
<button type="button" onClick={() => onToggle(group)} aria-expanded={open}
className={cx('w-full px-3 py-2.5 text-body', link(false), here && 'bg-nav-raised text-nav-ink')}>
<Icon size={18} className="shrink-0" aria-hidden="true" />
<span className="flex-1 text-left">{t(label)}</span>
<ChevronDown size={14} className={cx('shrink-0 transition-transform duration-base', open && 'rotate-180')} aria-hidden="true" />
</button>
{open && <div className="mt-0.5 mb-1 py-1 grid gap-0.5 border-l border-nav-line ml-5">{children.map(c => <Child key={c.to} {...c} />)}</div>}
</div>
)
}
function Solo({ to, icon: Icon, label, badge, onNavigate }) {
const { t } = useTranslation('manager')
return (
<NavLink to={to} end onClick={onNavigate} className={({ isActive }) => cx(link(isActive), 'px-3 py-2.5 text-body')}>
<span className="relative shrink-0">
<Icon size={18} aria-hidden="true" />
{badge > 0 && (
<span className="absolute -top-1.5 -right-1.5 bg-danger text-danger-fg text-caption font-bold min-w-4 h-4 px-0.5 rounded-full grid place-items-center leading-none" data-testid="nav-badge">
{badge > 9 ? '9+' : badge}
</span>
)}
</span>
<span>{t(label)}</span>
</NavLink>
)
}
export default function Sidebar() {
const { t } = useTranslation('manager')
const access = useAccess()
const { pathname } = useLocation()
const nav = visibleNav(access)
const onlineShown = nav.some(s => s.items.some(i => i.badge === 'onlineOrders'))
const { data: waiting = [] } = useLiveQuery({
queryKey: ['online-orders', 'incoming'], enabled: onlineShown, refetchInterval: 20_000,
queryFn: () => client.get('/api/connect/orders/incoming').then(r => r.data),
events: ['online_order_received', 'online_order_updated'],
})
// The group of the open page opens by itself when the page changes; the user can still toggle
const pageGroup = NAV.flatMap(s => s.items).find(i => i.children && inGroup(i.children, pathname))?.group ?? null
const [toggled, setToggled] = useState({ page: pathname, group: undefined })
const open = toggled.page === pathname && toggled.group !== undefined ? toggled.group : pageGroup
const toggle = g => setToggled({ page: pathname, group: open === g ? null : g })
return (
<aside className="flex flex-col bg-nav-bg text-nav-ink shrink-0 w-56 h-full sidebar-scroll" data-testid="sidebar">
<div className="flex items-center px-4 py-4 border-b border-nav-line shrink-0">
<span className="font-bold text-title tracking-wide">XeniaPOS</span>
</div>
<nav className="flex-1 py-3 px-2 grid content-start gap-4" aria-label={t('nav.main')}>
{nav.map(({ section, items }) => (
<div key={section}>
<div className="flex items-center gap-2 px-3 mb-1.5 select-none">
<span className="text-caption font-bold uppercase tracking-widest text-nav-ink-3 whitespace-nowrap">{t(section)}</span>
<span className="flex-1 h-px bg-nav-line" aria-hidden="true" />
</div>
<div className="grid gap-0.5">
{items.map(item => (item.children
? <Group key={item.group} {...item} open={open === item.group} onToggle={toggle} />
: <Solo key={item.to} {...item} badge={item.badge === 'onlineOrders' ? waiting.length : undefined} onNavigate={() => setToggled({ page: pathname, group: null })} />))}
</div>
</div>
))}
</nav>
<div className="shrink-0 px-2 pb-3 pt-3 border-t border-nav-line grid gap-0.5">
{NAV_BOTTOM.filter(item => canSee(item, access)).map(item => <Solo key={item.to} {...item} />)}
</div>
</aside>
)
}
@@ -0,0 +1,5 @@
// The license state the layout reads once (hooks/useLicenseStatus) and shares with the pages
// (the overview's "open the day" says why it can't). Plan step 6.14b; was exported by AppLayout.
import { createContext } from 'react'
export const LicenseContext = createContext(null)
@@ -0,0 +1,14 @@
// The profile dialog's checks (plan step 6.14b), unit-tested in tests/shell.test.mjs.
/** What is wrong with the form: [field, key] pairs. */
export function profileProblems(f) {
const out = []
if (!f.username.trim()) out.push(['username', 'username'])
const pw = f.current || f.next || f.again
if (pw && !f.current) out.push(['current', 'current'])
if (pw && f.next.length < 6) out.push(['next', 'short'])
if (pw && f.next !== f.again) out.push(['again', 'mismatch'])
if ((f.pin || f.pin2) && !/^\d{4,6}$/.test(f.pin)) out.push(['pin', 'pin'])
if ((f.pin || f.pin2) && f.pin !== f.pin2) out.push(['pin2', 'pinMismatch'])
return out
}
-36
View File
@@ -1,36 +0,0 @@
import { STATUS_STYLES } from './tokens'
// Unified StatusBadge — replaces both src/components/StatusBadge.jsx
// and the StatusBadge in TablePrimitives.jsx.
//
// Greek labels map to the canonical status keys used across the app.
const LABELS = {
free: 'Ελεύθερο',
open: 'Ανοιχτό',
active: 'Ενεργό',
partially_paid: 'Μερική πληρωμή',
paid: 'Πληρώθηκε',
closed: 'Κλειστό',
closed_item: 'Κλειστό (απλήρωτο)',
'force-closed': 'Αναγκαστικό κλείσιμο',
cancelled: 'Ακυρώθηκε',
completed: 'Ολοκληρώθηκε',
failed: 'Απέτυχε',
success: 'Επιτυχία',
}
export default function Badge({ status, pulse = false }) {
const s = STATUS_STYLES[status] || STATUS_STYLES.closed
const label = LABELS[status] ?? (status ? status.replace(/[_-]/g, ' ') : 'άγνωστο')
return (
<span className={`inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[10px] font-mono uppercase tracking-[0.08em] ring-1 ring-inset ${s.bg} ${s.text} ${s.ring}`}>
<span className={`relative inline-block h-1.5 w-1.5 rounded-full flex-shrink-0 ${s.dot}`}>
{pulse && (status === 'active' || status === 'open') && (
<span className={`absolute inset-0 rounded-full ${s.dot} animate-ping opacity-75`} />
)}
</span>
{label}
</span>
)
}
-23
View File
@@ -1,23 +0,0 @@
import { BUTTON_VARIANTS, BUTTON_SIZES } from './tokens'
export default function Button({
variant = 'secondary',
size = 'md',
children,
className = '',
...props
}) {
const base = BUTTON_VARIANTS[variant] ?? BUTTON_VARIANTS.secondary
const sizeOverride = BUTTON_SIZES[size]
// Replace the size-specific px/py/text classes from the base with the size override
const cls = size === 'sm'
? base.replace('px-3.5 py-2 text-[13px]', sizeOverride)
: base
return (
<button className={`${cls} ${className}`} {...props}>
{children}
</button>
)
}
@@ -1,101 +0,0 @@
import { useState } from 'react'
import { AlertTriangle } from 'lucide-react'
/**
* Two-step delete confirmation:
* Step 1 — "Are you sure?" with a description of what will be deleted.
* Step 2 — Type "DELETE" to confirm.
*
* Props:
* title — e.g. "Διαγραφή Βάρδιας #12"
* description — e.g. "Η βάρδια του Νίκου θα διαγραφεί μόνιμα."
* onConfirm — called when the user completes both steps
* onCancel — called when the user dismisses
*/
export default function DeleteConfirmModal({ title, description, onConfirm, onCancel }) {
const [step, setStep] = useState(1)
const [typed, setTyped] = useState('')
const canDelete = typed.trim().toUpperCase() === 'DELETE'
return (
<div
className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/60 p-4"
onClick={onCancel}
>
<div
className="w-full max-w-md rounded-2xl bg-white shadow-2xl"
onClick={e => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-start gap-3 px-6 pt-6 pb-4">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-red-100">
<AlertTriangle size={18} className="text-red-600" />
</div>
<div>
<div className="text-base font-bold text-gray-900">{title}</div>
<div className="mt-1 text-sm text-gray-500">{description}</div>
</div>
</div>
<div className="px-6 pb-6 space-y-4">
{step === 1 && (
<>
<p className="text-sm text-red-700 font-medium bg-red-50 rounded-lg px-3 py-2">
Αυτή η ενέργεια είναι μη αναστρέψιμη.
</p>
<div className="flex gap-3">
<button
onClick={onCancel}
className="flex-1 rounded-lg border border-gray-200 py-2 text-sm font-medium text-gray-600 hover:bg-gray-50"
>
Ακύρωση
</button>
<button
onClick={() => setStep(2)}
className="flex-1 rounded-lg bg-red-600 py-2 text-sm font-bold text-white hover:bg-red-700"
>
Ναι, συνέχεια →
</button>
</div>
</>
)}
{step === 2 && (
<>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Για επιβεβαίωση πληκτρολογήστε <span className="font-mono font-bold text-red-600">DELETE</span>
</label>
<input
autoFocus
type="text"
value={typed}
onChange={e => setTyped(e.target.value)}
onKeyDown={e => e.key === 'Enter' && canDelete && onConfirm()}
placeholder="DELETE"
className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-red-400"
/>
</div>
<div className="flex gap-3">
<button
onClick={onCancel}
className="flex-1 rounded-lg border border-gray-200 py-2 text-sm font-medium text-gray-600 hover:bg-gray-50"
>
Ακύρωση
</button>
<button
onClick={onConfirm}
disabled={!canDelete}
className="flex-1 rounded-lg bg-red-600 py-2 text-sm font-bold text-white hover:bg-red-700 disabled:opacity-40 disabled:cursor-not-allowed"
>
Διαγραφή
</button>
</div>
</>
)}
</div>
</div>
</div>
)
}
-64
View File
@@ -1,64 +0,0 @@
import { INPUT_CLASS } from './tokens'
// Text input
export function Input({ className = '', ...props }) {
return (
<div className={`${INPUT_CLASS} ${className}`}>
<input
className="flex-1 bg-transparent outline-none text-[13px] text-slate-700 placeholder-slate-400 min-w-0"
{...props}
/>
</div>
)
}
// Native <select> wrapper
export function Select({ children, className = '', ...props }) {
return (
<div className={`${INPUT_CLASS} ${className}`}>
<select
className="flex-1 bg-transparent outline-none text-[13px] text-slate-700 cursor-pointer min-w-0"
{...props}
>
{children}
</select>
</div>
)
}
// Date input
export function DateInput({ label, icon: Icon, className = '', ...props }) {
return (
<label className={`${INPUT_CLASS} cursor-pointer ${className}`}>
{Icon && <Icon className="h-3.5 w-3.5 text-slate-400 flex-shrink-0" />}
{label && (
<span className="text-[11px] font-medium uppercase tracking-wider text-slate-400 flex-shrink-0">
{label}
</span>
)}
<input
type="date"
className="bg-transparent outline-none text-[13px] text-slate-700 font-normal min-w-0"
{...props}
/>
</label>
)
}
// Labelled text input with optional leading icon
export function LabelledInput({ label, icon: Icon, className = '', ...props }) {
return (
<div className={`${INPUT_CLASS} ${className}`}>
{Icon && <Icon className="h-3.5 w-3.5 text-slate-400 flex-shrink-0" />}
{label && (
<span className="text-[11px] font-medium uppercase tracking-wider text-slate-400 flex-shrink-0">
{label}
</span>
)}
<input
className="flex-1 bg-transparent outline-none text-[13px] text-slate-700 placeholder-slate-400 min-w-0"
{...props}
/>
</div>
)
}
-113
View File
@@ -1,113 +0,0 @@
import { useEffect } from 'react'
import { X } from 'lucide-react'
import Button from './Button'
// General-purpose modal — replaces ConfirmModal and can wrap any content.
//
// Usage (confirm pattern):
// <Modal title="Διαγραφή" onClose={onCancel}>
// <p>Θέλετε σίγουρα να διαγράψετε αυτό το στοιχείο;</p>
// <Modal.Footer>
// <Button variant="secondary" onClick={onCancel}>Ακύρωση</Button>
// <Button variant="danger" onClick={onConfirm}>Διαγραφή</Button>
// </Modal.Footer>
// </Modal>
export default function Modal({ title, onClose, children, footer, maxWidth = 'max-w-sm', className = '', tabs = null, activeTab = null, onTabChange = null }) {
// Close on Escape
useEffect(() => {
function handler(e) {
if (e.key === 'Escape') onClose?.()
}
document.addEventListener('keydown', handler)
return () => document.removeEventListener('keydown', handler)
}, [onClose])
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
onMouseDown={(e) => { if (e.target === e.currentTarget) onClose?.() }}
>
<div className={`relative w-full ${maxWidth} rounded-xl border border-slate-200 bg-white shadow-xl flex flex-col ${className}`}
style={{ maxHeight: 'calc(100vh - 2rem)' }}>
{/* Header */}
{title && (
<div className="flex items-center justify-between border-b border-slate-100 px-5 py-4 shrink-0">
<h2 className="text-[15px] font-semibold text-slate-900">{title}</h2>
{onClose && (
<button
onClick={onClose}
className="rounded-md p-1 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600"
>
<X className="h-4 w-4" />
</button>
)}
</div>
)}
{/* Tab bar */}
{tabs && (
<div className="flex border-b border-slate-100 px-5 shrink-0 gap-1">
{tabs.map(tab => (
<button
key={tab.key}
type="button"
onClick={() => onTabChange?.(tab.key)}
className={`px-3 py-2.5 text-[12px] font-medium border-b-2 transition-colors -mb-px ${
activeTab === tab.key
? 'border-sky-500 text-sky-700'
: 'border-transparent text-slate-500 hover:text-slate-700'
}`}
>
{tab.label}
</button>
))}
</div>
)}
{/* Body — scrollable */}
<div className="px-5 py-4 text-[13px] text-slate-700 overflow-y-auto flex-1 min-h-0">
{children}
</div>
{/* Footer — fixed outside scroll area when provided via prop */}
{footer && (
<div className="shrink-0 border-t border-slate-100 px-5 py-3 flex items-center justify-end gap-2">
{footer}
</div>
)}
</div>
</div>
)
}
// Footer helper — for modals without tabs (renders inline, modal doesn't scroll)
function ModalFooter({ children }) {
return (
<div className="flex items-center justify-end gap-2 border-t border-slate-100 pt-4 mt-2">
{children}
</div>
)
}
Modal.Footer = ModalFooter
// Convenience: ConfirmModal wrapping Modal for the most common pattern
export function ConfirmModal({
title,
message,
confirmLabel = 'Επιβεβαίωση',
confirmVariant = 'danger',
onConfirm,
onCancel,
}) {
return (
<Modal title={title} onClose={onCancel}>
{message && <p className="text-[13px] text-slate-600">{message}</p>}
<Modal.Footer>
<Button variant="secondary" onClick={onCancel}>Ακύρωση</Button>
<Button variant={confirmVariant} onClick={onConfirm}>{confirmLabel}</Button>
</Modal.Footer>
</Modal>
)
}
-85
View File
@@ -1,85 +0,0 @@
// Unified tab system — identical appearance across every page.
//
// TabGroup → primary nav row (supports lucide icons, used in Reports + Management + Settings)
// TabBar → secondary sub-tab row (pill style, used below TabGroup in Reports)
// TabRow → alias for TabGroup without icons — exact same markup and spacing
// TabCard → white rounded-xl card shell that wraps tab chrome + content
// Use this on any page that has tabs so it sits in the p-6 grey area correctly.
//
// Rule: ALL tab bars use px-6 pt-2 pb-0, border-b border-slate-200, transparent bg (inherits page bg).
// The sky-500 underline indicator is the ONLY active state difference.
const TAB_BTN_BASE =
'relative flex items-center gap-2 px-4 py-3 text-[13.5px] font-medium transition-colors whitespace-nowrap'
const TAB_BTN_ACTIVE = 'text-slate-900'
const TAB_BTN_INACTIVE = 'text-slate-500 hover:text-slate-700'
// ─── Primary tab row (with optional icons) ───────────────────────────────────
export function TabGroup({ tabs, active, onChange }) {
return (
<div className="flex-shrink-0 flex border-b border-slate-200 px-6 pt-2 overflow-x-auto">
{tabs.map((tab) => {
const isActive = tab.id === active
const Icon = tab.icon ?? tab.Icon
return (
<button
key={tab.id}
onClick={() => onChange(tab.id)}
className={`${TAB_BTN_BASE} ${isActive ? TAB_BTN_ACTIVE : TAB_BTN_INACTIVE}`}
>
{Icon && <Icon className={`h-4 w-4 flex-shrink-0 ${isActive ? 'text-sky-500' : 'text-slate-400'}`} />}
{tab.label}
{isActive && <span className="absolute inset-x-2 -bottom-px h-0.5 rounded-full bg-sky-500" />}
</button>
)
})}
</div>
)
}
// ─── Secondary sub-tab row (pill style) ──────────────────────────────────────
export function TabBar({ tabs, active, onChange }) {
return (
<div className="flex-shrink-0 flex items-center gap-1 border-b border-slate-200 px-6 py-2 overflow-x-auto">
{tabs.map((tab) => {
const isActive = tab.id === active
return (
<button
key={tab.id}
onClick={() => onChange(tab.id)}
className={`whitespace-nowrap rounded-md px-3 py-1.5 text-[12px] font-medium transition-colors ${
isActive
? 'bg-sky-100 text-sky-700 font-semibold'
: 'text-slate-500 hover:bg-slate-100 hover:text-slate-700'
}`}
>
{tab.label}
</button>
)
})}
</div>
)
}
// ─── TabRow: identical to TabGroup, kept as named alias ──────────────────────
export function TabRow({ tabs, active, onChange }) {
return <TabGroup tabs={tabs} active={active} onChange={onChange} />
}
// ─── TabCard: the white card shell for any tabbed page ───────────────────────
// Renders a rounded-xl bordered white card that fills the available space.
// Place TabGroup/TabBar as direct children, then a flex-1 overflow content area.
//
// Usage:
// <TabCard>
// <TabGroup ... />
// <TabBar ... /> {/* optional */}
// <div className="flex-1 overflow-y-auto p-6"> ... </div>
// </TabCard>
export function TabCard({ children, className = '' }) {
return (
<div className={`flex flex-col flex-1 min-h-0 rounded-xl border border-slate-200 bg-white shadow-sm overflow-hidden ${className}`}>
{children}
</div>
)
}
-154
View File
@@ -1,154 +0,0 @@
// Global design tokens — single source of truth for the manager dashboard UI
// Reports subsystem and all other pages import from here.
export const COLORS = {
// Primary accent
sky500: '#0ea5e9',
sky400: '#38bdf8',
sky600: '#0284c7',
sky50: '#f0f9ff',
// Neutrals
slate900: '#0f172a',
slate800: '#1e293b',
slate700: '#334155',
slate600: '#475569',
slate500: '#64748b',
slate400: '#94a3b8',
slate300: '#cbd5e1',
slate200: '#e2e8f0',
slate100: '#f1f5f9',
slate50: '#f8fafc',
white: '#ffffff',
// Semantic
emerald600: '#059669',
emerald700: '#047857',
emerald50: '#ecfdf5',
emerald200: '#a7f3d0',
rose600: '#e11d48',
rose700: '#be123c',
rose50: '#fff1f2',
rose200: '#fecdd3',
amber500: '#f59e0b',
amber50: '#fffbeb',
amber200: '#fde68a',
violet500: '#8b5cf6',
teal500: '#14b8a6',
}
export const CHART_PALETTE = [
'#60a5fa',
'#7fa67f',
'#dc6a3d',
'#c08aa8',
'#6b8fb5',
'#f59e0b',
'#14b8a6',
'#a78bfa',
]
export const STATUS_STYLES = {
completed: { bg: 'bg-emerald-50', text: 'text-emerald-700', ring: 'ring-emerald-200', dot: 'bg-emerald-500' },
active: { bg: 'bg-sky-50', text: 'text-sky-700', ring: 'ring-sky-200', dot: 'bg-sky-500' },
'force-closed': { bg: 'bg-amber-50', text: 'text-amber-800', ring: 'ring-amber-200', dot: 'bg-amber-500' },
closed: { bg: 'bg-slate-100', text: 'text-slate-600', ring: 'ring-slate-200', dot: 'bg-slate-400' },
paid: { bg: 'bg-emerald-50', text: 'text-emerald-700', ring: 'ring-emerald-200', dot: 'bg-emerald-500' },
open: { bg: 'bg-sky-50', text: 'text-sky-700', ring: 'ring-sky-200', dot: 'bg-sky-500' },
partially_paid: { bg: 'bg-amber-50', text: 'text-amber-800', ring: 'ring-amber-200', dot: 'bg-amber-500' },
cancelled: { bg: 'bg-rose-50', text: 'text-rose-700', ring: 'ring-rose-200', dot: 'bg-rose-500' },
closed_item: { bg: 'bg-amber-50', text: 'text-amber-800', ring: 'ring-amber-200', dot: 'bg-amber-500' },
failed: { bg: 'bg-rose-50', text: 'text-rose-700', ring: 'ring-rose-200', dot: 'bg-rose-500' },
success: { bg: 'bg-emerald-50', text: 'text-emerald-700', ring: 'ring-emerald-200', dot: 'bg-emerald-500' },
free: { bg: 'bg-slate-100', text: 'text-slate-600', ring: 'ring-slate-200', dot: 'bg-slate-400' },
}
export const AVATAR_PALETTE = [
'bg-sky-100 text-sky-700',
'bg-emerald-100 text-emerald-700',
'bg-amber-100 text-amber-800',
'bg-violet-100 text-violet-700',
'bg-rose-100 text-rose-700',
'bg-teal-100 text-teal-700',
]
export function avatarColor(id) {
const key = String(id)
let h = 0
for (let i = 0; i < key.length; i++) h = (h * 31 + key.charCodeAt(i)) >>> 0
return AVATAR_PALETTE[h % AVATAR_PALETTE.length]
}
// Formatters
export const fmtEUR = (n) => {
if (n == null) return '—'
return '€' + Number(n).toLocaleString('en-EU', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}
export const fmtNum = (n) => (n == null ? '—' : Number(n).toLocaleString('en-EU'))
export const fmtTime = (iso) => {
if (!iso) return '—'
return new Date(iso).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })
}
export const fmtDate = (iso) => {
if (!iso) return '—'
const d = new Date(iso)
if (isNaN(d)) return String(iso)
return d.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' })
}
// Format a raw YYYY-MM-DD string (from a date picker) as DD/MM/YYYY without any timezone conversion
export const fmtDateStr = (yyyymmdd) => {
if (!yyyymmdd) return '—'
const [y, m, d] = String(yyyymmdd).split('-')
if (!y || !m || !d) return yyyymmdd
return `${d}/${m}/${y}`
}
export const fmtDateTime = (iso) => {
if (!iso) return '—'
return fmtDate(iso) + ' · ' + fmtTime(iso)
}
export const fmtDuration = (startIso, endIso) => {
if (!startIso) return '—'
const start = new Date(startIso)
const end = endIso ? new Date(endIso) : new Date()
const minutes = Math.floor((end - start) / 60000)
if (minutes < 0) return '—'
const h = Math.floor(minutes / 60)
const m = minutes % 60
return `${h}h ${String(m).padStart(2, '0')}m`
}
export const fmtMinutes = (mins) => {
if (mins == null) return '—'
const h = Math.floor(mins / 60)
const m = Math.round(mins % 60)
return h > 0 ? `${h}h ${String(m).padStart(2, '0')}m` : `${m}m`
}
// Common Tailwind class strings
export const PANEL_CLASS = 'overflow-hidden rounded-lg border border-slate-200 bg-white shadow-[0_1px_0_rgba(15,23,42,0.04)]'
export const STAT_CARD_CLASS = 'relative overflow-hidden rounded-lg border border-slate-200 bg-white p-5 shadow-[0_1px_0_rgba(15,23,42,0.04)]'
export const INPUT_CLASS = 'flex items-center gap-2 rounded-md border border-slate-200 bg-white px-2.5 py-1.5 text-[13px] text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:border-slate-300 focus-within:border-sky-400 focus-within:ring-2 focus-within:ring-sky-100'
// Button variant class strings
export const BUTTON_VARIANTS = {
primary: 'inline-flex items-center justify-center gap-2 rounded-md bg-sky-500 px-3.5 py-2 text-[13px] font-medium text-white shadow-[0_1px_0_rgba(15,23,42,0.08)] transition hover:bg-sky-600 active:bg-sky-700 disabled:opacity-50 disabled:pointer-events-none',
secondary: 'inline-flex items-center justify-center gap-2 rounded-md border border-slate-200 bg-white px-3.5 py-2 text-[13px] font-medium text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:bg-slate-50 hover:border-slate-300 active:bg-slate-100 disabled:opacity-50 disabled:pointer-events-none',
ghost: 'inline-flex items-center justify-center gap-2 rounded-md px-3.5 py-2 text-[13px] font-medium text-slate-600 transition hover:bg-slate-100 hover:text-slate-900 active:bg-slate-200 disabled:opacity-50 disabled:pointer-events-none',
danger: 'inline-flex items-center justify-center gap-2 rounded-md bg-rose-500 px-3.5 py-2 text-[13px] font-medium text-white shadow-[0_1px_0_rgba(15,23,42,0.08)] transition hover:bg-rose-600 active:bg-rose-700 disabled:opacity-50 disabled:pointer-events-none',
}
export const BUTTON_SIZES = {
sm: 'px-2.5 py-1.5 text-[12px]',
md: 'px-3.5 py-2 text-[13px]',
}
// Modal overlay
export const MODAL_OVERLAY_CLASS = 'fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4'
// Sidebar nav item
export const NAV_ITEM_BASE = 'flex items-center gap-3 rounded-md px-3 py-2 text-[13px] font-medium transition'
export const NAV_ITEM_ACTIVE = 'bg-sky-50 text-sky-700'
export const NAV_ITEM_INACTIVE = 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
-11
View File
@@ -10,17 +10,6 @@ export default {
fontFamily: { fontFamily: {
sans: ['Google Sans', 'system-ui', 'sans-serif'], sans: ['Google Sans', 'system-ui', 'sans-serif'],
}, },
colors: {
primary: {
DEFAULT: '#0f766e',
50: '#f0fdfa',
100: '#ccfbf1',
600: '#0d9488',
700: '#0f766e',
800: '#115e59',
900: '#134e4a',
},
},
fontSize: { fontSize: {
base: ['1rem', { lineHeight: '1.5rem' }], base: ['1rem', { lineHeight: '1.5rem' }],
}, },
+46
View File
@@ -0,0 +1,46 @@
// The shell, the setup wizard and the tables list as plain data (plan step 6.14b).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { profileProblems } from '../src/shell/profileLogic.js'
import { accountProblems, pinProblems, setupBody, startLanguage, venueProblems } from '../src/pages/setup/setupLogic.js'
import { duplicateNames, nextNumber, reorder, series, tableBody, tableProblems, tablesOf } from '../src/pages/tables/tablesLogic.js'
const fields = list => list.map(([f, k]) => `${f}:${k}`)
test('the profile: password and PIN only when typed', () => {
const base = { username: 'maria', current: '', next: '', again: '', pin: '', pin2: '' }
assert.deepEqual(profileProblems(base), [])
assert.deepEqual(fields(profileProblems({ ...base, next: 'abc', again: 'abd' })), ['current:current', 'next:short', 'again:mismatch'])
assert.deepEqual(fields(profileProblems({ ...base, pin: '12', pin2: '12' })), ['pin:pin'])
assert.deepEqual(fields(profileProblems({ ...base, pin: '123456', pin2: '123457' })), ['pin2:pinMismatch'])
assert.deepEqual(fields(profileProblems({ ...base, username: ' ' })), ['username:username'])
})
test('the setup wizard: account, venue, PIN, what is sent', () => {
const a = { username: 'owner', fullName: 'Olga', email: '', password: 'secret1', confirm: 'secret1' }
assert.deepEqual(accountProblems(a), [])
assert.deepEqual(fields(accountProblems({ ...a, username: 'o w', email: 'x@', confirm: 'nope' })), ['username:spaces', 'email:email', 'confirm:mismatch'])
assert.deepEqual(fields(venueProblems({ types: [], name: '' })), ['types:pickOne', 'name:required'])
assert.deepEqual(pinProblems('', ''), [])
assert.deepEqual(fields(pinProblems('123', '123')), ['pin:pin'])
assert.deepEqual(fields(pinProblems('1234', '1235')), ['again:pinMismatch'])
assert.deepEqual(setupBody(a, { types: ['bar', 'restaurant'], name: ' Golden ', language: 'el', timezone: 'Europe/Athens' }, ''),
{ username: 'owner', password: 'secret1', email: null, full_name: 'Olga', venue_type: 'bar,restaurant', venue_name: 'Golden', language: 'el', timezone: 'Europe/Athens', pin: undefined })
assert.equal(startLanguage('el-GR'), 'el')
assert.equal(startLanguage('en-US'), 'en')
})
test('the tables list: tabs, twice-used names, numbering on, series, reordering zones', () => {
const tables = [{ id: 1, group_id: 7, label: 'BS-1' }, { id: 2, group_id: 7, label: 'BS-4' }, { id: 3, group_id: null, label: 'B3' }, { id: 4, group_id: 8, label: 'B3' }]
assert.deepEqual(tablesOf(tables, 'none').map(x => x.id), [3])
assert.deepEqual(tablesOf(tables, 7).map(x => x.id), [1, 2])
assert.deepEqual([...duplicateNames(tables)], ['B3'])
assert.equal(nextNumber(tables, 7, 'BS-'), 5)
assert.equal(nextNumber(tables, 8, 'BS-'), 1)
assert.deepEqual(series('T-', 9, 3), { names: ['T-9', 'T-10', 'T-11'], last: 'T-11', tooLong: false })
assert.equal(series('BAR-', 99, 2).tooLong, true) // BAR-100 is 7 characters
assert.deepEqual(reorder([1, 2, 3], 1, 3), [2, 3, 1])
assert.deepEqual(reorder([1, 2, 3], 3, 0), [3, 1, 2])
assert.deepEqual(tableBody({ label: ' ', group_id: '7', seats: '4' }), { label: null, group_id: 7, seat_count: 4 })
assert.deepEqual(tableProblems({ label: 'TOOLONG', seats: '0' }), ['label', 'seats'])
})
+3 -5
View File
@@ -1,9 +1,7 @@
{ {
"_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.", "_comment": "Plan step 6.1 → 6.14b: what is on the v2 rules. `paths` is all of `src` (6.14b): tests/v2-guards.test.mjs refuses Greek and colour literals anywhere in it (colour data files: the guard's DATA list). `strict`: also no setState in effects (data loads with useLiveQuery / react-query); a few older files still load in an effect and are left out.",
"paths": [ "paths": ["src"],
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing", "src/pages/schedule", "src/pages/reports", "src/pages/finance", "src/pages/customers", "src/pages/inventory", "src/pages/notes"
],
"strict": [ "strict": [
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing", "src/pages/staff", "src/pages/schedule", "src/pages/reports/kit", "src/pages/reports/today", "src/pages/reports/store", "src/pages/reports/products", "src/pages/reports/staff", "src/pages/reports/misc", "src/pages/reports/technical", "src/pages/reports/prepzones", "src/pages/reports/expenses", "src/pages/finance", "src/pages/customers", "src/pages/inventory", "src/pages/notes", "src/pages/Settings/SettingsPage.jsx", "src/pages/Settings/sections/SystemSettings.jsx", "src/pages/Settings/sections/DataTransfer.jsx", "src/pages/Settings/sections/SecuritySettings.jsx", "src/pages/Settings/sections/OperationSettings.jsx", "src/pages/Settings/sections/TableFlags.jsx", "src/pages/Settings/sections/QuickMessages.jsx", "src/pages/Settings/sections/TableColours.jsx", "src/pages/Settings/sections/FiscalSettings.jsx", "src/pages/Settings/sections/DevelopmentSettings.jsx" "src/App.jsx", "src/hooks", "src/live", "src/pages/Settings/SettingsPage.jsx", "src/pages/Settings/sections/DataTransfer.jsx", "src/pages/Settings/sections/DevelopmentSettings.jsx", "src/pages/Settings/sections/FiscalSettings.jsx", "src/pages/Settings/sections/OperationSettings.jsx", "src/pages/Settings/sections/QuickMessages.jsx", "src/pages/Settings/sections/SecuritySettings.jsx", "src/pages/Settings/sections/SystemSettings.jsx", "src/pages/Settings/sections/TableColours.jsx", "src/pages/Settings/sections/TableFlags.jsx", "src/pages/customers", "src/pages/finance", "src/pages/floor", "src/pages/inventory", "src/pages/notes", "src/pages/online/OnlineOrdersPage.jsx", "src/pages/orders", "src/pages/overview", "src/pages/pricing", "src/pages/printing", "src/pages/products", "src/pages/reports/expenses", "src/pages/reports/kit", "src/pages/reports/misc", "src/pages/reports/prepzones", "src/pages/reports/products", "src/pages/reports/staff", "src/pages/reports/store", "src/pages/reports/technical", "src/pages/reports/today", "src/pages/schedule", "src/pages/setup", "src/pages/staff", "src/pages/staff/SessionsPage.jsx", "src/pages/tables", "src/shell"
] ]
} }
+195 -3
View File
@@ -48,12 +48,35 @@
"deliveryFees": "Online παραγγελίες (ρύθμιση)", "deliveryFees": "Online παραγγελίες (ρύθμιση)",
"qrCodes": "QR τραπεζιών", "qrCodes": "QR τραπεζιών",
"media": "Πολυμέσα", "media": "Πολυμέσα",
"signage": "Προβολή" "signage": "Προβολή",
"main": "Κύριο μενού"
}, },
"profile": { "profile": {
"edit": "Επεξεργασία προφίλ", "edit": "Επεξεργασία προφίλ",
"signOut": "Αποσύνδεση", "signOut": "Αποσύνδεση",
"language": "Γλώσσα" "language": "Γλώσσα",
"back": "Πίσω",
"save": "Αποθήκευση",
"saved": "Το προφίλ αποθηκεύτηκε",
"name": "Όνομα",
"username": "Όνομα χρήστη",
"password": "Κωδικός",
"keepHint": "Αφήστε κενό για να κρατήσετε τον κωδικό σας.",
"current": "Τρέχων κωδικός",
"next": "Νέος κωδικός",
"again": "Νέος κωδικός ξανά",
"pin": "PIN",
"pinHint": "Για την οθόνη κλειδώματος. Αφήστε κενό για να κρατήσετε το δικό σας.",
"newPin": "Νέο PIN",
"pinAgain": "Νέο PIN ξανά",
"wrong": {
"username": "Γράψτε όνομα χρήστη.",
"current": "Γράψτε τον τρέχοντα κωδικό.",
"short": "Τουλάχιστον 6 χαρακτήρες.",
"mismatch": "Οι δύο κωδικοί δεν ταιριάζουν.",
"pin": "4 έως 6 ψηφία.",
"pinMismatch": "Τα δύο PIN δεν ταιριάζουν."
}
}, },
"login": { "login": {
"title": "Σύνδεση", "title": "Σύνδεση",
@@ -678,7 +701,61 @@
"setup": { "setup": {
"language": "Γλώσσα προσωπικού", "language": "Γλώσσα προσωπικού",
"timezone": "Ζώνη ώρας", "timezone": "Ζώνη ώρας",
"languageHint": "Η γλώσσα των οθονών του προσωπικού (ο καθένας μπορεί να διαλέξει τη δική του) και των εκτυπωμένων δελτίων και αναφορών." "languageHint": "Η γλώσσα των οθονών του προσωπικού (ο καθένας μπορεί να διαλέξει τη δική του) και των εκτυπωμένων δελτίων και αναφορών.",
"welcome": "Καλώς ήρθατε στο Xenia POS",
"welcomeIntro": "Λίγα βήματα και το κατάστημά σας είναι έτοιμο.",
"plan": {
"account": "Ο λογαριασμός σας",
"venue": "Το κατάστημά σας",
"ready": "Έτοιμοι"
},
"start": "Ξεκινάμε",
"stepOf": "Βήμα {{n}} από {{of}}",
"back": "Πίσω",
"next": "Επόμενο",
"skip": "Παράλειψη",
"accountTitle": "Ο λογαριασμός σας",
"accountIntro": "Ο λογαριασμός του ιδιοκτήτη: μπορεί να κάνει τα πάντα.",
"username": "Όνομα χρήστη",
"fullName": "Ονοματεπώνυμο",
"email": "Email",
"emailHint": "Προαιρετικό.",
"password": "Κωδικός",
"confirm": "Κωδικός ξανά",
"venueTitle": "Το κατάστημά σας",
"venueIntro": "Επιλέξτε όσα ταιριάζουν· αλλάζουν αργότερα.",
"kind": "Είδος",
"kinds": {
"restaurant": "Εστιατόριο",
"bar": "Μπαρ",
"coffee_shop": "Καφετέρια",
"fast_food": "Fast food"
},
"venueName": "Όνομα καταστήματος",
"venueNameExample": "π.χ. Το Χρυσό Πιρούνι",
"pinTitle": "PIN για την οθόνη κλειδώματος",
"pinIntro": "Προαιρετικό: 4 έως 6 ψηφία για να ξεκλειδώνετε χωρίς κωδικό.",
"pin": "PIN",
"pinAgain": "PIN ξανά",
"doneTitle": "Όλα έτοιμα",
"doneIntro": "Το κατάστημά σας είναι έτοιμο. Συνδεθείτε και προσθέστε μενού, τραπέζια και προσωπικό.",
"next3": {
"menu": "Προσθέστε το μενού και τα προϊόντα",
"tables": "Ρυθμίστε τραπέζια και ζώνες",
"staff": "Προσθέστε το προσωπικό"
},
"finish": "Τέλος και σύνδεση",
"footer": "Xenia POS · αρχική ρύθμιση",
"wrong": {
"required": "Υποχρεωτικό.",
"spaces": "Χωρίς κενά.",
"email": "Δεν μοιάζει με διεύθυνση email.",
"short": "Τουλάχιστον 6 χαρακτήρες.",
"mismatch": "Οι δύο κωδικοί δεν ταιριάζουν.",
"pickOne": "Επιλέξτε τουλάχιστον ένα.",
"pin": "4 έως 6 ψηφία.",
"pinMismatch": "Τα δύο PIN δεν ταιριάζουν."
}
}, },
"fees": { "fees": {
"title": "Περιοχές και χρεώσεις διανομής", "title": "Περιοχές και χρεώσεις διανομής",
@@ -3684,5 +3761,120 @@
"deleteYes": "Διαγραφή", "deleteYes": "Διαγραφή",
"deleted": "Διαγράφηκε", "deleted": "Διαγράφηκε",
"back": "Πίσω" "back": "Πίσω"
},
"shell": {
"where": "Βρίσκεστε εδώ",
"lock": "Κλείδωμα οθόνης",
"banner": {
"adminLocked": "Το σύστημα κλειδώθηκε από τον διαχειριστή. Επικοινωνήστε με την υποστήριξη.",
"adminPending": "Ο διαχειριστής θα κλειδώσει το σύστημα με το κλείσιμο της τρέχουσας μέρας.",
"clock": "Το ρολόι του server γύρισε πίσω. Διορθώστε την ημερομηνία και την ώρα του server ή συνδέστε τον στο internet.",
"unverified": "Δεν υπάρχει ακόμα επιβεβαιωμένη άδεια. Συνδέστε τον server στο internet για να ενεργοποιηθεί.",
"expired_one": "Η άδεια έληξε πριν από {{count}} μέρα ({{date}}). Ανανεώστε την ή επικοινωνήστε με την υποστήριξη.",
"expired_other": "Η άδεια έληξε πριν από {{count}} μέρες ({{date}}). Ανανεώστε την ή επικοινωνήστε με την υποστήριξη.",
"grace_one": "Η άδεια έληξε στις {{date}}. Απομένουν {{left}} μέρες χάριτος: ανανεώστε την για να μην κλειδώσει.",
"grace_other": "Η άδεια έληξε στις {{date}}. Απομένουν {{left}} μέρες χάριτος: ανανεώστε την για να μην κλειδώσει.",
"expiring_one": "Η άδεια λήγει σε {{count}} μέρα ({{date}}). Ανανεώστε την έγκαιρα.",
"expiring_other": "Η άδεια λήγει σε {{count}} μέρες ({{date}}). Ανανεώστε την έγκαιρα.",
"offline_one": "Χωρίς επαφή με το cloud εδώ και {{count}} μέρα. Όλα λειτουργούν· η άδεια ισχύει έως {{date}}.",
"offline_other": "Χωρίς επαφή με το cloud εδώ και {{count}} μέρες. Όλα λειτουργούν· η άδεια ισχύει έως {{date}}.",
"connect": "Συνδέστε τον server στο internet για να ανανεωθεί."
}
},
"tablesList": {
"all": "Όλα",
"noZone": "Χωρίς ζώνη",
"zones": "Ζώνες",
"counts": "{{tables}} τραπέζια · {{zones}} ζώνες",
"offCount_one": "{{count}} ανενεργό",
"offCount_other": "{{count}} ανενεργά",
"showOff": "Εμφάνιση ανενεργών",
"pick": "Επιλογή",
"picked_one": "{{count}} επιλεγμένο",
"picked_other": "{{count}} επιλεγμένα",
"pickAll": "Επιλογή όλων",
"unpickAll": "Αποεπιλογή όλων",
"pickOne": "Επιλογή: {{name}}",
"moveZone": "Μετακίνηση σε ζώνη",
"renameSeries": "Μετονομασία σε σειρά",
"delete": "Διαγραφή",
"newZone": "Νέα ζώνη",
"newTable": "Νέο τραπέζι",
"editZone": "Επεξεργασία ζώνης",
"addMany": "Μαζική προσθήκη",
"numbered": "Τραπέζι {{n}}",
"duplicate": "Ίδιο όνομα δύο φορές",
"seats_one": "{{count}} θέση",
"seats_other": "{{count}} θέσεις",
"off": "Ανενεργό",
"hasOrder": "Έχει ανοιχτή παραγγελία",
"edit": "Επεξεργασία: {{name}}",
"turnOff": "Απενεργοποίηση: {{name}}",
"turnOn": "Ενεργοποίηση: {{name}}",
"deleteOne": "Διαγραφή: {{name}}",
"none": "Δεν υπάρχουν τραπέζια.",
"noneActive": "Δεν υπάρχουν ενεργά τραπέζια.",
"saved": "Αποθηκεύτηκε",
"added": "Το τραπέζι προστέθηκε",
"deleted": "Το τραπέζι διαγράφηκε",
"turnedOff": "Το τραπέζι απενεργοποιήθηκε",
"someFailed_one": "{{count}} τραπέζι δεν άλλαξε",
"someFailed_other": "{{count}} τραπέζια δεν άλλαξαν",
"moved_one": "{{count}} τραπέζι μετακινήθηκε",
"moved_other": "{{count}} τραπέζια μετακινήθηκαν",
"renamed_one": "{{count}} τραπέζι μετονομάστηκε",
"renamed_other": "{{count}} τραπέζια μετονομάστηκαν",
"deletedMany_one": "{{count}} τραπέζι διαγράφηκε",
"deletedMany_other": "{{count}} τραπέζια διαγράφηκαν",
"offTitle": "Απενεργοποίηση: {{name}};",
"offBody": "Κρύβεται και δεν χρησιμοποιείται. Μπορείτε να το ενεργοποιήσετε ξανά.",
"turnOffYes": "Απενεργοποίηση",
"deleteTitle": "Διαγραφή: {{name}};",
"deleteBody": "Διαγράφεται οριστικά.",
"deleteYes": "Διαγραφή",
"deleteManyTitle_one": "Διαγραφή {{count}} τραπεζιού;",
"deleteManyTitle_other": "Διαγραφή {{count}} τραπεζιών;",
"deleteManyBody": "Διαγράφονται οριστικά (όσα έχουν ανοιχτή παραγγελία μένουν).",
"back": "Πίσω",
"save": "Αποθήκευση",
"add": "Προσθήκη",
"name": "Όνομα",
"nameHint": "Έως {{max}} χαρακτήρες (χωράει στις κάρτες των κινητών). Κενό: αριθμείται αυτόματα.",
"nameLong": "Έως {{max}} χαρακτήρες.",
"nameExample": "π.χ. Β3",
"zone": "Ζώνη",
"seatsLabel": "Θέσεις",
"seatsHint": "Προαιρετικό.",
"seatsWrong": "Αριθμός από 1 έως 99.",
"zoneSaved": "Η ζώνη αποθηκεύτηκε",
"zoneDeleted": "Η ζώνη διαγράφηκε",
"zoneDeleteTitle": "Διαγραφή της ζώνης {{name}};",
"zoneDeleteBody": "Τα τραπέζια της μένουν, χωρίς ζώνη.",
"zoneName": "Όνομα ζώνης",
"zoneNameNeeded": "Γράψτε ένα όνομα.",
"zoneExample": "π.χ. Βεράντα",
"prefix": "Πρόθεμα",
"prefixHint": "Προτείνεται στη μαζική προσθήκη (π.χ. Τ → Τ-1, Τ-2…).",
"colour": "Χρώμα",
"noColour": "Χωρίς χρώμα",
"inZone": "Στη ζώνη {{name}}",
"batchHint": "Αριθμούνται από εκεί που σταμάτησε η ζώνη.",
"howMany": "Πόσα",
"addSeries": "Προσθήκη {{from}} … {{to}}",
"addedMany_one": "Προστέθηκε {{count}} τραπέζι",
"addedMany_other": "Προστέθηκαν {{count}} τραπέζια",
"seriesLong": "Το τελευταίο όνομα θα ήταν {{last}}: πάνω από {{max}} χαρακτήρες.",
"moveTitle_one": "Μετακίνηση {{count}} τραπεζιού",
"moveTitle_other": "Μετακίνηση {{count}} τραπεζιών",
"toZone": "Στη ζώνη",
"move": "Μετακίνηση",
"renameTitle_one": "Μετονομασία {{count}} τραπεζιού",
"renameTitle_other": "Μετονομασία {{count}} τραπεζιών",
"renameIntro": "Με τη σειρά που εμφανίζονται.",
"startAt": "Από τον αριθμό",
"renameYes_one": "Μετονομασία {{count}} τραπεζιού",
"renameYes_other": "Μετονομασία {{count}} τραπεζιών",
"andMore_one": "και {{count}} ακόμα",
"andMore_other": "και {{count}} ακόμα"
} }
} }
+195 -3
View File
@@ -48,12 +48,35 @@
"deliveryFees": "Online ordering", "deliveryFees": "Online ordering",
"qrCodes": "Table QR codes", "qrCodes": "Table QR codes",
"media": "Media", "media": "Media",
"signage": "Signage" "signage": "Signage",
"main": "Main menu"
}, },
"profile": { "profile": {
"edit": "Edit profile", "edit": "Edit profile",
"signOut": "Sign out", "signOut": "Sign out",
"language": "Language" "language": "Language",
"back": "Back",
"save": "Save",
"saved": "Profile saved",
"name": "Name",
"username": "Username",
"password": "Password",
"keepHint": "Leave empty to keep your password.",
"current": "Current password",
"next": "New password",
"again": "New password again",
"pin": "PIN",
"pinHint": "For the lock screen. Leave empty to keep yours.",
"newPin": "New PIN",
"pinAgain": "New PIN again",
"wrong": {
"username": "Enter a username.",
"current": "Enter your current password.",
"short": "At least 6 characters.",
"mismatch": "The two passwords don't match.",
"pin": "4 to 6 digits.",
"pinMismatch": "The two PINs don't match."
}
}, },
"login": { "login": {
"title": "Sign in", "title": "Sign in",
@@ -678,7 +701,61 @@
"setup": { "setup": {
"language": "Staff language", "language": "Staff language",
"timezone": "Time zone", "timezone": "Time zone",
"languageHint": "The language of staff screens (each person can choose their own) and of printed tickets and reports." "languageHint": "The language of staff screens (each person can choose their own) and of printed tickets and reports.",
"welcome": "Welcome to Xenia POS",
"welcomeIntro": "A few steps and your venue is ready.",
"plan": {
"account": "Your account",
"venue": "Your venue",
"ready": "Ready to go"
},
"start": "Start",
"stepOf": "Step {{n}} of {{of}}",
"back": "Back",
"next": "Next",
"skip": "Skip",
"accountTitle": "Your account",
"accountIntro": "The owner's account: it can do everything.",
"username": "Username",
"fullName": "Full name",
"email": "E-mail",
"emailHint": "Optional.",
"password": "Password",
"confirm": "Password again",
"venueTitle": "Your venue",
"venueIntro": "Pick all that fit; you can change them later.",
"kind": "Kind",
"kinds": {
"restaurant": "Restaurant",
"bar": "Bar",
"coffee_shop": "Café",
"fast_food": "Fast food"
},
"venueName": "Venue name",
"venueNameExample": "e.g. The Golden Fork",
"pinTitle": "A PIN for the lock screen",
"pinIntro": "Optional: 4 to 6 digits to unlock the dashboard without your password.",
"pin": "PIN",
"pinAgain": "PIN again",
"doneTitle": "All set",
"doneIntro": "Your venue is ready. Sign in and add your menu, tables and staff.",
"next3": {
"menu": "Add your menu and products",
"tables": "Set up tables and zones",
"staff": "Add your staff"
},
"finish": "Finish and sign in",
"footer": "Xenia POS · first-time setup",
"wrong": {
"required": "Required.",
"spaces": "No spaces.",
"email": "This doesn't look like an e-mail address.",
"short": "At least 6 characters.",
"mismatch": "The two passwords don't match.",
"pickOne": "Pick at least one.",
"pin": "4 to 6 digits.",
"pinMismatch": "The two PINs don't match."
}
}, },
"fees": { "fees": {
"title": "Delivery areas and fees", "title": "Delivery areas and fees",
@@ -3684,5 +3761,120 @@
"deleteYes": "Delete", "deleteYes": "Delete",
"deleted": "Deleted", "deleted": "Deleted",
"back": "Back" "back": "Back"
},
"shell": {
"where": "You are here",
"lock": "Lock the screen",
"banner": {
"adminLocked": "The system was locked by the administrator. Contact support.",
"adminPending": "The administrator will lock the system when the current business day closes.",
"clock": "The server's clock went back in time. Fix the server's date and time, or connect it to the internet.",
"unverified": "There is no verified license yet. Connect the server to the internet to activate it.",
"expired_one": "The license expired {{count}} day ago ({{date}}). Renew it or contact support.",
"expired_other": "The license expired {{count}} days ago ({{date}}). Renew it or contact support.",
"grace_one": "The license expired on {{date}}. {{left}} grace days are left: renew it to avoid the lock.",
"grace_other": "The license expired on {{date}}. {{left}} grace days are left: renew it to avoid the lock.",
"expiring_one": "The license ends in {{count}} day ({{date}}). Renew it in time.",
"expiring_other": "The license ends in {{count}} days ({{date}}). Renew it in time.",
"offline_one": "No contact with the cloud for {{count}} day. Everything works; the license is valid until {{date}}.",
"offline_other": "No contact with the cloud for {{count}} days. Everything works; the license is valid until {{date}}.",
"connect": "Connect the server to the internet so it can renew."
}
},
"tablesList": {
"all": "All",
"noZone": "No zone",
"zones": "Zones",
"counts": "{{tables}} tables · {{zones}} zones",
"offCount_one": "{{count}} off",
"offCount_other": "{{count}} off",
"showOff": "Show the ones off",
"pick": "Pick",
"picked_one": "{{count}} picked",
"picked_other": "{{count}} picked",
"pickAll": "Pick all",
"unpickAll": "Unpick all",
"pickOne": "Pick {{name}}",
"moveZone": "Move to a zone",
"renameSeries": "Rename in a series",
"delete": "Delete",
"newZone": "New zone",
"newTable": "New table",
"editZone": "Edit the zone",
"addMany": "Add many",
"numbered": "Table {{n}}",
"duplicate": "Same name twice",
"seats_one": "{{count}} seat",
"seats_other": "{{count}} seats",
"off": "Off",
"hasOrder": "It has an open order",
"edit": "Edit {{name}}",
"turnOff": "Turn {{name}} off",
"turnOn": "Turn {{name}} on",
"deleteOne": "Delete {{name}}",
"none": "No tables.",
"noneActive": "No tables in use.",
"saved": "Saved",
"added": "Table added",
"deleted": "Table deleted",
"turnedOff": "Table turned off",
"someFailed_one": "{{count}} table couldn't be changed",
"someFailed_other": "{{count}} tables couldn't be changed",
"moved_one": "{{count}} table moved",
"moved_other": "{{count}} tables moved",
"renamed_one": "{{count}} table renamed",
"renamed_other": "{{count}} tables renamed",
"deletedMany_one": "{{count}} table deleted",
"deletedMany_other": "{{count}} tables deleted",
"offTitle": "Turn {{name}} off?",
"offBody": "It is hidden and can't be used. You can turn it on again.",
"turnOffYes": "Turn off",
"deleteTitle": "Delete {{name}}?",
"deleteBody": "It is deleted for good.",
"deleteYes": "Delete",
"deleteManyTitle_one": "Delete {{count}} table?",
"deleteManyTitle_other": "Delete {{count}} tables?",
"deleteManyBody": "They are deleted for good (tables with an open order are kept).",
"back": "Back",
"save": "Save",
"add": "Add",
"name": "Name",
"nameHint": "Up to {{max}} characters (it fits on the phones' cards). Empty: numbered for you.",
"nameLong": "Up to {{max}} characters.",
"nameExample": "e.g. B3",
"zone": "Zone",
"seatsLabel": "Seats",
"seatsHint": "Optional.",
"seatsWrong": "A number from 1 to 99.",
"zoneSaved": "Zone saved",
"zoneDeleted": "Zone deleted",
"zoneDeleteTitle": "Delete the zone {{name}}?",
"zoneDeleteBody": "Its tables stay, without a zone.",
"zoneName": "Zone name",
"zoneNameNeeded": "Enter a name.",
"zoneExample": "e.g. Terrace",
"prefix": "Prefix",
"prefixHint": "Suggested when adding many tables (e.g. T → T-1, T-2…).",
"colour": "Colour",
"noColour": "No colour",
"inZone": "In {{name}}",
"batchHint": "Numbered on from the zone's last one.",
"howMany": "How many",
"addSeries": "Add {{from}} … {{to}}",
"addedMany_one": "{{count}} table added",
"addedMany_other": "{{count}} tables added",
"seriesLong": "The last name would be {{last}}: over {{max}} characters.",
"moveTitle_one": "Move {{count}} table",
"moveTitle_other": "Move {{count}} tables",
"toZone": "To the zone",
"move": "Move",
"renameTitle_one": "Rename {{count}} table",
"renameTitle_other": "Rename {{count}} tables",
"renameIntro": "In the order they are listed.",
"startAt": "Start at",
"renameYes_one": "Rename {{count}} table",
"renameYes_other": "Rename {{count}} tables",
"andMore_one": "and {{count}} more",
"andMore_other": "and {{count}} more"
} }
} }
+36
View File
@@ -259,6 +259,42 @@
} }
} }
/* ── Nav (the manager's navigation rail, plan step 6.14b) ─────────────────
* The dark teal side rail of the manager dashboard: its own set, so the rail keeps the
* product's colour whatever the venue's accent, and has a dark-mode version (6.15). */
:root {
--x-nav-bg-rgb: 17 94 89; /* the rail */
--x-nav-raised-rgb: 15 118 110; /* hover, an open group */
--x-nav-active-rgb: 13 148 136; /* the page you are on */
--x-nav-line-rgb: 13 148 136; /* dividers, a group's left line */
--x-nav-ink-rgb: 255 255 255; /* text on the rail */
--x-nav-ink-2-rgb: 204 251 241; /* items */
--x-nav-ink-3-rgb: 153 246 228; /* section titles, sub-items */
--x-nav-dot-rgb: 56 189 248; /* the mark next to the open page */
--x-nav-bg: rgb(var(--x-nav-bg-rgb));
--x-nav-raised: rgb(var(--x-nav-raised-rgb));
--x-nav-active: rgb(var(--x-nav-active-rgb));
--x-nav-line: rgb(var(--x-nav-line-rgb));
--x-nav-ink: rgb(var(--x-nav-ink-rgb));
--x-nav-ink-2: rgb(var(--x-nav-ink-2-rgb));
--x-nav-ink-3: rgb(var(--x-nav-ink-3-rgb));
--x-nav-dot: rgb(var(--x-nav-dot-rgb));
}
[data-theme="dark"] {
--x-nav-bg-rgb: 4 47 46;
--x-nav-raised-rgb: 17 94 89;
--x-nav-active-rgb: 15 118 110;
--x-nav-line-rgb: 19 78 74;
}
@media (prefers-color-scheme: dark) {
[data-theme="system"] {
--x-nav-bg-rgb: 4 47 46;
--x-nav-raised-rgb: 17 94 89;
--x-nav-active-rgb: 15 118 110;
--x-nav-line-rgb: 19 78 74;
}
}
/* ── Board (the kitchen display's design language, plan step 3.2b-2) ─────── /* ── Board (the kitchen display's design language, plan step 3.2b-2) ───────
* A dark board with light cards, for screens read from a distance (kitchen, bar, * A dark board with light cards, for screens read from a distance (kitchen, bar,
* and any later "board" screen). Always dark: it doesn't follow data-theme; the * and any later "board" screen). Always dark: it doesn't follow data-theme; the
+3
View File
@@ -24,6 +24,7 @@ export default {
extend: { extend: {
colors: { colors: {
canvas: c('canvas'), canvas: c('canvas'),
scrim: c('scrim'), // behind dialogs and the lock screen (6.14b)
surface: { DEFAULT: c('surface'), 2: c('surface-2'), 3: c('surface-3') }, surface: { DEFAULT: c('surface'), 2: c('surface-2'), 3: c('surface-3') },
line: { DEFAULT: c('line'), strong: c('line-strong') }, line: { DEFAULT: c('line'), strong: c('line-strong') },
ink: { DEFAULT: c('ink'), 2: c('ink-2'), 3: c('ink-3') }, ink: { DEFAULT: c('ink'), 2: c('ink-2'), 3: c('ink-3') },
@@ -34,6 +35,8 @@ export default {
info: tone('info'), info: tone('info'),
// the board design language (kitchen display): bg-board-bg, text-board-ink-2, bg-board-late… // the board design language (kitchen display): bg-board-bg, text-board-ink-2, bg-board-late…
board: Object.fromEntries(BOARD.map(n => [n, c(`board-${n}`)])), board: Object.fromEntries(BOARD.map(n => [n, c(`board-${n}`)])),
// the manager's navigation rail (6.14b): bg-nav-bg, text-nav-ink-2, bg-nav-active…
nav: Object.fromEntries(['bg', 'raised', 'active', 'line', 'ink', 'ink-2', 'ink-3', 'dot'].map(n => [n, c(`nav-${n}`)])),
}, },
fontSize: { fontSize: {
caption: ['var(--x-text-caption)', { lineHeight: 'var(--x-leading-caption)' }], caption: ['var(--x-text-caption)', { lineHeight: 'var(--x-leading-caption)' }],
+40
View File
@@ -770,6 +770,46 @@ try {
await page.getByTestId('user-menu').click() await page.getByTestId('user-menu').click()
await page.getByRole('menuitemradio', { name: 'English' }).click() await page.getByRole('menuitemradio', { name: 'English' }).click()
// ── 6.14b: the tables list, the profile, the shell on v2 ──────────────────────
const tl = 'tables list:'
await page.goto(`${APP}/management/tables`)
await page.getByTestId('zone-new').click()
await page.getByTestId('zone-save').click()
r.check(`${tl} a zone needs a name`, (await page.getByTestId('zone-dialog').textContent()).includes('Enter a name'))
await page.getByTestId('zone-name').fill('E2E Zone')
await page.getByTestId('zone-prefix').fill('EZ')
await page.getByTestId('zone-save').click()
const zoneTab = page.locator('[data-testid="zone-tab"]', { hasText: 'E2E Zone' })
await zoneTab.waitFor({ timeout: 8000 }).catch(() => {})
await zoneTab.click()
await page.getByTestId('tables-batch').click()
await page.getByTestId('batch-count').fill('3')
r.check(`${tl} adding many: the button says the series (EZ-1 … EZ-3)`, (await page.getByTestId('batch-save').textContent()).includes('EZ-1') && (await page.getByTestId('batch-save').textContent()).includes('EZ-3'))
await page.getByTestId('batch-save').click()
await page.locator('[data-testid="table-row"][data-name="EZ-3"]').waitFor({ timeout: 8000 }).catch(() => {})
const ezZone = (await api('GET', '/api/tables/groups', { token: boss })).find(g => g.name === 'E2E Zone')
let ezTables = (await api('GET', '/api/tables/', { token: boss })).filter(x => x.group_id === ezZone?.id)
r.check(`${tl} a zone with 3 tables EZ-1..EZ-3`, ezTables.map(x => x.label).sort().join() === 'EZ-1,EZ-2,EZ-3', JSON.stringify(ezTables.map(x => x.label)))
await page.getByTestId('tables-pick').click()
for (const row of await page.getByTestId('table-row').all()) await row.locator('input[type=checkbox]').check()
await page.getByTestId('tables-rename').click()
await page.getByTestId('rename-prefix').fill('Q')
await page.getByTestId('rename-save').click()
await page.locator('[data-testid="table-row"][data-name="Q3"]').waitFor({ timeout: 8000 }).catch(() => {})
ezTables = (await api('GET', '/api/tables/', { token: boss })).filter(x => x.group_id === ezZone?.id)
r.check(`${tl} the 3 picked tables renamed in a series (Q1..Q3)`, ezTables.map(x => x.label).sort().join() === 'Q1,Q2,Q3', JSON.stringify(ezTables.map(x => x.label)))
await page.screenshot({ path: path.join(OUT, 'manager-tables-list.png'), fullPage: true })
for (const x of ezTables) await api('DELETE', `/api/tables/${x.id}?hard=true`, { token: boss }).catch(() => {})
if (ezZone) await api('DELETE', `/api/tables/groups/${ezZone.id}`, { token: boss }).catch(() => {})
await page.getByTestId('user-menu').click()
await page.getByRole('menuitem', { name: 'Edit profile' }).click()
await page.getByTestId('profile-pin').fill('12')
await page.getByTestId('profile-pin2').fill('12')
await page.getByTestId('profile-save').click()
r.check(`${tl} the profile: a PIN of 2 digits is refused before saving`, (await page.getByTestId('profile-dialog').textContent()).includes('4 to 6 digits'))
await page.keyboard.press('Escape')
r.check(`${tl} the side rail is drawn with the nav tokens`, await page.getByTestId('sidebar').evaluate(el => getComputedStyle(el).backgroundColor) === 'rgb(17, 94, 89)')
await page.goto(`${APP}/reports/technical`) await page.goto(`${APP}/reports/technical`)
await page.getByText('Log files', { exact: true }).click() await page.getByText('Log files', { exact: true }).click()
const today = new Date().toISOString().slice(0, 10) const today = new Date().toISOString().slice(0, 10)
+1
View File
@@ -29,6 +29,7 @@ const suites = [
['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E], ['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E],
['waiter (sign-in, keys, prices, languages, history, look, bookings)', 'node', ['waiter.mjs'], E2E], ['waiter (sign-in, keys, prices, languages, history, look, bookings)', 'node', ['waiter.mjs'], E2E],
['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E], ['manager (login, bootstrap, approvals)', 'node', ['manager.mjs'], E2E],
['setup (a fresh install: the wizard to the overview)', 'node', ['setup.mjs'], E2E],
['media (Media page, product photos, waiter offline photos)', 'node', ['media.mjs'], E2E], ['media (Media page, product photos, waiter offline photos)', 'node', ['media.mjs'], E2E],
['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E], ['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E],
['signage (the player on a TV, the editor)', 'node', ['signage.mjs'], E2E], ['signage (the player on a TV, the editor)', 'node', ['signage.mjs'], E2E],
+69
View File
@@ -0,0 +1,69 @@
// First-run setup (plan step 6.14b, "done when"): a fresh install (an empty database, no manager)
// sends the sign-in page to the setup wizard; the wizard is filled in Greek (it switches language
// at once), finishes, and the new owner signs in and reaches the overview.
// Starts its own backend (:8065, an empty data folder) and the manager (:5189).
// node setup.mjs
import path from 'node:path'
import { mkdtempSync, openSync } from 'node:fs'
import { spawn } from 'node:child_process'
import { chromium } from 'playwright'
import { BROWSER_CHANNEL, CS, OUT, reporter } from './lib/env.mjs'
import { killTree, startBackend, waitHttp } from './lib/proc.mjs'
const dataDir = mkdtempSync(path.join(OUT, 'fresh-')) // no pos.db: the backend creates it
const backend = await startBackend({ port: 8065, dataDir })
const APP = 'http://localhost:5189'
const log = openSync(path.join(OUT, 'vite-5189.log'), 'w')
const vite = spawn('npx', ['vite', '--port', '5189', '--strictPort'], {
cwd: path.join(CS, 'manager_dashboard'), shell: process.platform === 'win32', detached: process.platform !== 'win32',
stdio: ['ignore', log, log], env: { ...process.env, XENIA_BACKEND: backend.url },
})
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
const r = reporter('setup (6.14b): a fresh install goes through the wizard, in Greek, to the overview')
const errors = []
try {
await waitHttp(APP)
const page = await browser.newPage({ locale: 'en-US' })
page.on('pageerror', e => errors.push(String(e)))
const status = await fetch(`${backend.url}/api/setup/status`).then(x => x.json())
r.check('a fresh install needs setup', status.needs_setup === true, JSON.stringify(status))
await page.goto(`${APP}/login`)
const wizard = page.getByTestId('setup-wizard')
r.check('the sign-in page sends to the wizard', await wizard.waitFor({ timeout: 60_000 }).then(() => true).catch(() => false) && new URL(page.url()).pathname === '/setup')
r.check('…in English for an English browser', (await wizard.textContent()).includes('Welcome to Xenia POS'))
await page.getByTestId('setup-lang-el').click()
r.check('choosing Ελληνικά switches the wizard at once', await page.getByText('Καλώς ήρθατε στο Xenia POS').waitFor({ timeout: 5000 }).then(() => true).catch(() => false))
await page.getByTestId('setup-start').click()
await page.getByTestId('setup-next').click()
r.check('the account step says what is missing', await wizard.getAttribute('data-step') === 'account' && (await wizard.textContent()).includes('Υποχρεωτικό'))
await page.getByTestId('setup-username').fill('olga')
await page.getByTestId('setup-full-name').fill('Όλγα Ιδιοκτήτρια')
await page.getByTestId('setup-password').fill('kalimera1')
await page.getByTestId('setup-confirm').fill('kalimera1')
await page.getByTestId('setup-next').click()
await page.getByTestId('setup-type-coffee_shop').click()
await page.getByTestId('setup-venue-name').fill('Καφέ E2E')
r.check('the venue step starts in Greek with the browser\'s time zone', await page.getByTestId('setup-language').inputValue() === 'el' && !!(await page.getByTestId('setup-timezone').inputValue()))
await page.getByTestId('setup-next').click()
await page.getByTestId('setup-pin').fill('2468')
await page.getByTestId('setup-pin-again').fill('2468')
await page.getByTestId('setup-next').click()
await page.screenshot({ path: path.join(OUT, 'setup-done.png'), fullPage: true })
await page.getByTestId('setup-finish').click()
r.check('finishing goes to the sign-in page', await page.getByTestId('login-form').waitFor({ timeout: 15_000 }).then(() => true).catch(() => false))
const boot = await fetch(`${backend.url}/api/platform/bootstrap`).then(x => x.json())
r.check('the venue is set up in Greek', boot.venue?.language === 'el', JSON.stringify(boot.venue))
await page.locator('input[type=password]').waitFor({ timeout: 10_000 })
if (!(await page.getByTestId('login-account').count())) await page.locator('input[autocomplete=username]').fill('olga') // one manager: the form shows the account
await page.locator('input[type=password]').fill('kalimera1')
await page.locator('button[type=submit]').click()
r.check('the new owner signs in and reaches the overview', await page.getByTestId('overview').waitFor({ timeout: 20_000 }).then(() => true).catch(() => false))
await page.screenshot({ path: path.join(OUT, 'setup-overview.png'), fullPage: true })
r.check('the setup is done (no second owner can be made)', (await fetch(`${backend.url}/api/setup/status`).then(x => x.json())).needs_setup === false)
r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | '))
} finally {
await browser.close()
killTree(vite)
await backend.stop()
}
process.exit(r.done() ? 1 : 0)