feat(manager): notification bell, sign-in/venue/print settings, log download (platform-v2 2.6f)

- Bell in the header: /api/platform/notifications with unread count, live via
  the new LiveProvider (one createLiveClient connection) on platform_notification
  and reconnect; mark read / all; warning+critical pop a toast.
- Settings: Sign-in card (manager/waiter/device modes, require username, one
  session per manager/waiter, username autofill) replaces the dead v1
  security.login_method card; new "Venue & language" tab (language, time zone);
  print alert threshold in Printing. Tab labels are i18n keys.
- Technical > Log files: list + download of the daily logs (owner-level).
  Backend: GET /api/system/logs, /api/system/logs/{date} (core.settings.manage),
  error system.log_not_found.
- Setup wizard asks staff language and time zone (setup/init stores them).
- @xenia/ui theme helpers (applyTheme, getStoredTheme); the manager stays light
  until phase 6 converts the older pages (owner decision 2026-11-14).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 09:01:26 +02:00
co-authored by Claude Opus 5.5
parent 92bc1b0113
commit 2426ffddad
36 changed files with 995 additions and 92 deletions
+1 -1
View File
@@ -171,7 +171,7 @@ Design tokens are CSS variables prefixed `--x-` (`packages/ui/src/tokens.css`),
New UI text goes into `packages/i18n/locales/en/<ns>.json` first, then `el` (same keys, same `{{placeholders}}`), and is shown with `t()` from `@xenia/i18n` (`useTranslation`, re-exported). Dates and times are shown only through `useFormat()` (`formatTime`, `formatDateTime`, `formatDate`, `formatRelative`), which use the venue zone from bootstrap; money with `formatMoney`, numbers with `formatNumber`; typed numbers are read with `parseNumber` (comma or dot). Business dates (`YYYY-MM-DD`) go to `formatDate` as they are. `npm test -w @xenia/i18n` runs `scripts/check-i18n.mjs`, which fails on keys missing in English, placeholder mismatches, and `toLocale…String()` / `new Intl.DateTimeFormat(` without `timeZone` in new code (`packages/*`, `terminal/`); it warns for missing Greek. Module names, their limits and **every permission key** have texts in `modules.json` (`modules:<module>.name`, `.limits.<key>`, `.permissions.<rest of the key, nested by its dots>`); `tests/test_module_texts.py` fails for a new module or key without them in both languages. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `<UiLabelsProvider labels={useUiLabels()}>` at the app root.
**CS-18. Frontends talk to the backend through `@xenia/api` and read access from bootstrap** (branch `platform-v2`, D-7, D-10, §9).
An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. Lock screens never log in again: they call `POST /api/auth/unlock {pin}` with the current session (same token; 5 wrong PINs end the session); manager sign-in sends `client: "manager"` and reads its mode from bootstrap `login`. The app root is `<AccessProvider client token i18n>`: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand).
An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. Lock screens never log in again: they call `POST /api/auth/unlock {pin}` with the current session (same token; 5 wrong PINs end the session); manager sign-in sends `client: "manager"` and reads its mode from bootstrap `login`. The app root is `<AccessProvider client token i18n>`: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand). In the manager there is one connection, `live/LiveProvider.jsx` (opened with the signed-in shell); components listen with `useLiveEvent(type, handler)` (`'ready'` fires after each reconnect: refetch then).
**CS-15. Support access is a challenge code, never a password** (branch `platform-v2`, D-16).
There is no master account. A site's `SUPPORT_SECRET` (env only) comes from `tools/support_code.py --site-secret <SITE_ID>`, derived from the builder's master key in `%USERPROFILE%\.xenia\support_master_key.txt` (outside the repo, back it up). The derivation lives in `local_backend/core/support_codes.py` (stdlib only, the tool loads it by path) and is re-implemented for the e2e suites in `tests/e2e/lib/support.mjs`; `tests/test_support.py` pins a vector both must match. The e2e backends log in through support access (`login()` in `lib/proc.mjs`).
+1
View File
@@ -86,6 +86,7 @@ CODES: dict[str, tuple[int, str]] = {
# domain
"order.not_found": (404, "Order {order_id} not found."),
"notification.not_found": (404, "Notification {notification_id} not found."),
"system.log_not_found": (404, "There is no log file for {date}."),
"catalog.unknown_category": (422, "There is no category {category_id}."),
"catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."),
}
+27
View File
@@ -277,3 +277,30 @@ class RequestContextMiddleware:
lvl = logging.WARNING if (code or 500) >= 500 else logging.INFO
_http_log.log(lvl, "http %s %s status=%s ms=%d", method, scope.get("path"), code, ms)
_ctx.reset(token)
# ── download (plan step 2.6f) ────────────────────────────────────────────────
def log_dir() -> Path:
"""Where the daily files are: the active handler's folder, else the default."""
return _file_handler.directory if _file_handler is not None else default_log_dir()
def list_log_files(directory: Path | None = None) -> list[dict]:
"""[{date, name, size}] newest first, for the manager's log download."""
d = directory or log_dir()
out = []
if d.is_dir():
for f in d.glob(f"{FILE_PREFIX}*.log"):
m = _FILE_RE.match(f.name)
if m:
out.append({"date": m.group(1), "name": f.name, "size": f.stat().st_size})
return sorted(out, key=lambda x: x["date"], reverse=True)
def log_file_for(date_str: str, directory: Path | None = None) -> Path | None:
"""The file of one UTC day, or None (bad date or no file). Only names we write."""
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date_str or ""):
return None
f = (directory or log_dir()) / f"{FILE_PREFIX}{date_str}.log"
return f if f.is_file() else None
+28
View File
@@ -26,6 +26,8 @@ class SetupInitRequest(BaseModel):
venue_type: Optional[str] = None
venue_name: Optional[str] = None
pin: Optional[str] = None
language: Optional[str] = None # venue.language (2.6f): v2 defaults to English otherwise
timezone: Optional[str] = None # venue.timezone, IANA (the browser's zone)
class SetupInitResponse(BaseModel):
@@ -81,6 +83,16 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
if existing:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken.")
from core import i18n, timeutil
from core.errors import XeniaError
if body.language and not i18n.is_supported(body.language):
raise XeniaError("validation.unknown_language", language=body.language)
if body.timezone:
try:
timeutil.validate_tz(body.timezone)
except ValueError:
raise XeniaError("validation.unknown_timezone", timezone=body.timezone)
password_hash = bcrypt.hashpw(body.password.encode(), bcrypt.gensalt()).decode()
raw_pin = body.pin if (body.pin and body.pin.isdigit() and 4 <= len(body.pin) <= 6) else "0000"
@@ -100,6 +112,19 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
db.add(user)
# Persist venue settings if provided
from models.settings import PosSettings
def _put(key, value):
row = db.query(PosSettings).filter(PosSettings.key == key).first()
if row:
row.value = value
row.updated_at = utcnow()
else:
db.add(PosSettings(key=key, value=value, updated_at=utcnow()))
if body.language:
_put("venue.language", body.language)
if body.timezone:
_put("venue.timezone", body.timezone)
if body.venue_name or body.venue_type:
from models.settings import PosSettings
from datetime import datetime, timezone
@@ -120,6 +145,9 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
db.add(PosSettings(key="venue.type", value=body.venue_type, updated_at=now))
db.commit()
if body.language or body.timezone:
i18n.invalidate()
timeutil.invalidate()
db.refresh(user)
add_user_to_system_group(db, user.id)
return SetupInitResponse(ok=True)
+24
View File
@@ -1,5 +1,6 @@
from core.access.deps import public
from core.access.queries import holders_filter
from core.access.deps import require
import asyncio
import ipaddress
import json
@@ -77,6 +78,29 @@ def _lock_reason() -> str | None:
return None
# ── Log download (plan step 2.6f, APPS_PLATFORM §10) ───────────────────────────
# The daily files of core/logging.py. Owner-level (core.settings.manage): lines carry
# usernames, IPs and order ids (never secrets).
@router.get("/logs")
def list_logs(user: User = Depends(require("core.settings.manage"))):
"""[{date, name, size}] newest first (UTC days)."""
from core.logging import list_log_files
return list_log_files()
@router.get("/logs/{date}")
def download_log(date: str, user: User = Depends(require("core.settings.manage"))):
"""One day's file as an attachment (today's is still being written: a snapshot)."""
from fastapi.responses import FileResponse
from core.errors import XeniaError
from core.logging import log_file_for
f = log_file_for(date)
if f is None:
raise XeniaError("system.log_not_found", date=date)
return FileResponse(f, media_type="text/plain; charset=utf-8", filename=f.name)
@router.get("/status")
def system_status(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
printers = db.query(Printer).filter(Printer.is_active == True).all()
+35
View File
@@ -0,0 +1,35 @@
"""Log download for the manager (plan step 2.6f): list + one day's file, owner-level."""
import pytest
from core import logging as xlog
@pytest.fixture
def logs(tmp_path, monkeypatch):
(tmp_path / "xenia-2026-11-13.log").write_text("2026-11-13T10:00:00.000Z INFO x [req=- user=- device=-] hello\n", encoding="utf-8")
(tmp_path / "xenia-2026-11-14.log").write_text("today\n", encoding="utf-8")
(tmp_path / "other.txt").write_text("not a log", encoding="utf-8")
monkeypatch.setattr(xlog, "log_dir", lambda: tmp_path)
return tmp_path
def test_list_and_download(client, make_user, login, logs):
h = login(make_user(role="owner"))
rows = client.get("/api/system/logs", headers=h).json()
assert [r["date"] for r in rows] == ["2026-11-14", "2026-11-13"] and rows[1]["size"] > 10
r = client.get("/api/system/logs/2026-11-13", headers=h)
assert r.status_code == 200 and "hello" in r.text
assert 'filename="xenia-2026-11-13.log"' in r.headers["content-disposition"]
def test_missing_and_bad_dates(client, make_user, login, logs):
h = login(make_user(role="owner"))
for d in ("2026-01-01", "..%2Fpos", "x"):
r = client.get(f"/api/system/logs/{d}", headers=h)
assert r.status_code == 404, (d, r.text)
assert client.get("/api/system/logs/2026-01-01", headers=h).json()["error"]["code"] == "system.log_not_found"
def test_needs_settings_permission(client, make_user, login, logs):
h = login(make_user(role="staff_manager"))
assert client.get("/api/system/logs", headers=h).json()["error"]["code"] == "access.denied"
@@ -0,0 +1,24 @@
"""The setup wizard sets the venue language and time zone (plan step 2.6f)."""
import pytest
from models.settings import PosSettings
def _setting(db, key):
row = db.query(PosSettings).filter_by(key=key).first()
return row.value if row else None
def test_init_sets_language_and_timezone(client, db):
from models.user import User
if db.query(User).count():
pytest.skip("db has users")
bad = client.post("/api/setup/init", json={"username": "boss", "password": "secret1", "language": "xx"})
assert bad.json()["error"]["code"] == "validation.unknown_language"
bad = client.post("/api/setup/init", json={"username": "boss", "password": "secret1", "timezone": "Mars/Base"})
assert bad.json()["error"]["code"] == "validation.unknown_timezone"
r = client.post("/api/setup/init", json={"username": "boss", "password": "secret1", "language": "el",
"timezone": "Europe/Berlin"})
assert r.status_code in (200, 201), r.text
db.expire_all()
assert _setting(db, "venue.language") == "el" and _setting(db, "venue.timezone") == "Europe/Berlin"
+2 -1
View File
@@ -5,6 +5,7 @@ import RouteGuard from './shell/RouteGuard'
import { createI18n } from '@xenia/i18n'
import useAuthStore from './store/authStore'
import AppLayout from './layouts/AppLayout'
import LiveProvider from './live/LiveProvider'
import client from './api/client'
// Auth / setup
@@ -141,7 +142,7 @@ export default function App() {
<Route path="/login" element={<SetupGuard><LoginPage /></SetupGuard>} />
<Route path="/kds" element={<RequireAuth><RouteGuard><KdsPage /></RouteGuard></RequireAuth>} />
<Route path="/" element={<RequireAuth><AppLayout /></RequireAuth>}>
<Route path="/" element={<RequireAuth><LiveProvider><AppLayout /></LiveProvider></RequireAuth>}>
<Route index element={<Navigate to="/dashboard" replace />} />
{/* ── Operation ── */}
@@ -0,0 +1,128 @@
// The bell in the manager's header (plan step 2.6f, APPS_PLATFORM §10): platform
// notifications (license limits and expiry, support access used, print failures…) from
// GET /api/platform/notifications, in the reader's language (the backend renders `message`).
// - The unread count shows on the bell; it refetches on the live event
// `platform_notification` {id} and after every reconnect ('ready').
// - A NEW warning/critical one also pops up as a toast.
// - Opening an item marks it read; "Mark all as read" does the rest.
// Not staff chat (/api/notifications, the chat module), which stays separate.
import { useCallback, useEffect, useRef, useState } from 'react'
import toast from 'react-hot-toast'
import { Bell, CheckCheck } from 'lucide-react'
import { useTranslation, useFormat } from '@xenia/i18n'
import client from '../api/client'
import { useLiveEvent } from '../live/useLiveEvent'
const DOT = { info: 'bg-info', warning: 'bg-warning', critical: 'bg-danger' }
const FALLBACK_REFRESH_MS = 5 * 60_000
export default function NotificationBell() {
const { t } = useTranslation('manager')
const f = useFormat()
const [data, setData] = useState({ items: [], unread: 0 })
const [open, setOpen] = useState(false)
const ref = useRef(null)
const load = useCallback(async () => {
try {
const r = await client.get('/api/platform/notifications', { params: { limit: 30 } })
setData(r.data)
return r.data
} catch {
return null // the bell stays as it was; the next event or refresh tries again
}
}, [])
useEffect(() => {
load()
const id = setInterval(load, FALLBACK_REFRESH_MS)
return () => clearInterval(id)
}, [load])
useLiveEvent('ready', load)
useLiveEvent('platform_notification', async ev => {
const fresh = await load()
const n = fresh?.items.find(x => x.id === ev?.id)
if (n && n.severity !== 'info') toast(n.message, { icon: '⚠️', duration: 8000 })
})
useEffect(() => {
if (!open) return undefined
const outside = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false) }
const escape = e => { if (e.key === 'Escape') setOpen(false) }
document.addEventListener('mousedown', outside)
document.addEventListener('keydown', escape)
return () => {
document.removeEventListener('mousedown', outside)
document.removeEventListener('keydown', escape)
}
}, [open])
async function markRead(n) {
if (n.read) return
setData(d => ({ unread: Math.max(0, d.unread - 1), items: d.items.map(x => (x.id === n.id ? { ...x, read: true } : x)) }))
await client.post(`/api/platform/notifications/${n.id}/read`).catch(() => {})
}
async function markAll() {
setData(d => ({ unread: 0, items: d.items.map(x => ({ ...x, read: true })) }))
await client.post('/api/platform/notifications/read-all').catch(() => {})
load()
}
const badge = data.unread > 9 ? '9+' : String(data.unread)
return (
<div className="relative" ref={ref}>
<button
onClick={() => { setOpen(o => !o); if (!open) load() }}
className="relative flex h-8 w-8 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-700"
aria-label={data.unread ? t('notifications.bellUnread', { count: data.unread }) : t('notifications.bell')}
aria-haspopup="dialog"
aria-expanded={open}
data-testid="notif-bell"
>
<Bell className="h-3.5 w-3.5" />
{data.unread > 0 && (
<span className="absolute -top-1.5 -right-1.5 min-w-[18px] h-[18px] px-1 rounded-full bg-danger text-danger-fg text-[10px] font-bold leading-[18px] text-center"
data-testid="notif-count">{badge}</span>
)}
</button>
{open && (
<div className="absolute right-0 top-full mt-1.5 w-96 max-w-[calc(100vw-2rem)] rounded-card border border-line bg-surface shadow-popover z-popover"
role="dialog" aria-label={t('notifications.title')} data-testid="notif-panel">
<div className="flex items-center justify-between px-4 py-2.5 border-b border-line">
<span className="text-label font-semibold text-ink">{t('notifications.title')}</span>
{data.unread > 0 && (
<button onClick={markAll} className="inline-flex items-center gap-1 text-caption text-accent-ink hover:underline" data-testid="notif-read-all">
<CheckCheck className="h-3.5 w-3.5" />{t('notifications.markAll')}
</button>
)}
</div>
{data.items.length === 0
? <p className="px-4 py-8 text-center text-label text-ink-3">{t('notifications.empty')}</p>
: (
<ul className="max-h-[60vh] overflow-y-auto divide-y divide-line">
{data.items.map(n => (
<li key={n.id}>
<button onClick={() => markRead(n)} className={`w-full text-left flex gap-3 px-4 py-3 hover:bg-surface-2 ${n.read ? '' : 'bg-accent-soft/40'}`}
data-testid={`notif-${n.id}`} data-read={n.read ? 'true' : 'false'}>
<span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${DOT[n.severity] || DOT.info}`} />
<span className="flex-1 min-w-0">
<span className={`block text-label ${n.read ? 'text-ink-2' : 'text-ink font-medium'}`}>{n.message}</span>
<span className="block text-caption text-ink-3 mt-0.5">
{f.formatRelative(n.last_at)}
{n.count > 1 && ` · ${t('notifications.times', { count: n.count })}`}
</span>
</span>
</button>
</li>
))}
</ul>
)}
</div>
)}
</div>
)
}
+4 -8
View File
@@ -1,7 +1,8 @@
import { Outlet, useNavigate, useLocation } from 'react-router-dom'
import { useState, useEffect, useRef, createContext } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Lock, AlertTriangle, ShieldAlert, Search, Bell, ChevronRight } from 'lucide-react'
import { Lock, AlertTriangle, ShieldAlert, Search, ChevronRight } from 'lucide-react'
import NotificationBell from '../components/NotificationBell'
import Sidebar from '../components/Sidebar'
import useAuthStore from '../store/authStore'
import client from '../api/client'
@@ -271,13 +272,8 @@ export default function AppLayout() {
/>
</div>
{/* Notifications (placeholder) */}
<button
className="flex h-8 w-8 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-700"
title="Notifications"
>
<Bell className="h-3.5 w-3.5" />
</button>
{/* Platform notifications (2.6f) */}
<NotificationBell />
{/* Divider */}
<div className="h-5 w-px bg-slate-200" />
@@ -0,0 +1,37 @@
// The manager's one live connection (plan step 2.6f): the backend WebSocket through
// createLiveClient (@xenia/api, CS-2/CS-18), opened while signed in. Components listen
// with useLiveEvent(type, handler). The cursor is kept in memory: a reconnect replays what
// was missed; a page reload starts fresh (pages load their data anyway).
import { useEffect, useMemo, useRef } from 'react'
import { createLiveClient, wsUrlFor } from '@xenia/api'
import useAuthStore from '../store/authStore'
import { LiveContext } from './context'
export default function LiveProvider({ children }) {
const token = useAuthStore(s => s.token)
const listeners = useRef(new Map()) // type -> Set(fn)
const value = useMemo(() => ({
subscribe(type, fn) {
if (!listeners.current.has(type)) listeners.current.set(type, new Set())
listeners.current.get(type).add(fn)
return () => listeners.current.get(type)?.delete(fn)
},
}), [])
useEffect(() => {
if (!token) return undefined
const emit = (type, data) => listeners.current.get(type)?.forEach(fn => { try { fn(data) } catch { /* one listener must not stop the others */ } })
let seq = 0
const live = createLiveClient({
url: () => wsUrlFor(`/api/ws/connect?token=${encodeURIComponent(token)}`),
cursor: { load: () => seq, save: s => { seq = s } },
onEvent: emit,
onReady: () => emit('ready', null),
})
live.start()
return () => live.stop()
}, [token])
return <LiveContext.Provider value={value}>{children}</LiveContext.Provider>
}
+4
View File
@@ -0,0 +1,4 @@
import { createContext } from 'react'
/** { subscribe(type, fn) → unsubscribe } or null outside <LiveProvider> */
export const LiveContext = createContext(null)
@@ -0,0 +1,14 @@
import { useContext, useEffect, useRef } from 'react'
import { LiveContext } from './context'
/**
* Run `handler(data)` for each live event of `type` (plan step 2.6f).
* The type 'ready' fires after every (re)connect, once missed events are replayed:
* a good moment to refetch what a page shows.
*/
export function useLiveEvent(type, handler) {
const live = useContext(LiveContext)
const ref = useRef(handler)
useEffect(() => { ref.current = handler }, [handler])
useEffect(() => (live ? live.subscribe(type, data => ref.current?.(data)) : undefined), [live, type])
}
+5
View File
@@ -5,6 +5,11 @@ import { Toaster } from 'react-hot-toast'
import App from './App.jsx'
import '@xenia/ui/styles.css' // shared tokens + component styles (.x-*), no global rules
import './index.css'
import { applyTheme } from '@xenia/ui'
// Light only until phase 6 converts the older pages to the colour tokens (decided
// 2026-11-14); then the profile menu offers light/dark/system: applyTheme(getStoredTheme()).
applyTheme('light')
const queryClient = new QueryClient({
defaultOptions: {
@@ -1,4 +1,6 @@
import { useState } from 'react'
import { useTranslation } from '@xenia/i18n'
import VenueSettings from './sections/VenueSettings'
import AppInfoTab from './tabs/AppInfoTab'
import ColoursTab from './tabs/ColoursTab'
import OperationTab from './tabs/OperationTab'
@@ -8,24 +10,19 @@ import DevelopmentTab from './tabs/DevelopmentTab'
import FiscalTab from './tabs/FiscalTab'
import { TabGroup } from '../../ui/Tabs'
const TABS = [
{ id: 'app-info', label: 'Γενικά' },
{ id: 'security', label: 'Ασφάλεια' },
{ id: 'operation', label: 'Λειτουργία' },
{ id: 'colours', label: 'Εμφάνιση' },
{ id: 'print-fonts', label: 'Εκτύπωση' },
{ id: 'fiscal', label: 'Ταμειακή' },
{ id: 'development', label: 'Developer' },
]
const TABS = ['app-info', 'venue', 'security', 'operation', 'colours', 'print-fonts', 'fiscal', 'development']
export default function SettingsPage() {
const { t } = useTranslation('manager')
const [activeTab, setActiveTab] = useState('app-info')
const tabs = TABS.map(id => ({ id, label: t(`settings.tabs.${id}`) }))
return (
<div className="flex flex-col h-full min-h-0">
<TabGroup tabs={TABS} active={activeTab} onChange={setActiveTab} />
<TabGroup tabs={tabs} active={activeTab} onChange={setActiveTab} />
<div className="flex-1 overflow-y-auto p-6">
{activeTab === 'app-info' && <AppInfoTab />}
{activeTab === 'venue' && <div className="max-w-3xl"><VenueSettings /></div>}
{activeTab === 'security' && <SecurityTab />}
{activeTab === 'operation' && <OperationTab />}
{activeTab === 'colours' && <ColoursTab />}
@@ -0,0 +1,31 @@
// print.alert_after_failures (plan step 2.6f, step 1.11): after how many failed attempts a
// kitchen/bar ticket that is still retrying raises a notification (the bell). 0 = only when
// it is finally given up (that one is always sent). Part of the ordering module.
import { useId } from 'react'
import { useModule } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { Select } from '@xenia/ui'
import { SettingRow, SettingsCard } from './SettingsCard'
import { useSettings } from './useSettings'
const CHOICES = [0, 1, 2, 3, 5, 10]
export default function PrintAlertSetting() {
const { t } = useTranslation('manager')
const ordering = useModule('ordering')
const s = useSettings()
const id = useId()
if (!ordering || s.loading) return null
const value = s.get('print.alert_after_failures', '2')
const options = CHOICES.map(n => ({ value: String(n), label: n === 0 ? t('settings.print.never') : t('settings.print.after', { count: n }) }))
if (!options.some(o => o.value === value)) options.push({ value, label: t('settings.print.after', { count: Number(value) }) })
return (
<SettingsCard title={t('settings.print.title')} testId="settings-print-alert">
<SettingRow label={t('settings.print.alert')} htmlFor={id} hint={t('settings.print.alertHint')}>
<Select id={id} value={value} disabled={s.saving} data-testid="setting-print.alert_after_failures"
onChange={e => s.save('print.alert_after_failures', e.target.value)} options={options} />
</SettingRow>
</SettingsCard>
)
}
@@ -0,0 +1,33 @@
// A card of settings rows on the tokens (plan step 2.6f). Each row: label, optional help
// line and (i) tip, and its control on the right (stacked on narrow screens).
import { InfoTip } from '@xenia/ui'
export function SettingsCard({ title, description, children, testId }) {
return (
<section className="bg-surface border border-line rounded-card shadow-raised" data-testid={testId}>
<header className="px-5 pt-4 pb-3 border-b border-line">
<h2 className="text-body font-semibold text-ink">{title}</h2>
{description && <p className="text-label text-ink-2 mt-0.5">{description}</p>}
</header>
<div className="divide-y divide-line">{children}</div>
</section>
)
}
export function SettingRow({ label, hint, tip, children, warning, htmlFor }) {
return (
<div className="px-5 py-3.5">
<div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-6">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1">
<label className="text-body font-medium text-ink" htmlFor={htmlFor}>{label}</label>
{tip && <InfoTip>{tip}</InfoTip>}
</div>
{hint && <p className="text-label text-ink-2 mt-0.5">{hint}</p>}
</div>
<div className="sm:w-64 shrink-0">{children}</div>
</div>
{warning && <p className="mt-2 rounded-control bg-warning-soft text-warning-ink text-label px-3 py-2" role="note">{warning}</p>}
</div>
)
}
@@ -0,0 +1,61 @@
// Sign-in settings (plan step 2.6f, APPS_PLATFORM D-8, D-9). Backend-only until now:
// auth.manager_login_mode, auth.waiter_login_mode, auth.waiter_require_username,
// auth.default_login_mode (paired devices; a device can choose its own on the Devices page),
// auth.single_session_manager / _waiter, and security.autofill_username (the sign-in page).
// Replaces the v1 "login method" card, whose setting (security.login_method) no longer exists.
import { useId } from 'react'
import { useTranslation } from '@xenia/i18n'
import { Select, Spinner, Switch } from '@xenia/ui'
import { SettingRow, SettingsCard } from './SettingsCard'
import { useSettings } from './useSettings'
const SESSION_RULES = ['off', 'refuse_new', 'end_old']
export default function SignInSettings() {
const { t } = useTranslation('manager')
const s = useSettings()
const idManager = useId()
const idWaiter = useId()
const idDevice = useId()
const idSingleManager = useId()
const idSingleWaiter = useId()
if (s.loading) return <div className="py-8 flex justify-center"><Spinner /></div>
const opts = (keys, prefix) => keys.map(k => ({ value: k, label: t(`${prefix}.${k}`) }))
const select = (key, fallback, options, id) => (
<Select id={id} value={s.get(key, fallback)} disabled={s.saving} onChange={e => s.save(key, e.target.value)}
options={options} data-testid={`setting-${key}`} />
)
const toggle = (key, fallback, label) => (
<Switch aria-label={label} checked={s.get(key, fallback) === 'true'} disabled={s.saving}
onChange={v => s.save(key, v ? 'true' : 'false')} data-testid={`setting-${key}`} />
)
const waiterMode = s.get('auth.waiter_login_mode', 'pin')
return (
<SettingsCard title={t('settings.signIn.title')} description={t('settings.signIn.intro')} testId="settings-sign-in">
<SettingRow label={t('settings.signIn.manager')} htmlFor={idManager} tip={t('settings.signIn.managerTip')}>
{select('auth.manager_login_mode', 'password', opts(['password', 'pin'], 'settings.mode'), idManager)}
</SettingRow>
<SettingRow label={t('settings.signIn.autofill')} hint={t('settings.signIn.autofillHint')}>
{toggle('security.autofill_username', 'true', t('settings.signIn.autofill'))}
</SettingRow>
<SettingRow label={t('settings.signIn.waiter')} htmlFor={idWaiter}
warning={waiterMode === 'tap' ? t('settings.signIn.waiterTapWarning') : undefined}>
{select('auth.waiter_login_mode', 'pin', opts(['pin', 'password', 'tap'], 'settings.mode'), idWaiter)}
</SettingRow>
<SettingRow label={t('settings.signIn.requireUsername')} hint={t('settings.signIn.requireUsernameHint')}>
{toggle('auth.waiter_require_username', 'false', t('settings.signIn.requireUsername'))}
</SettingRow>
<SettingRow label={t('settings.signIn.device')} htmlFor={idDevice} hint={t('settings.signIn.deviceHint')}>
{select('auth.default_login_mode', 'pin', opts(['pin', 'password', 'tap', 'none'], 'settings.mode'), idDevice)}
</SettingRow>
<SettingRow label={t('settings.signIn.singleManager')} htmlFor={idSingleManager} tip={t('settings.signIn.singleTip')}>
{select('auth.single_session_manager', 'off', opts(SESSION_RULES, 'settings.session'), idSingleManager)}
</SettingRow>
<SettingRow label={t('settings.signIn.singleWaiter')} htmlFor={idSingleWaiter}>
{select('auth.single_session_waiter', 'off', opts(SESSION_RULES, 'settings.session'), idSingleWaiter)}
</SettingRow>
</SettingsCard>
)
}
@@ -0,0 +1,38 @@
// Venue language and time zone (plan step 2.6f, D-11, D-12): venue.language is the
// language of staff without their own choice and of printed tickets/reports; venue.timezone
// is the zone every time is shown in (applies at once). Both reload bootstrap after saving.
import { useId, useMemo } from 'react'
import { useAccess } from '@xenia/access'
import { LANGUAGE_NAMES, useTranslation, useFormat } from '@xenia/i18n'
import { Select, Spinner } from '@xenia/ui'
import { SettingRow, SettingsCard } from './SettingsCard'
import { useSettings } from './useSettings'
import { timeZones } from './timeZones'
export default function VenueSettings() {
const { t } = useTranslation('manager')
const f = useFormat()
const { languages } = useAccess()
const s = useSettings()
const langId = useId()
const tzId = useId()
const tz = s.get('venue.timezone', 'Europe/Athens')
const zones = useMemo(() => timeZones(tz), [tz])
if (s.loading) return <div className="py-8 flex justify-center"><Spinner /></div>
return (
<SettingsCard title={t('settings.venue.title')} testId="settings-venue">
<SettingRow label={t('settings.venue.language')} htmlFor={langId} hint={t('settings.venue.languageHint')}>
<Select id={langId} value={s.get('venue.language', 'en')} disabled={s.saving} data-testid="setting-venue.language"
onChange={e => s.save('venue.language', e.target.value)}
options={(languages || ['en', 'el']).map(l => ({ value: l, label: LANGUAGE_NAMES[l] || l }))} />
</SettingRow>
<SettingRow label={t('settings.venue.timezone')} htmlFor={tzId}
hint={t('settings.venue.timezoneHint', { time: f.formatTime(new Date()) })}>
<Select id={tzId} value={tz} disabled={s.saving} data-testid="setting-venue.timezone"
onChange={e => s.save('venue.timezone', e.target.value)}
options={zones.map(z => ({ value: z, label: z.replace(/_/g, ' ') }))} />
</SettingRow>
</SettingsCard>
)
}
@@ -0,0 +1,12 @@
/** Every IANA zone the browser knows; the current one is kept even when the browser lacks it. */
export function timeZones(current) {
let zones = []
try { zones = Intl.supportedValuesOf('timeZone') } catch { zones = [] }
if (current && !zones.includes(current)) zones = [current, ...zones]
return zones
}
/** The browser's own zone (for the setup wizard's default), or Europe/Athens. */
export function browserTimeZone() {
try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'Europe/Athens' } catch { return 'Europe/Athens' }
}
@@ -0,0 +1,41 @@
// Venue settings for the v2 settings sections (plan step 2.6f): GET /api/settings/ (all
// declared keys with their values) and PUT /api/settings/{key} {value} (core.settings.manage;
// the backend checks types, enums, time zones and languages). Shares the react-query key
// with the older settings tabs, so both stay in sync.
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useAccess } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import client from '../../../api/client'
/** Keys that change what bootstrap says (language, time zone, sign-in mode): reload it. */
const BOOTSTRAP_KEYS = new Set(['venue.language', 'venue.timezone', 'auth.manager_login_mode', 'security.autofill_username'])
export function useSettings() {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const access = useAccess()
const query = useQuery({
queryKey: ['pos-settings'],
queryFn: () => client.get('/api/settings/').then(r => r.data),
staleTime: 30_000,
})
const mutation = useMutation({
mutationFn: ({ key, value }) => client.put(`/api/settings/${key}`, { value }),
onSuccess: (_r, { key }) => {
toast.success(t('settings.saved'))
qc.invalidateQueries({ queryKey: ['pos-settings'] })
if (BOOTSTRAP_KEYS.has(key)) access.refresh()
},
onError: err => toast.error(errorMessage(err, t)),
})
return {
loading: query.isLoading,
error: query.error ? errorMessage(query.error, t) : null,
/** The stored value (strings, as the backend keeps them), or `fallback`. */
get: (key, fallback = '') => query.data?.[key]?.value ?? fallback,
save: (key, value) => mutation.mutate({ key, value: String(value) }),
saving: mutation.isPending,
}
}
@@ -1,4 +1,5 @@
import React, { useState, useEffect, useRef, useCallback } from 'react'
import PrintAlertSetting from '../sections/PrintAlertSetting'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../../../api/client'
@@ -1115,6 +1116,7 @@ export default function PrintFontsTab() {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
<PrintAlertSetting />
{/* 1. Printers */}
<PrintersSection />
@@ -1,8 +1,9 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Shield, Lock, LogOut, User, KeyRound, ShieldCheck, Copy, RefreshCw, X } from 'lucide-react'
import { Shield, Lock, LogOut, User, ShieldCheck, Copy, RefreshCw, X } from 'lucide-react'
import client from '../../../api/client'
import SignInSettings from '../sections/SignInSettings'
import { PANEL_CLASS } from '../../../ui/tokens'
import Button from '../../../ui/Button'
@@ -76,28 +77,6 @@ function Toggle({ checked, onChange, disabled }) {
)
}
function SegmentedControl({ options, value, onChange, disabled }) {
return (
<div className="flex rounded-lg border border-gray-200 overflow-hidden bg-gray-50 p-0.5 gap-0.5">
{options.map(opt => (
<button
key={opt.value}
type="button"
onClick={() => !disabled && onChange(opt.value)}
disabled={disabled}
className={`px-3 py-1.5 text-xs font-medium rounded-md transition-all ${
value === opt.value
? 'bg-white text-gray-800 shadow-sm'
: 'text-gray-500 hover:text-gray-700'
}`}
>
{opt.label}
</button>
))}
</div>
)
}
function TimeSelect({ value, onChange, disabled }) {
return (
<div className="flex items-center gap-2">
@@ -290,8 +269,6 @@ export default function SecurityTab() {
)
}
const loginMethod = get('security.login_method', 'password')
const autofill = get('security.autofill_username', 'true') === 'true'
const autoLock = get('security.auto_lock', 'false') === 'true'
const autoLockSecs = get('security.auto_lock_seconds', '300')
const autoLogout = get('security.auto_logout', 'false') === 'true'
@@ -300,46 +277,8 @@ export default function SecurityTab() {
return (
<div className="space-y-5">
{/* ── Μέθοδος σύνδεσης ─────────────────────────────────────────────── */}
<SectionCard
icon={KeyRound}
title="Σύνδεση"
description="Τι διαπιστευτήρια απαιτούνται όταν η εφαρμογή ξεκινά ή μετά από πλήρη αποσύνδεση."
>
<OptionRow
label="Μέθοδος σύνδεσης"
description="Πώς πιστοποιούνται οι διαχειριστές κατά την πρώτη πρόσβαση."
>
<SegmentedControl
value={loginMethod}
onChange={v => save('security.login_method', v)}
disabled={busy}
options={[
{ value: 'password', label: 'Κωδικός' },
{ value: 'pin', label: 'PIN' },
{ value: 'none', label: 'Κανένα' },
]}
/>
</OptionRow>
{loginMethod === 'none' && (
<div className="mx-5 mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-[12px] text-amber-700">
<strong>Προσοχή:</strong> με έναν μόνο λογαριασμό διαχειριστή, η εφαρμογή θα ανοίγει χωρίς πιστοποίηση.
Χρησιμοποιήστε αυτό μόνο σε φυσικά ασφαλή, ιδιωτική συσκευή.
</div>
)}
<OptionRow
label="Αυτόματη συμπλήρωση ονόματος χρήστη"
description="Όταν υπάρχει μόνο ένας διαχειριστής, παράλειψη του πεδίου ονόματος."
>
<Toggle
checked={autofill}
onChange={v => save('security.autofill_username', v ? 'true' : 'false')}
disabled={busy}
/>
</OptionRow>
</SectionCard>
{/* Sign-in (2.6f): the v2 settings auth.* replace the v1 security.login_method card */}
<SignInSettings />
{/* ── Αυτόματο κλείδωμα ────────────────────────────────────────────── */}
<SectionCard
+31 -1
View File
@@ -1,4 +1,6 @@
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,
@@ -266,6 +268,7 @@ function StepAccount({ data, onChange, onNext, onBack }) {
}
function StepVenue({ data, onChange, onNext, onBack }) {
const { t } = useTranslation('manager')
const [errors, setErrors] = useState({})
function toggleType(id) {
@@ -307,6 +310,26 @@ function StepVenue({ data, onChange, onNext, onBack }) {
{errors.venueType && <p className="mt-1 text-[12px] text-rose-500">{errors.venueType}</p>}
</div>
<div className="grid grid-cols-2 gap-3">
<label className="block">
<span className="block text-[12px] font-medium text-slate-500 uppercase tracking-wider mb-2">{t('setup.language')}</span>
<select value={data.language} onChange={e => onChange('language', e.target.value)} data-testid="setup-language"
className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-[14px]">
{Object.entries(LANGUAGE_NAMES).map(([code, name]) => <option key={code} value={code}>{name}</option>)}
</select>
</label>
<label className="block">
<span className="block text-[12px] font-medium text-slate-500 uppercase tracking-wider mb-2">{t('setup.timezone')}</span>
<select value={data.timezone} onChange={e => onChange('timezone', e.target.value)} data-testid="setup-timezone"
className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2.5 text-[14px]">
{timeZones(data.timezone).map(z => <option key={z} value={z}>{z.replace(/_/g, ' ')}</option>)}
</select>
</label>
<p className="col-span-2 -mt-1 text-[12px] text-slate-500">
{t('setup.languageHint')}
</p>
</div>
<div>
<p className="text-[12px] font-medium text-slate-500 uppercase tracking-wider mb-2">Venue name</p>
<LabelledInput
@@ -424,7 +447,12 @@ export default function SetupWizard() {
const [account, setAccount] = useState({
username: '', fullName: '', email: '', password: '', confirm: '',
})
const [venue, setVenue] = useState({ venueTypes: [], venueName: '' })
// 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) {
@@ -445,6 +473,8 @@ export default function SetupWizard() {
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 })
@@ -2,6 +2,9 @@ import { useState } from 'react'
import { TabBar } from '../../ui/Tabs'
import PrinterHistory from './operations/PrinterHistory'
import PrinterHealthLog from './operations/PrinterHealthLog'
import LogsPanel from './operations/LogsPanel'
import { useCan } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
const TABS = [
{ id: 'printer-history', label: 'Ιστορικό Εκτυπωτή', Component: PrinterHistory },
@@ -9,13 +12,16 @@ const TABS = [
]
export default function TechnicalPage() {
const { t } = useTranslation('manager')
const canLogs = useCan('core.settings.manage') // the files carry names and IPs: owner-level
const tabs = canLogs ? [...TABS, { id: 'logs', label: t('logs.tab'), Component: LogsPanel }] : TABS
const [active, setActive] = useState('printer-history')
const tab = TABS.find(t => t.id === active) || TABS[0]
const tab = tabs.find(x => x.id === active) || tabs[0]
const { Component } = tab
return (
<div className="flex flex-col h-full min-h-0">
<TabBar tabs={TABS} active={active} onChange={setActive} />
<TabBar tabs={tabs} active={active} onChange={setActive} />
<div className="flex-1 min-h-0 flex flex-col">
<Component key={active} />
</div>
@@ -0,0 +1,76 @@
// Log download (plan step 2.6f, APPS_PLATFORM §10): the backend's daily log files
// (UTC days, kept 30 days) to send to support. GET /api/system/logs → [{date, name, size}],
// GET /api/system/logs/{date} → the file (core.settings.manage). Fetched through the API
// client (it carries the session), then saved with a temporary link.
import { useCallback, useEffect, useState } from 'react'
import { Download, FileText } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation, useFormat } from '@xenia/i18n'
import { Button, EmptyState, Spinner } from '@xenia/ui'
import client from '../../../api/client'
export default function LogsPanel() {
const { t } = useTranslation('manager')
const f = useFormat()
const [rows, setRows] = useState(null)
const [error, setError] = useState(null)
const [busy, setBusy] = useState(null)
const load = useCallback(async () => {
try {
setRows((await client.get('/api/system/logs')).data)
setError(null)
} catch (err) {
setError(errorMessage(err, t))
}
}, [t])
useEffect(() => { load() }, [load])
async function download(row) {
setBusy(row.date)
try {
const r = await client.get(`/api/system/logs/${row.date}`, { responseType: 'blob' })
const url = URL.createObjectURL(r.data)
const a = document.createElement('a')
a.href = url
a.download = row.name
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), 10_000)
} catch (err) {
setError(errorMessage(err, t))
} finally {
setBusy(null)
}
}
if (error && !rows) return <div className="p-8"><EmptyState title={error} action={<Button variant="secondary" onClick={load}>{t('common:actions.retry')}</Button>} /></div>
if (!rows) return <div className="p-8 flex justify-center"><Spinner /></div>
return (
<div className="p-6 max-w-3xl grid gap-4 overflow-y-auto">
<p className="text-body text-ink-2">{t('logs.intro')}</p>
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
{rows.length === 0
? <EmptyState icon={<FileText />} title={t('logs.empty')} />
: (
<div className="bg-surface border border-line rounded-card shadow-raised divide-y divide-line" data-testid="logs-list">
{rows.map(row => (
<div key={row.date} className="flex items-center gap-4 px-4 py-3" data-testid={`log-${row.date}`}>
<div className="flex-1 min-w-0">
<div className="text-body font-medium text-ink">
{f.formatDate(row.date, 'dateLong')}{row.date === new Date().toISOString().slice(0, 10) && <span className="ml-2 text-caption text-ink-3">{t('logs.current')}</span>}
</div>
<div className="text-caption text-ink-3">{row.name} · {t('logs.size', { size: f.formatNumber(Math.max(1, Math.round(row.size / 1024))) })}</div>
</div>
<Button size="sm" variant="secondary" icon={<Download size={14} />} loading={busy === row.date} onClick={() => download(row)}>
{t('logs.download')}
</Button>
</div>
))}
</div>
)}
</div>
)
}
+3
View File
@@ -68,5 +68,8 @@
"catalog": {
"unknown_category": "Δεν υπάρχει η κατηγορία {{category_id}}.",
"primary_not_listed": "Η κύρια κατηγορία ({{category_id}}) πρέπει να είναι μία από τις κατηγορίες του προϊόντος."
},
"system": {
"log_not_found": "Δεν υπάρχει αρχείο καταγραφής για {{date}}."
}
}
+79
View File
@@ -283,5 +283,84 @@
"waiting": "Σε αναμονή"
},
"order": "Παραγγελία #{{id}}"
},
"notifications": {
"bell": "Ειδοποιήσεις",
"bellUnread_one": "Ειδοποιήσεις: {{count}} αδιάβαστη",
"bellUnread_other": "Ειδοποιήσεις: {{count}} αδιάβαστες",
"title": "Ειδοποιήσεις",
"empty": "Τίποτα καινούργιο. Εδώ εμφανίζονται ειδοποιήσεις για την άδεια, την εκτύπωση και την υποστήριξη.",
"markAll": "Όλες διαβασμένες",
"times_one": "{{count}} φορά",
"times_other": "{{count}} φορές"
},
"settings": {
"saved": "Αποθηκεύτηκε",
"tabs": {
"app-info": "Γενικά",
"venue": "Κατάστημα & γλώσσα",
"security": "Σύνδεση & ασφάλεια",
"operation": "Λειτουργία",
"colours": "Εμφάνιση",
"print-fonts": "Εκτύπωση",
"fiscal": "Ταμειακή",
"development": "Developer"
},
"mode": {
"password": "Κωδικός",
"pin": "PIN",
"tap": "Επιλογή ονόματος",
"none": "Χωρίς σύνδεση"
},
"session": {
"off": "Επιτρέπεται σε πολλές συσκευές",
"refuse_new": "Άρνηση δεύτερης σύνδεσης",
"end_old": "Αποσύνδεση της παλιότερης"
},
"signIn": {
"title": "Σύνδεση",
"intro": "Πώς κάθε εφαρμογή ρωτά ποιος είναι ο χρήστης. Οι αλλαγές ισχύουν από την επόμενη σύνδεση.",
"manager": "Οι υπεύθυνοι συνδέονται στη διαχείριση με",
"managerTip": "Με PIN, οι υπεύθυνοι βάζουν το ίδιο PIN που χρησιμοποιούν για ξεκλείδωμα και εγκρίσεις. Κάθε υπεύθυνος χρειάζεται PIN.",
"autofill": "Συμπλήρωση ονόματος χρήστη όταν υπάρχει ένας μόνο υπεύθυνος",
"autofillHint": "Η σελίδα σύνδεσης ζητά τότε μόνο τον κωδικό ή το PIN.",
"waiter": "Οι σερβιτόροι συνδέονται στην εφαρμογή τους με",
"waiterTapWarning": "Η «Επιλογή ονόματος» λειτουργεί μόνο σε συζευγμένες συσκευές. Από τα δικά τους κινητά οι σερβιτόροι δεν μπορούν να συνδεθούν έτσι.",
"requireUsername": "Οι σερβιτόροι γράφουν το όνομα χρήστη τους",
"requireUsernameHint": "Αντί να επιλέγουν το όνομά τους από τη λίστα.",
"device": "Στις συζευγμένες συσκευές (οθόνη κουζίνας, ταμείο πάγκου) το προσωπικό συνδέεται με",
"deviceHint": "Κάθε συσκευή μπορεί να έχει δική της επιλογή στη σελίδα Συσκευές.",
"singleManager": "Μία σύνδεση ανά υπεύθυνο",
"singleWaiter": "Μία σύνδεση ανά σερβιτόρο",
"singleTip": "Όταν κάποιος είναι ήδη συνδεδεμένος σε άλλη συσκευή: επιτρέπονται και οι δύο, απορρίπτεται η νέα σύνδεση ή αποσυνδέεται η παλιότερη."
},
"venue": {
"title": "Κατάστημα",
"language": "Γλώσσα",
"languageHint": "Για όσους δεν έχουν διαλέξει δική τους, και για τα εκτυπωμένα δελτία και τις αναφορές.",
"timezone": "Ζώνη ώρας",
"timezoneHint": "Όλες οι ώρες εμφανίζονται σε αυτή. Η ώρα εκεί τώρα: {{time}}."
},
"print": {
"title": "Ειδοποιήσεις εκτύπωσης",
"alert": "Ειδοποίηση των υπευθύνων όταν ένα δελτίο δεν τυπώνεται",
"alertHint": "Όσο συνεχίζει να ξαναδοκιμάζει. Ένα δελτίο που εγκαταλείπεται οριστικά αναφέρεται πάντα.",
"never": "Μόνο όταν εγκαταλειφθεί",
"after_one": "Μετά από {{count}} αποτυχία",
"after_other": "Μετά από {{count}} αποτυχίες"
}
},
"logs": {
"tab": "Αρχεία καταγραφής",
"intro": "Τα ημερήσια αρχεία καταγραφής του συστήματος, που κρατιούνται 30 ημέρες. Η υποστήριξη μπορεί να ζητήσει το αρχείο της ημέρας που κάτι πήγε στραβά. Οι ημέρες είναι σε ώρα UTC.",
"empty": "Δεν υπάρχουν αρχεία ακόμα",
"current": "(γράφεται ακόμα)",
"size": "{{size}} KB",
"download": "Λήψη"
},
"setup": {
"language": "Γλώσσα προσωπικού",
"timezone": "Ζώνη ώρας",
"languageHint": "Η γλώσσα των οθονών του προσωπικού (ο καθένας μπορεί να διαλέξει τη δική του) και των εκτυπωμένων δελτίων και αναφορών."
}
}
+3
View File
@@ -68,5 +68,8 @@
"catalog": {
"unknown_category": "There is no category {{category_id}}.",
"primary_not_listed": "The main category ({{category_id}}) must be one of the product's categories."
},
"system": {
"log_not_found": "There is no log file for {{date}}."
}
}
+79
View File
@@ -283,5 +283,84 @@
"waiting": "Waiting"
},
"order": "Order #{{id}}"
},
"notifications": {
"bell": "Notifications",
"bellUnread_one": "Notifications: {{count}} unread",
"bellUnread_other": "Notifications: {{count}} unread",
"title": "Notifications",
"empty": "Nothing new. Licence, printing and support alerts show up here.",
"markAll": "Mark all as read",
"times_one": "{{count}} time",
"times_other": "{{count}} times"
},
"settings": {
"saved": "Saved",
"tabs": {
"app-info": "General",
"venue": "Venue & language",
"security": "Sign-in & security",
"operation": "Operation",
"colours": "Appearance",
"print-fonts": "Printing",
"fiscal": "Fiscal device",
"development": "Developer"
},
"mode": {
"password": "Password",
"pin": "PIN",
"tap": "Tap your name",
"none": "No sign-in"
},
"session": {
"off": "Allowed on several devices",
"refuse_new": "Refuse a second sign-in",
"end_old": "Sign out the older one"
},
"signIn": {
"title": "Sign-in",
"intro": "How each app asks people who they are. Changes apply to the next sign-in.",
"manager": "Managers sign in to this dashboard with",
"managerTip": "With PIN, managers type the same PIN they use to unlock the screen and to approve actions. Every manager needs a PIN.",
"autofill": "Fill in the username when there is only one manager",
"autofillHint": "The sign-in page then only asks for the password or PIN.",
"waiter": "Waiters sign in to the waiter app with",
"waiterTapWarning": "\"Tap your name\" works only on paired devices. On their own phones, waiters can't sign in this way.",
"requireUsername": "Waiters type their username",
"requireUsernameHint": "Instead of picking their name from the list.",
"device": "On paired devices (kitchen display, counter POS), staff sign in with",
"deviceHint": "Each device can choose its own on the Devices page.",
"singleManager": "One session per manager",
"singleWaiter": "One session per waiter",
"singleTip": "When someone is already signed in on another device: allow both, refuse the new sign-in, or sign out the older one."
},
"venue": {
"title": "Venue",
"language": "Language",
"languageHint": "For staff who haven't chosen their own, and for printed tickets and reports.",
"timezone": "Time zone",
"timezoneHint": "Every time is shown in it. The time there now: {{time}}."
},
"print": {
"title": "Print alerts",
"alert": "Tell managers when a ticket fails to print",
"alertHint": "While it keeps retrying. A ticket that is finally given up is always reported.",
"never": "Only when it is given up",
"after_one": "After {{count}} failed attempt",
"after_other": "After {{count}} failed attempts"
}
},
"logs": {
"tab": "Log files",
"intro": "The system's daily log files, kept for 30 days. Support may ask for the file of the day something went wrong. Days are in UTC.",
"empty": "No log files yet",
"current": "(still being written)",
"size": "{{size}} KB",
"download": "Download"
},
"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."
}
}
+1
View File
@@ -22,3 +22,4 @@ export { Field, Input, Textarea, Select } from './components/Field.jsx'
export { Switch } from './components/Switch.jsx'
export { UiLabelsProvider, DEFAULT_LABELS } from './components/labels.js'
export { cx } from './internal/cx.js'
export { THEMES, THEME_STORAGE_KEY, applyTheme, getStoredTheme } from './theme.js'
+34
View File
@@ -0,0 +1,34 @@
// The colour theme of an app (plan step 2.6f): light | dark | system (follows the OS).
// tokens.css reads it from data-theme on <html>. The choice is per device (localStorage),
// like a screen setting, not per user. No React here.
//
// applyTheme(getStoredTheme()) at startup
// applyTheme('dark', { save: true }) when the user picks one
//
// The manager offers the choice only once its older pages use the tokens (phase 6): until
// then it always applies 'light' (decided 2026-11-14), so a saved choice waits unused.
export const THEMES = ['light', 'dark', 'system']
export const THEME_STORAGE_KEY = 'xenia_theme'
const browserStorage = () => { try { return globalThis.localStorage ?? null } catch { return null } }
/** The saved theme, or 'light'. */
export function getStoredTheme(storage = browserStorage()) {
try {
const v = storage?.getItem(THEME_STORAGE_KEY)
return THEMES.includes(v) ? v : 'light'
} catch {
return 'light'
}
}
/** Set data-theme on the root element (and save it when asked). Unknown values become 'light'. */
export function applyTheme(theme, { root = globalThis.document?.documentElement, storage = browserStorage(), save = false } = {}) {
const t = THEMES.includes(theme) ? theme : 'light'
root?.setAttribute('data-theme', t)
if (save) {
try { storage?.setItem(THEME_STORAGE_KEY, t) } catch { /* private mode: not remembered */ }
}
return t
}
+27
View File
@@ -0,0 +1,27 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { applyTheme, getStoredTheme, THEME_STORAGE_KEY } from '../src/theme.js'
const memory = () => { const m = new Map(); return { getItem: k => m.get(k) ?? null, setItem: (k, v) => m.set(k, v) } }
const element = () => { const a = {}; return { setAttribute: (k, v) => { a[k] = v }, attrs: a } }
test('stored theme: light unless a known one is saved', () => {
const s = memory()
assert.equal(getStoredTheme(s), 'light')
s.setItem(THEME_STORAGE_KEY, 'neon')
assert.equal(getStoredTheme(s), 'light')
s.setItem(THEME_STORAGE_KEY, 'system')
assert.equal(getStoredTheme(s), 'system')
assert.equal(getStoredTheme({ getItem: () => { throw new Error('blocked') } }), 'light')
})
test('applyTheme sets data-theme and saves only when asked', () => {
const s = memory()
const root = element()
assert.equal(applyTheme('dark', { root, storage: s }), 'dark')
assert.equal(root.attrs['data-theme'], 'dark')
assert.equal(getStoredTheme(s), 'light')
applyTheme('dark', { root, storage: s, save: true })
assert.equal(getStoredTheme(s), 'dark')
assert.equal(applyTheme('bogus', { root, storage: s }), 'light')
})
+1 -1
View File
@@ -41,7 +41,7 @@ Or run one suite at a time:
| `node install.mjs` | `install.sh`: VPN-safe `HOST_IP` detection (simulated WireGuard/WiFi hosts); fresh install, upgrade, re-run; proxy config identical to `nginx-proxy/nginx.conf` | Docker | ~1 min |
| `python license_e2e.py` | Offline licensing with a real cloud + site process: 400 days offline, tampered file, clock set back, expiry deferred to workday close, renewal, remote lock | Python deps of both backends | ~2 min |
| `node ui.mjs` | `@xenia/ui` components on the dev-only gallery (`/ui-gallery`, manager Vite :5185): dialog focus/Escape/backdrop, sheet, toasts, field wiring, switch, InfoTip, PinPad, themes; `@xenia/i18n` on `/i18n-sample` with the browser in New York: venue time, live language switch, el/en money and numbers, price input, translated component labels | Edge | ~40 s |
| `node manager.mjs` | Manager on `@xenia/api`/`@xenia/access` (backend :8057 on a demo DB, manager Vite :5186): bootstrap before/after login, wrong password and wrong lock PIN stay on screen, sidebar from keys, KDS module off → "turned off" screen, session ended elsewhere → /login, a waiter's cancel approved by a manager PIN (wrong PIN first) and audited; Apps, Integrations, License, Devices (pairing played through the API); the approvals log, "Signed in now" + end session, the staff permission editor (give, reset to role, a staff manager can't give what they lack) | Edge | ~1 min |
| `node manager.mjs` | Manager on `@xenia/api`/`@xenia/access` (backend :8057 on a demo DB, manager Vite :5186): bootstrap before/after login, wrong password and wrong lock PIN stay on screen, sidebar from keys, KDS module off → "turned off" screen, session ended elsewhere → /login, a waiter's cancel approved by a manager PIN (wrong PIN first) and audited; Apps, Integrations, License, Devices (pairing played through the API); the approvals log, "Signed in now" + end session, the staff permission editor (give, reset to role, a staff manager can't give what they lack); the notification bell (live, read, read all), sign-in/venue/print settings, log download | Edge | ~1 min |
| `node browser.mjs` | Waiter web modes (same-origin, plain HTTP by LAN IP, venue mode), install dialog + drawer entry (Android / iPhone / desktop / no APK) | Docker, Edge | ~2 min |
| `node android.mjs basics` | Pairing, wrong address / other venue's QR, login + live WS, back button, restart, two venues, camera permission | Android emulator | ~5 min |
| `node android.mjs rediscovery` | Server IP change (logged in / out), server down + manual search, cold start while offline | Android emulator | ~4 min |
+88 -2
View File
@@ -6,12 +6,12 @@
// ended session logs out), a module turned off, and the manager-approval dialog.
// node manager.mjs
import { spawn } from 'node:child_process'
import { openSync } from 'node:fs'
import { openSync, readFileSync } from 'node:fs'
import path from 'node:path'
import { chromium } from 'playwright'
import { BROWSER_CHANNEL, CS, OUT, reporter, sleep } from './lib/env.mjs'
import { killTree, startBackend, waitHttp } from './lib/proc.mjs'
import { SUPPORT_MASTER, codeFor, siteSecret } from './lib/support.mjs'
import { SUPPORT_MASTER, codeFor, siteSecret, supportLogin } from './lib/support.mjs'
const PORT = 5186
const APP = `http://localhost:${PORT}`
@@ -430,6 +430,92 @@ try {
(await s2.getByTestId('perm-error').textContent().catch(() => '')).includes('You can only give permissions you have yourself: "See reports"'))
r.check('…and nothing was saved', !(await mariaPerms()).keys.includes('reports.view'))
// ── 2.6f: notification bell (live), settings pages, log download ───────────
await page.goto(`${APP}/dashboard`)
const bell = page.getByTestId('notif-bell')
await bell.waitFor({ timeout: 10_000 })
await page.getByTestId('notif-count').waitFor({ timeout: 8000 }).catch(() => {})
r.check('bell: unread count from the earlier support sign-ins', Number((await page.getByTestId('notif-count').textContent().catch(() => '0')).replace('+', '')) >= 1)
await bell.click()
const panel = page.getByTestId('notif-panel')
r.check('bell: the list says support signed in, in plain words', (await panel.textContent()).includes('Xenia support logged in'))
await page.getByTestId('notif-read-all').click()
await page.getByTestId('notif-count').waitFor({ state: 'detached', timeout: 5000 }).catch(() => {})
r.check('bell: "mark all as read" clears the count', await page.getByTestId('notif-count').count() === 0)
await bell.click() // close
await sleep(1500) // the live socket is up (opened with the shell)
await supportLogin(backend.url)
await page.getByTestId('notif-count').waitFor({ timeout: 8000 }).catch(() => {})
r.check('bell: a new one arrives live (no reload): count 1 and a toast',
await page.getByTestId('notif-count').textContent().catch(() => '') === '1' && await page.getByText('Xenia support logged in').count() >= 1)
await bell.click()
const unreadItem = panel.locator('[data-read="false"]').first()
await unreadItem.click()
await page.waitForFunction(() => !document.querySelector('[data-testid="notif-count"]'), null, { timeout: 5000 }).catch(() => {})
r.check('bell: opening it marks it read', await page.getByTestId('notif-count').count() === 0 &&
(await api('GET', '/api/platform/notifications', { token: boss })).unread === 0)
await page.screenshot({ path: path.join(OUT, 'manager-notifications.png') })
await page.keyboard.press('Escape')
const settingValue = async key => (await api('GET', '/api/settings/', { token: boss }))[key].value
await page.goto(`${APP}/settings`)
await page.getByText('Sign-in & security', { exact: true }).click()
const waiterMode = page.getByTestId('setting-auth.waiter_login_mode')
await waiterMode.waitFor({ timeout: 10_000 })
await waiterMode.selectOption('tap')
await page.getByRole('note').waitFor({ timeout: 5000 }).catch(() => {})
r.check('settings: waiter sign-in → "Tap your name" is saved and warns it needs paired devices',
await settingValue('auth.waiter_login_mode') === 'tap' && (await page.getByRole('note').textContent()).includes('only on paired devices'))
await waiterMode.selectOption('pin')
await page.getByTestId('setting-auth.manager_login_mode').selectOption('pin')
await sleep(800)
r.check('settings: manager sign-in → PIN reaches the sign-in page (bootstrap)',
(await api('GET', '/api/platform/bootstrap')).login.manager_mode === 'pin')
await page.screenshot({ path: path.join(OUT, 'manager-settings-sign-in.png'), fullPage: true })
await page.getByTestId('setting-auth.manager_login_mode').selectOption('password')
await page.getByTestId('setting-auth.single_session_waiter').selectOption('end_old')
await sleep(800)
r.check('settings: one session per waiter → "sign out the older one"', await settingValue('auth.single_session_waiter') === 'end_old' &&
await settingValue('auth.manager_login_mode') === 'password' && await settingValue('auth.waiter_login_mode') === 'pin')
await page.getByTestId('setting-auth.single_session_waiter').selectOption('off')
await page.getByText('Venue & language', { exact: true }).click()
const tzSelect = page.getByTestId('setting-venue.timezone')
await tzSelect.waitFor({ timeout: 10_000 })
await tzSelect.selectOption('Europe/London')
await sleep(800)
await page.getByTestId('setting-venue.language').selectOption('el')
await sleep(800)
const venue = (await api('GET', '/api/platform/bootstrap')).venue
r.check('settings: time zone and venue language saved (bootstrap says Europe/London, el)', venue.timezone === 'Europe/London' && venue.language === 'el', JSON.stringify(venue))
await page.screenshot({ path: path.join(OUT, 'manager-settings-venue.png'), fullPage: true })
await page.getByTestId('setting-venue.language').selectOption('en')
await sleep(800)
await tzSelect.selectOption('Europe/Athens')
await sleep(800)
await page.getByText('Printing', { exact: true }).click()
const alertSel = page.getByTestId('setting-print.alert_after_failures')
await alertSel.waitFor({ timeout: 10_000 })
await alertSel.selectOption('5')
await sleep(800)
r.check('settings: print alert after 5 failed attempts', await settingValue('print.alert_after_failures') === '5')
await alertSel.selectOption('2')
await sleep(500)
await page.goto(`${APP}/reports/technical`)
await page.getByText('Log files', { exact: true }).click()
const today = new Date().toISOString().slice(0, 10)
const logRow = page.getByTestId(`log-${today}`)
await logRow.waitFor({ timeout: 10_000 }).catch(() => {})
r.check("logs: today's file is listed (still being written)", (await logRow.textContent().catch(() => '')).includes('still being written'))
const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 10_000 }), logRow.getByRole('button', { name: 'Download' }).click()])
const dlText = readFileSync(await dl.path(), 'utf-8')
r.check('logs: Download saves xenia-<day>.log with the backend\'s lines', dl.suggestedFilename() === `xenia-${today}.log` && dlText.includes('session.started'), dl.suggestedFilename())
await s2.goto(`${APP}/reports/technical`)
await s2.getByText('Printer history').or(s2.getByText('Ιστορικό Εκτυπωτή')).first().waitFor({ timeout: 10_000 }).catch(() => {})
r.check('logs: a staff manager has no "Log files" tab (owner-level)', await s2.getByText('Log files', { exact: true }).count() === 0)
r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | '))
} finally {
await browser.close()
+2 -1
View File
@@ -123,7 +123,8 @@ try {
await p.screenshot({ path: path.join(OUT, 'ui-gallery-dark-amber.png'), fullPage: true })
await p.evaluate(() => { history.pushState({}, '', '/login'); dispatchEvent(new PopStateEvent('popstate')) })
await sleep(500)
r.check('theme: leaving the gallery restores <html>', await p.evaluate(() => !document.documentElement.hasAttribute('data-theme') && !document.documentElement.hasAttribute('data-venue-theme')))
// the manager sets data-theme="light" at startup (2.6f); the gallery puts that back
r.check('theme: leaving the gallery restores <html>', await p.evaluate(() => document.documentElement.getAttribute('data-theme') === 'light' && !document.documentElement.hasAttribute('data-venue-theme')))
r.check('no page or console errors', errs.length === 0, errs.slice(0, 3).join(' | '))
failures += r.done()