diff --git a/manager_dashboard/eslint.config.js b/manager_dashboard/eslint.config.js index d9c9282..70b5c0b 100644 --- a/manager_dashboard/eslint.config.js +++ b/manager_dashboard/eslint.config.js @@ -32,7 +32,8 @@ export default defineConfig([ }, }, 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 // a fetch). A warning until phase 6 moves page loading to react-query (already a dependency). 'react-hooks/set-state-in-effect': 'warn', diff --git a/manager_dashboard/scripts/lint.mjs b/manager_dashboard/scripts/lint.mjs index 40c913b..0185e0e 100644 --- a/manager_dashboard/scripts/lint.mjs +++ b/manager_dashboard/scripts/lint.mjs @@ -1,8 +1,6 @@ -// `npm run lint` (plan step 6.1): ESLint over the code on the v2 rules (v2.json `paths`), the -// config and the tests. `npx eslint src` shows everything, older pages included. +// `npm run lint` (plan step 6.1; 6.14b: all of src is v2): ESLint over src, the config, the +// scripts and the tests. v2.json `strict` (eslint.config.js) adds the no-setState-in-effect rule. 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', ...v2.paths], { stdio: 'inherit', shell: process.platform === 'win32' }) +const r = spawnSync('npx', ['eslint', 'eslint.config.js', 'scripts', 'tests', 'src'], { stdio: 'inherit', shell: process.platform === 'win32' }) process.exit(r.status ?? 1) diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index 75dd35a..ac6749e 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -1,16 +1,21 @@ -import { lazy, Suspense, useEffect, useState } from 'react' -import { BrowserRouter, Routes, Route, Navigate, Outlet, useNavigate } from 'react-router-dom' +// The manager's routes (plan step 6.14b: the shell on v2). Every page sits in the platform +// 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 RouteGuard from './shell/RouteGuard' import { createI18n } from '@xenia/i18n' +import { Spinner } from '@xenia/ui' import useAuthStore from './store/authStore' -import AppLayout from './layouts/AppLayout' +import AppLayout from './shell/AppLayout' import LiveProvider from './live/LiveProvider' import client from './api/client' // Auth / setup import LoginPage from './pages/LoginPage' -import SetupWizard from './pages/SetupWizard' +import SetupWizard from './pages/setup/SetupWizard' // Operation import OverviewPage from './pages/overview/OverviewPage' @@ -63,37 +68,26 @@ import SettingsPage from './pages/Settings/SettingsPage' import NotesPage from './pages/notes/NotesPage' // 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() // 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 I18nSample = import.meta.env.DEV ? lazy(() => import('@xenia/i18n/sample')) : null -function Spinner() { - return ( -
-
-
- ) +function Loading() { + return
} +/** A token kept from an earlier visit: who it belongs to (else it is dropped and you sign in again). */ function AuthRehydrator({ children }) { const { token, user, rehydrate, logout } = useAuthStore() - const [ready, setReady] = useState(false) - - useEffect(() => { - if (token && !user) { - client.get('/api/auth/me') - .then(r => { rehydrate(r.data, token) }) - .catch(() => { logout() }) - .finally(() => setReady(true)) - } else { - setReady(true) - } - }, []) // intentionally runs once on mount - - if (!ready) return + const needed = !!token && !user + const { isPending } = useQuery({ + queryKey: ['auth-me', token], enabled: needed, retry: false, staleTime: Infinity, + queryFn: () => client.get('/api/auth/me').then(r => { rehydrate(r.data, token); return r.data }).catch(e => { logout(); throw e }), + }) + if (needed && isPending) return return children } @@ -102,20 +96,11 @@ function RequireAuth({ children }) { return token ? children : } +/** The sign-in page, unless nobody can sign in yet (a fresh install): then the setup wizard. */ function SetupGuard({ children }) { - const [checked, setChecked] = useState(false) - const navigate = useNavigate() - - useEffect(() => { - client.get('/api/setup/status') - .then(({ data }) => { - if (data.needs_setup) navigate('/setup', { replace: true }) - }) - .catch(() => {}) - .finally(() => setChecked(true)) - }, [navigate]) - - if (!checked) return + const { data, isPending } = useQuery({ queryKey: ['setup-status'], retry: false, queryFn: () => client.get('/api/setup/status').then(r => r.data) }) + if (isPending) return + if (data?.needs_setup) return return children } @@ -124,7 +109,7 @@ function SetupGuard({ children }) { function ManagerRoot() { const token = useAuthStore(s => s.token) return ( - }> + }> diff --git a/manager_dashboard/src/components/EditProfileModal.jsx b/manager_dashboard/src/components/EditProfileModal.jsx deleted file mode 100644 index 3f2bdf6..0000000 --- a/manager_dashboard/src/components/EditProfileModal.jsx +++ /dev/null @@ -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 ( - -
- -
- setFullName(e.target.value)} - placeholder="e.g. Maria Papadopoulou" - /> - setUsername(e.target.value)} - autoComplete="off" - /> -
- -
- -
-

- Change Password (leave blank to keep current) -

- setCurrentPassword(e.target.value)} - autoComplete="current-password" - /> - setNewPassword(e.target.value)} - autoComplete="new-password" - /> - setConfirmPassword(e.target.value)} - autoComplete="new-password" - /> -
- -
- -
-

- Change PIN (leave blank to keep current) -

-
- setNewPin(onlyDigits(e.target.value, 4))} - placeholder="••••" - className="flex-1" - /> - setConfirmPin(onlyDigits(e.target.value, 4))} - placeholder="••••" - className="flex-1" - /> -
-
- - {error && ( -

{error}

- )} -
- - - - - - - ) -} diff --git a/manager_dashboard/src/components/NotificationBell.jsx b/manager_dashboard/src/components/NotificationBell.jsx index 05710a4..0d01e29 100644 --- a/manager_dashboard/src/components/NotificationBell.jsx +++ b/manager_dashboard/src/components/NotificationBell.jsx @@ -80,7 +80,7 @@ export default function NotificationBell() {
- - {isOpen && ( -
- {children.map(child => ( - - ))} -
- )} -
- ) -} - -// ─── Solo item (direct link) ────────────────────────────────────────────────── - -function SoloItem({ to, icon: Icon, label, badge, onNavigate }) { - const { t } = useTranslation('manager') - return ( - - `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') - } - > -
- - {badge > 0 && ( - - {badge > 9 ? '9+' : badge} - - )} -
- {t(label)} -
- ) -} - -// ─── 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 ( - - ) -} diff --git a/manager_dashboard/src/components/UserMenuButton.jsx b/manager_dashboard/src/components/UserMenuButton.jsx index 2266b68..22f6125 100644 --- a/manager_dashboard/src/components/UserMenuButton.jsx +++ b/manager_dashboard/src/components/UserMenuButton.jsx @@ -50,28 +50,28 @@ export default function UserMenuButton({ displayName, onEditProfile, onSignOut }
{open && ( -
+
-
-
+
+
{t('profile.language')}
@@ -82,18 +82,18 @@ export default function UserMenuButton({ displayName, onEditProfile, onSignOut } aria-checked={lng === language} lang={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" > {LANGUAGE_NAMES[lng]} - {lng === language && } + {lng === language && } ))} -
+
-
-
- ) -} - -// ─── 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 ( - -
- {locked && loginUsername && ( - - )} - - - -
- - - {/* ── Header ── */} -
- {/* Left: page title / breadcrumbs */} -
- -
- - {/* Right: search + bell + lock + user */} -
- {/* Search (placeholder) */} -
- - -
- - {/* Platform notifications (2.6f) */} - - - {/* Divider */} -
- - {/* Lock */} - - - {/* User menu */} - setProfileOpen(true)} - onSignOut={handleLogout} - /> - {profileOpen && setProfileOpen(false)} />} -
-
- -
- -
-
- - -
-
- ) -} diff --git a/manager_dashboard/src/pages/Management/TablesConfigPage.jsx b/manager_dashboard/src/pages/Management/TablesConfigPage.jsx index 53da28b..75f587b 100644 --- a/manager_dashboard/src/pages/Management/TablesConfigPage.jsx +++ b/manager_dashboard/src/pages/Management/TablesConfigPage.jsx @@ -3,7 +3,7 @@ import { useState } from 'react' import { useTranslation } from '@xenia/i18n' import FloorPlansTab from '../floor/FloorPlansTab' -import TablesConfigTab from '../TablesConfigTab' +import TablesListTab from '../tables/TablesListTab' const TABS = ['list', 'floor'] @@ -22,7 +22,7 @@ export default function TablesConfigPage() { ))}
- {tab === 'list' ? : } + {tab === 'list' ? : }
) diff --git a/manager_dashboard/src/pages/SetupWizard.jsx b/manager_dashboard/src/pages/SetupWizard.jsx deleted file mode 100644 index 5b721ef..0000000 --- a/manager_dashboard/src/pages/SetupWizard.jsx +++ /dev/null @@ -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 ( -
- {Array.from({ length: total }).map((_, i) => ( -
- ))} -
- ) -} - -// ─── 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 ( - - ) -} - -// ─── 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 ( -
-
- {Array.from({ length: 4 }).map((_, i) => ( -
- ))} -
-
- {PIN_DIGITS.map((d, i) => ( - - ))} -
-
- ) -} - -// ─── Steps ─────────────────────────────────────────────────────────────────── - -function StepWelcome({ onNext }) { - return ( -
-
- -
- -
-

Welcome to Xenia POS

-

- 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. -

-
- -
- {[ - 'Create your manager account', - 'Tell us about your venue', - 'You\'re ready to go', - ].map((s, i) => ( -
-
- {i + 1} -
- {s} -
- ))} -
- - - -

Thank you for choosing Xenia POS.

-
- ) -} - -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 ( -
-
-

Create your manager account

-

This will be the primary administrator account.

-
- -
-
- onChange('username', e.target.value)} - autoComplete="off" - autoFocus - /> - {errors.username &&

{errors.username}

} -
- -
- onChange('fullName', e.target.value)} - autoComplete="off" - /> - {errors.fullName &&

{errors.fullName}

} -
- -
- onChange('email', e.target.value)} - type="email" - autoComplete="off" - /> - {errors.email &&

{errors.email}

} -
- -
- handlePasswordChange(e.target.value)} - type="password" - autoComplete="new-password" - /> - {errors.password &&

{errors.password}

} -
- -
- handleConfirmChange(e.target.value)} - type="password" - autoComplete="new-password" - /> - {errors.confirm &&

{errors.confirm}

} -
-
- -
- - -
-
- ) -} - -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 ( -
-
-

Tell us about your venue

-

Select all that apply — you can always change this later.

-
- -
-
-

Venue type

-
- {VENUE_TYPES.map(type => ( - - ))} -
- {errors.venueType &&

{errors.venueType}

} -
- -
- - -

- {t('setup.languageHint')} -

-
- -
-

Venue name

- onChange('venueName', e.target.value)} - autoComplete="off" - /> - {errors.venueName &&

{errors.venueName}

} -
-
- -
- - -
-
- ) -} - -function StepPin({ pin, onChange, onNext, onBack }) { - const hasPin = pin.length >= 4 - - return ( -
-
-

Set a quick-access PIN

-

- Optional. Used to unlock the dashboard quickly when it's locked, - without typing your full password. -

-
- -
- -
- - {hasPin && ( -

- PIN set — {pin.length} digits -

- )} - -
- - -
-
- ) -} - -function StepDone({ onGoToLogin, loading, error }) { - return ( -
-
- -
- -
-

You're all set!

-

- Your manager account is ready. Log in and start configuring your - products, tables, and staff. -

-
- -
- {['Add your menu and products', 'Set up tables and zones', 'Add your waiters'].map((tip, i) => ( -
- - {tip} -
- ))} -
- - {error &&

{error}

} - - -
- ) -} - -// ─── 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 ( -
-
-
- {/* Dot indicator for inner steps only */} - {step >= 1 && step <= INNER_STEPS && ( -
- -
- )} - - {step === 0 && setStep(1)} />} - - {step === 1 && ( - setStep(2)} - onBack={() => setStep(0)} - /> - )} - - {step === 2 && ( - setStep(3)} - onBack={() => setStep(1)} - /> - )} - - {step === 3 && ( - setStep(4)} - onBack={() => setStep(2)} - /> - )} - - {step === 4 && ( - - )} -
- -

- Xenia POS · First-time Setup -

-
-
- ) -} diff --git a/manager_dashboard/src/pages/TablesConfigTab.jsx b/manager_dashboard/src/pages/TablesConfigTab.jsx deleted file mode 100644 index 401c554..0000000 --- a/manager_dashboard/src/pages/TablesConfigTab.jsx +++ /dev/null @@ -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 ( -
-
- ) -} - -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
Φόρτωση…
- - 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 ( -
- {/* Toolbar */} -
- {/* Stats — left side */} - {!isLoading && !anySelected && !selectMode && ( -
- {totalTables} τραπέζια - · - {zoneCount} {zoneCount === 1 ? 'ζώνη' : 'ζώνες'} - {inactiveTables > 0 && ( - <> - · - {inactiveTables} ανενεργά - - )} -
- )} - - {/* Multi-select action bar */} - {(selectMode || anySelected) && ( - <> - {/* Select-all / deselect-all toggle + close */} - - - {anySelected && ( - <> - - - - - - )} - - - )} - - {!selectMode && !anySelected && } - - - {!selectMode && ( - - )} - - -
- - {/* Zone tabs */} -
- {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 ( -
- {/* Drop indicator line — left side of this tab */} - {showLineLeft && ( -
- )} - - - - {/* Drop indicator line — right side of the last group tab */} - {showLineRight && ( -
- )} -
- ) - })} -
- - {/* 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 ( -
- {g.name} - {g.prefix && {g.prefix}} - - -
- ) - })()} - - {/* Tables list */} -
- {visibleTables.length === 0 ? ( -

- {showInactive ? 'Δεν υπάρχουν τραπέζια.' : 'Δεν υπάρχουν ενεργά τραπέζια.'} -

- ) : (() => { - // 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 ( -
- {visibleTables.map((t, idx) => { - const isSelected = selected.has(t.id) - const isDuplicate = t.label && duplicateLabels.has(t.label) - const showCheckbox = selectMode || anySelected || isSelected - return ( -
toggleSelect(t.id) : undefined} - onMouseEnter={() => setAnyHovered(true)} - onMouseLeave={() => setAnyHovered(false)} - > - {/* Number / Checkbox */} -
- {showCheckbox ? ( - toggleSelect(t.id)} - className="w-4 h-4 rounded accent-sky-500 cursor-pointer" - onClick={e => e.stopPropagation()} - /> - ) : ( - {idx + 1} - )} - {!showCheckbox && ( - { setSelectMode(true); toggleSelect(t.id) }} - className="hidden group-hover:block w-4 h-4 rounded accent-sky-500 cursor-pointer" - onClick={e => e.stopPropagation()} - /> - )} -
- -

{t.label || `Τραπέζι ${t.number}`}

- {isDuplicate && ( - - Διπλό όνομα - - )} - {t.seat_count != null && ( - - {t.seat_count} θέσ. - - )} - {t.group && ( - - {t.group.name} - - )} - {!t.is_active && Ανενεργό} - {!selectMode && ( - <> - - {t.is_active - ? - : - } - - - )} -
- ) - })} -
- ) - })()} -
- - {/* Add single table */} - {addModal && ( - 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 && ( - 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 && ( - batchCreate.mutate(body)} - onClose={() => setBatchModal(null)} - /> - )} - - {/* Bulk move zone */} - {bulkMoveModal && ( - setBulkMoveModal(false)} - /> - )} - - {/* Bulk rename */} - {bulkRenameModal && ( - selected.has(t.id))} - onSave={handleBulkRename} - onClose={() => setBulkRenameModal(false)} - /> - )} - - {/* Group/Zone form */} - {groupModal !== null && ( - saveGroup.mutate(data)} - onDelete={groupModal.id ? () => deleteGroup.mutate(groupModal.id) : null} - onClose={() => setGroupModal(null)} - /> - )} - - {/* Delete confirmation */} - {confirmDelete && ( - { - 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)} - /> - )} -
- ) -} - -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 ( -
-
-

{title}

-
- - setForm(f => ({ ...f, label: e.target.value }))} - autoFocus - /> -
-

Αφήστε κενό για αυτόματη αρίθμηση.

- {form.label ? ( -

= MAX_TABLE_NAME_LENGTH ? 'text-red-500' : 'text-gray-400'}`}> - {labelLen}/{MAX_TABLE_NAME_LENGTH} -

- ) : null} -
- {labelTooLong && ( -

Το όνομα δεν μπορεί να υπερβαίνει τους {MAX_TABLE_NAME_LENGTH} χαρακτήρες.

- )} -
-
- - -
-
- - setForm(f => ({ ...f, seat_count: e.target.value ? Number(e.target.value) : null }))} - /> -

Αφήστε κενό αν δεν θέλετε να ορίσετε θέσεις.

-
-
- - -
-
-
- ) -} - -function BulkMoveModal({ count, groups, onSave, onClose }) { - const [groupId, setGroupId] = useState('') - - return ( -
-
-

Μετακίνηση σε ζώνη

-

{count} {count === 1 ? 'τραπέζι' : 'τραπέζια'} επιλεγμένα.

-
- - -
-
- - -
-
-
- ) -} - -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 ( -
-
-

Μαζική μετονομασία

-

- {count} {count === 1 ? 'τραπέζι' : 'τραπέζια'} επιλεγμένα — θα μετονομαστούν με τη σειρά που εμφανίζονται στη λίστα. -

- -
- - setPrefix(e.target.value)} - autoFocus - /> -
- -
- - setStartNumber(Math.max(1, Number(e.target.value) || 1))} - /> -
- - {/* Live preview */} - {trimmedPrefix && !lengthError && ( -
-

Προεπισκόπηση:

-
- {previewNames.map((name, i) => ( - - {name} - - ))} - {hasMore && ( - … +{count - 5} ακόμα - )} -
-
- )} - - {lengthError && ( -

{lengthError}

- )} - -
- - -
-
-
- ) -} - -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 ( -
-
-

Μαζική προσθήκη τραπεζιών

- {group &&

Ζώνη: {group.name}

} -
- - setPrefix(e.target.value)} - autoFocus - /> - {lengthError ? ( -

{lengthError}

- ) : ( -

Τα ονόματα θα αριθμηθούν αυτόματα συνεχίζοντας από εκεί που σταμάτησαν.

- )} -
-
- - setCount(Number(e.target.value))} /> -
-
- - -
-
-
- ) -} - -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 ( -
-
-

{group.id ? 'Επεξεργασία ζώνης' : 'Νέα ζώνη'}

-
- - setName(e.target.value)} autoFocus placeholder="π.χ. Beachside" /> -
-
- - setPrefix(e.target.value)} placeholder="π.χ. BS" /> -

Χρησιμοποιείται ως προτεινόμενο πρόθεμα στη μαζική προσθήκη.

-
-
- - -
-
- {onDelete && } - - -
-
-
- ) -} diff --git a/manager_dashboard/src/pages/overview/OverviewPage.jsx b/manager_dashboard/src/pages/overview/OverviewPage.jsx index 933bf86..268b44a 100644 --- a/manager_dashboard/src/pages/overview/OverviewPage.jsx +++ b/manager_dashboard/src/pages/overview/OverviewPage.jsx @@ -15,7 +15,7 @@ import { useCan, useModule } from '@xenia/access' import { useFormat, useTranslation } from '@xenia/i18n' import { Button, Dialog, IconButton, Spinner, cx } from '@xenia/ui' import client from '../../api/client' -import { LicenseContext } from '../../layouts/AppLayout' +import { LicenseContext } from '../../shell/licenseContext' import { useLiveQuery } from '../../live/useLiveQuery' import BookingsCard, { BookingDialog } from './BookingsCard' import DaySummaryDialog from './DaySummaryDialog' diff --git a/manager_dashboard/src/pages/setup/SetupWizard.jsx b/manager_dashboard/src/pages/setup/SetupWizard.jsx new file mode 100644 index 0000000..e1fef20 --- /dev/null +++ b/manager_dashboard/src/pages/setup/SetupWizard.jsx @@ -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 ( +
+
+
+ {step >= 1 && step <= 3 && ( +
+ {[1, 2, 3].map(i => )} +
+ )} + + {name === 'welcome' && ( +
+ +
+

{t('setup.welcome')}

+

{t('setup.welcomeIntro')}

+
+
    + {['account', 'venue', 'ready'].map((k, i) => ( +
  1. + {i + 1}{t(`setup.plan.${k}`)} +
  2. + ))} +
+ + {Object.entries(LANGUAGE_NAMES).map(([code, label]) => ( + + ))} + + +
+ )} + + {name === 'account' && ( +
+
+ + setAccount(a => ({ ...a, username: e.target.value }))} data-testid="setup-username" /> + + + setAccount(a => ({ ...a, fullName: e.target.value }))} data-testid="setup-full-name" /> + + + setAccount(a => ({ ...a, email: e.target.value }))} /> + +
+ + setAccount(a => ({ ...a, password: e.target.value }))} data-testid="setup-password" /> + + + setAccount(a => ({ ...a, confirm: e.target.value }))} data-testid="setup-confirm" /> + +
+
+ )} + + {name === 'venue' && ( +
+
+ + + {VENUE_TYPES.map(k => { + const Icon = ICONS[k] + const on = venue.types.includes(k) + return ( + + ) + })} + + + + setVenue(v => ({ ...v, name: e.target.value }))} data-testid="setup-venue-name" /> + +
+ + setVenue(v => ({ ...v, timezone: e.target.value }))} data-testid="setup-timezone" + options={timeZones(venue.timezone).map(z => ({ value: z, label: z.replace(/_/g, ' ') }))} /> + +
+

{t('setup.languageHint')}

+
+ )} + + {name === 'pin' && ( +
+
+
+ + setPin(p => ({ ...p, pin: e.target.value.replace(/\D/g, '').slice(0, 6) }))} data-testid="setup-pin" /> + + + setPin(p => ({ ...p, again: e.target.value.replace(/\D/g, '').slice(0, 6) }))} data-testid="setup-pin-again" /> + +
+
+ )} + + {name === 'done' && ( +
+ +
+

{t('setup.doneTitle')}

+

{t('setup.doneIntro')}

+
+
    + {['menu', 'tables', 'staff'].map(k =>
  • )} +
+ {finish.error &&

{errorMessage(finish.error, t)}

} + + + + +
+ )} +
+

{t('setup.footer')}

+
+
+ ) +} + +function Header({ title, intro }) { + return ( +
+

{title}

+

{intro}

+
+ ) +} + +function Nav({ onBack, onNext, next }) { + const { t } = useTranslation('manager') + return ( + + + + + ) +} diff --git a/manager_dashboard/src/pages/setup/setupLogic.js b/manager_dashboard/src/pages/setup/setupLogic.js new file mode 100644 index 0000000..82d7185 --- /dev/null +++ b/manager_dashboard/src/pages/setup/setupLogic.js @@ -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' +} diff --git a/manager_dashboard/src/pages/tables/TableDialogs.jsx b/manager_dashboard/src/pages/tables/TableDialogs.jsx new file mode 100644 index 0000000..d8e8f02 --- /dev/null +++ b/manager_dashboard/src/pages/tables/TableDialogs.jsx @@ -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 ( + + + + }> +
+ + set('label', e.target.value)} data-testid="table-name" /> + + + set('seats', e.target.value)} className="w-24" /> + +
+
+ ) +} + +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 ( + setRemoving(false)} title={t('tablesList.zoneDeleteTitle', { name: zone.name })} description={t('tablesList.zoneDeleteBody')} + footer={<> + + + } /> + ) + } + return ( + + {!isNew && } + + + }> +
+ + set('name', e.target.value)} data-testid="zone-name" /> + + + set('prefix', e.target.value)} data-testid="zone-prefix" /> + + + +
+
+ ) +} + +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 ( + + + + }> +
+ + setPrefix(e.target.value)} data-testid="batch-prefix" /> + + + setCount(e.target.value.replace(/\D/g, ''))} data-testid="batch-count" /> + +
+
+ ) +} + +export function MoveDialog({ count, zones, onClose, onMove }) { + const { t } = useTranslation('manager') + const [groupId, setGroupId] = useState('') + const [busy, setBusy] = useState(false) + return ( + + + + }> + + setPrefix(e.target.value)} data-testid="rename-prefix" /> + + + setStart(e.target.value.replace(/\D/g, ''))} /> + +
+ {ok && ( +

+ {s.names.slice(0, 5).map(x => {x})} + {s.names.length > 5 && {t('tablesList.andMore', { count: s.names.length - 5 })}} +

+ )} +
+ + ) +} diff --git a/manager_dashboard/src/pages/tables/TablesListTab.jsx b/manager_dashboard/src/pages/tables/TablesListTab.jsx new file mode 100644 index 0000000..f53c0c5 --- /dev/null +++ b/manager_dashboard/src/pages/tables/TablesListTab.jsx @@ -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
+ 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 ( +
+
+ {picking || picked.size ? (<> + + + {picked.size > 0 && (<> + + + + )} + ) : ( + + {t('tablesList.counts', { tables: tables.length, zones: zones.length })} + {tables.some(x => !x.is_active) && <> · {t('tablesList.offCount', { count: tables.filter(x => !x.is_active).length })}} + + )} + + + {!picking && } + + +
+ +
+ {tabs.map(x => { + const i = x.zone ? zones.indexOf(x.zone) : -1 + return ( + + ) + })} +
+ + {zone && ( +
+ {zone.name} + {zone.prefix && {zone.prefix}} + + +
+ )} + +
+ {!shown.length ? : ( +
    + {shown.map((x, i) => { + const on = picked.has(x.id) + const busy = x.has_active_order + return ( +
  • + {picking || picked.size + ? pick(x.id)} aria-label={t('tablesList.pickOne', { name: name(x) })} className="w-4 h-4 accent-accent" /> + : {i + 1}} + {name(x)} + {x.label && dupes.has(x.label) && {t('tablesList.duplicate')}} + {x.seat_count != null && {t('tablesList.seats', { count: x.seat_count })}} + {tab === 'all' && x.group && {x.group.name}} + {!x.is_active && {t('tablesList.off')}} + {!picking && !picked.size && ( + + setDialog({ kind: 'table', table: x })}> + {x.is_active + ? setDialog({ kind: 'off', table: x })}> + : update.mutate({ id: x.id, is_active: true })}>} + setDialog({ kind: 'delete', table: x })}> + + )} +
  • + ) + })} +
+ )} +
+ + {dialog?.kind === 'table' && { close(); changed() }} />} + {dialog?.kind === 'zone' && { close(); changed() }} />} + {dialog?.kind === 'batch' && { close(); changed() }} />} + {dialog?.kind === 'move' && each([...picked], id => client.put(`/api/tables/${id}`, { group_id: groupId }), t('tablesList.moved', { count: picked.size }))} />} + {dialog?.kind === 'rename' && 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?.kind === 'deleteMany' && ( + + + + } /> + )} +
+ ) +} diff --git a/manager_dashboard/src/pages/tables/tablesLogic.js b/manager_dashboard/src/pages/tables/tablesLogic.js new file mode 100644 index 0000000..e342927 --- /dev/null +++ b/manager_dashboard/src/pages/tables/tablesLogic.js @@ -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 +} diff --git a/manager_dashboard/src/shell/AppLayout.jsx b/manager_dashboard/src/shell/AppLayout.jsx new file mode 100644 index 0000000..a5713d9 --- /dev/null +++ b/manager_dashboard/src/shell/AppLayout.jsx @@ -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 XeniaPOS + if (!page.parent) return

{t(page.label)}

+ return ( + + ) +} + +/** 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 ( +
+
+ ) +} + +// 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 ( +
+
+
+
+

{t('lock.title')}

+

{displayName}

+
+ + +
+
+ ) +} + +/** 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 ( + +
+ {locked && loginUsername && { unlock(u); touched() }} onLogout={signOut} />} + +
+ +
+
+
+ +
+
+
+
+ +
+
+ ) +} diff --git a/manager_dashboard/src/shell/ProfileDialog.jsx b/manager_dashboard/src/shell/ProfileDialog.jsx new file mode 100644 index 0000000..a13fd7b --- /dev/null +++ b/manager_dashboard/src/shell/ProfileDialog.jsx @@ -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 ( + + + + }> +
+
+ set('fullName', e.target.value)} data-testid="profile-name" /> + set('username', e.target.value)} /> +
+
+ {t('profile.password')} +

{t('profile.keepHint')}

+ set('current', e.target.value)} /> +
+ set('next', e.target.value)} /> + set('again', e.target.value)} /> +
+
+
+ {t('profile.pin')} +

{t('profile.pinHint')}

+
+ set('pin', digits(e.target.value))} data-testid="profile-pin" /> + set('pin2', digits(e.target.value))} data-testid="profile-pin2" /> +
+
+
+
+ ) +} diff --git a/manager_dashboard/src/shell/Sidebar.jsx b/manager_dashboard/src/shell/Sidebar.jsx new file mode 100644 index 0000000..bb253ce --- /dev/null +++ b/manager_dashboard/src/shell/Sidebar.jsx @@ -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 ( + cx(link(isActive), 'gap-2.5 px-3 py-2 mx-2 text-label opacity-70')}> + + ) + } + return ( + cx(link(isActive), 'gap-2.5 px-3 py-2 mx-2 text-label')}> + {({ isActive }) => (<> + + ) +} + +function Group({ group, icon: Icon, label, children, open, onToggle }) { + const { t } = useTranslation('manager') + const { pathname } = useLocation() + const here = inGroup(children, pathname) + return ( +
+ + {open &&
{children.map(c => )}
} +
+ ) +} + +function Solo({ to, icon: Icon, label, badge, onNavigate }) { + const { t } = useTranslation('manager') + return ( + cx(link(isActive), 'px-3 py-2.5 text-body')}> + + + {t(label)} + + ) +} + +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 ( + + ) +} diff --git a/manager_dashboard/src/shell/licenseContext.js b/manager_dashboard/src/shell/licenseContext.js new file mode 100644 index 0000000..4a3a853 --- /dev/null +++ b/manager_dashboard/src/shell/licenseContext.js @@ -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) diff --git a/manager_dashboard/src/shell/profileLogic.js b/manager_dashboard/src/shell/profileLogic.js new file mode 100644 index 0000000..db0e0fb --- /dev/null +++ b/manager_dashboard/src/shell/profileLogic.js @@ -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 +} diff --git a/manager_dashboard/src/ui/Badge.jsx b/manager_dashboard/src/ui/Badge.jsx deleted file mode 100644 index b44d739..0000000 --- a/manager_dashboard/src/ui/Badge.jsx +++ /dev/null @@ -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 ( - - - {pulse && (status === 'active' || status === 'open') && ( - - )} - - {label} - - ) -} diff --git a/manager_dashboard/src/ui/Button.jsx b/manager_dashboard/src/ui/Button.jsx deleted file mode 100644 index c581432..0000000 --- a/manager_dashboard/src/ui/Button.jsx +++ /dev/null @@ -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 ( - - ) -} diff --git a/manager_dashboard/src/ui/DeleteConfirmModal.jsx b/manager_dashboard/src/ui/DeleteConfirmModal.jsx deleted file mode 100644 index 8dd47a0..0000000 --- a/manager_dashboard/src/ui/DeleteConfirmModal.jsx +++ /dev/null @@ -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 ( -
-
e.stopPropagation()} - > - {/* Header */} -
-
- -
-
-
{title}
-
{description}
-
-
- -
- {step === 1 && ( - <> -

- Αυτή η ενέργεια είναι μη αναστρέψιμη. -

-
- - -
- - )} - - {step === 2 && ( - <> -
- - 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" - /> -
-
- - -
- - )} -
-
-
- ) -} diff --git a/manager_dashboard/src/ui/Input.jsx b/manager_dashboard/src/ui/Input.jsx deleted file mode 100644 index 3ac4d60..0000000 --- a/manager_dashboard/src/ui/Input.jsx +++ /dev/null @@ -1,64 +0,0 @@ -import { INPUT_CLASS } from './tokens' - -// Text input -export function Input({ className = '', ...props }) { - return ( -
- -
- ) -} - -// Native - {children} - -
- ) -} - -// Date input -export function DateInput({ label, icon: Icon, className = '', ...props }) { - return ( - - ) -} - -// Labelled text input with optional leading icon -export function LabelledInput({ label, icon: Icon, className = '', ...props }) { - return ( -
- {Icon && } - {label && ( - - {label} - - )} - -
- ) -} diff --git a/manager_dashboard/src/ui/Modal.jsx b/manager_dashboard/src/ui/Modal.jsx deleted file mode 100644 index 6f96ea9..0000000 --- a/manager_dashboard/src/ui/Modal.jsx +++ /dev/null @@ -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): -// -//

Θέλετε σίγουρα να διαγράψετε αυτό το στοιχείο;

-// -// -// -// -//
- -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 ( -
{ if (e.target === e.currentTarget) onClose?.() }} - > -
- {/* Header */} - {title && ( -
-

{title}

- {onClose && ( - - )} -
- )} - - {/* Tab bar */} - {tabs && ( -
- {tabs.map(tab => ( - - ))} -
- )} - - {/* Body — scrollable */} -
- {children} -
- - {/* Footer — fixed outside scroll area when provided via prop */} - {footer && ( -
- {footer} -
- )} -
-
- ) -} - -// Footer helper — for modals without tabs (renders inline, modal doesn't scroll) -function ModalFooter({ children }) { - return ( -
- {children} -
- ) -} - -Modal.Footer = ModalFooter - -// Convenience: ConfirmModal wrapping Modal for the most common pattern -export function ConfirmModal({ - title, - message, - confirmLabel = 'Επιβεβαίωση', - confirmVariant = 'danger', - onConfirm, - onCancel, -}) { - return ( - - {message &&

{message}

} - - - - -
- ) -} diff --git a/manager_dashboard/src/ui/Tabs.jsx b/manager_dashboard/src/ui/Tabs.jsx deleted file mode 100644 index f895884..0000000 --- a/manager_dashboard/src/ui/Tabs.jsx +++ /dev/null @@ -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 ( -
- {tabs.map((tab) => { - const isActive = tab.id === active - const Icon = tab.icon ?? tab.Icon - return ( - - ) - })} -
- ) -} - -// ─── Secondary sub-tab row (pill style) ────────────────────────────────────── -export function TabBar({ tabs, active, onChange }) { - return ( -
- {tabs.map((tab) => { - const isActive = tab.id === active - return ( - - ) - })} -
- ) -} - -// ─── TabRow: identical to TabGroup, kept as named alias ────────────────────── -export function TabRow({ tabs, active, onChange }) { - return -} - -// ─── 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: -// -// -// {/* optional */} -//
...
-//
-export function TabCard({ children, className = '' }) { - return ( -
- {children} -
- ) -} diff --git a/manager_dashboard/src/ui/tokens.js b/manager_dashboard/src/ui/tokens.js deleted file mode 100644 index 19e84bd..0000000 --- a/manager_dashboard/src/ui/tokens.js +++ /dev/null @@ -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' diff --git a/manager_dashboard/tailwind.config.js b/manager_dashboard/tailwind.config.js index 40f7596..a23d0a5 100644 --- a/manager_dashboard/tailwind.config.js +++ b/manager_dashboard/tailwind.config.js @@ -10,17 +10,6 @@ export default { fontFamily: { sans: ['Google Sans', 'system-ui', 'sans-serif'], }, - colors: { - primary: { - DEFAULT: '#0f766e', - 50: '#f0fdfa', - 100: '#ccfbf1', - 600: '#0d9488', - 700: '#0f766e', - 800: '#115e59', - 900: '#134e4a', - }, - }, fontSize: { base: ['1rem', { lineHeight: '1.5rem' }], }, diff --git a/manager_dashboard/tests/shell.test.mjs b/manager_dashboard/tests/shell.test.mjs new file mode 100644 index 0000000..3ff4c31 --- /dev/null +++ b/manager_dashboard/tests/shell.test.mjs @@ -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']) +}) diff --git a/manager_dashboard/v2.json b/manager_dashboard/v2.json index 2d2e166..ba5b2c2 100644 --- a/manager_dashboard/v2.json +++ b/manager_dashboard/v2.json @@ -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`.", - "paths": [ - "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" - ], + "_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": ["src"], "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" ] } diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index c0e4ca7..8dc7ae1 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -48,12 +48,35 @@ "deliveryFees": "Online παραγγελίες (ρύθμιση)", "qrCodes": "QR τραπεζιών", "media": "Πολυμέσα", - "signage": "Προβολή" + "signage": "Προβολή", + "main": "Κύριο μενού" }, "profile": { "edit": "Επεξεργασία προφίλ", "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": { "title": "Σύνδεση", @@ -678,7 +701,61 @@ "setup": { "language": "Γλώσσα προσωπικού", "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": { "title": "Περιοχές και χρεώσεις διανομής", @@ -3684,5 +3761,120 @@ "deleteYes": "Διαγραφή", "deleted": "Διαγράφηκε", "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}} ακόμα" } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index 7be3ca1..75444b9 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -48,12 +48,35 @@ "deliveryFees": "Online ordering", "qrCodes": "Table QR codes", "media": "Media", - "signage": "Signage" + "signage": "Signage", + "main": "Main menu" }, "profile": { "edit": "Edit profile", "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": { "title": "Sign in", @@ -678,7 +701,61 @@ "setup": { "language": "Staff language", "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": { "title": "Delivery areas and fees", @@ -3684,5 +3761,120 @@ "deleteYes": "Delete", "deleted": "Deleted", "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" } } diff --git a/packages/ui/src/tokens.css b/packages/ui/src/tokens.css index 274292d..47a6340 100644 --- a/packages/ui/src/tokens.css +++ b/packages/ui/src/tokens.css @@ -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) ─────── * 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 diff --git a/packages/ui/tailwind-preset.js b/packages/ui/tailwind-preset.js index ad3a912..28dc1e1 100644 --- a/packages/ui/tailwind-preset.js +++ b/packages/ui/tailwind-preset.js @@ -24,6 +24,7 @@ export default { extend: { colors: { 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') }, line: { DEFAULT: c('line'), strong: c('line-strong') }, ink: { DEFAULT: c('ink'), 2: c('ink-2'), 3: c('ink-3') }, @@ -34,6 +35,8 @@ export default { info: tone('info'), // 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}`)])), + // 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: { caption: ['var(--x-text-caption)', { lineHeight: 'var(--x-leading-caption)' }], diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index a4ec7fe..3feef37 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -770,6 +770,46 @@ try { await page.getByTestId('user-menu').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.getByText('Log files', { exact: true }).click() const today = new Date().toISOString().slice(0, 10) diff --git a/tests/e2e/run-all.mjs b/tests/e2e/run-all.mjs index ff42c24..fbb6706 100644 --- a/tests/e2e/run-all.mjs +++ b/tests/e2e/run-all.mjs @@ -29,6 +29,7 @@ const suites = [ ['ui (@xenia/ui + @xenia/i18n)', 'node', ['ui.mjs'], E2E], ['waiter (sign-in, keys, prices, languages, history, look, bookings)', 'node', ['waiter.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], ['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E], ['signage (the player on a TV, the editor)', 'node', ['signage.mjs'], E2E], diff --git a/tests/e2e/setup.mjs b/tests/e2e/setup.mjs new file mode 100644 index 0000000..41449f3 --- /dev/null +++ b/tests/e2e/setup.mjs @@ -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)