diff --git a/docs/README.md b/docs/README.md index 16f68c3..afa2e57 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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/.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:.name`, `.limits.`, `.permissions.`); `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 `` 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 ``: 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)` / `` / `` (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 ``: 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)` / `` / `` (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 `, 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`). diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 2e08635..5a194f1 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -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."), } diff --git a/local_backend/core/logging.py b/local_backend/core/logging.py index 73e5c91..f6c1cd0 100644 --- a/local_backend/core/logging.py +++ b/local_backend/core/logging.py @@ -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 diff --git a/local_backend/routers/setup.py b/local_backend/routers/setup.py index 412a128..dd97cd9 100644 --- a/local_backend/routers/setup.py +++ b/local_backend/routers/setup.py @@ -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) diff --git a/local_backend/routers/system.py b/local_backend/routers/system.py index 6cdccdb..304e4be 100644 --- a/local_backend/routers/system.py +++ b/local_backend/routers/system.py @@ -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() diff --git a/local_backend/tests/test_log_download.py b/local_backend/tests/test_log_download.py new file mode 100644 index 0000000..7ba5b5d --- /dev/null +++ b/local_backend/tests/test_log_download.py @@ -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" diff --git a/local_backend/tests/test_setup_language.py b/local_backend/tests/test_setup_language.py new file mode 100644 index 0000000..b066e3b --- /dev/null +++ b/local_backend/tests/test_setup_language.py @@ -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" diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index 4855a17..5555467 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -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() { } /> } /> - }> + }> } /> {/* ── Operation ── */} diff --git a/manager_dashboard/src/components/NotificationBell.jsx b/manager_dashboard/src/components/NotificationBell.jsx new file mode 100644 index 0000000..9d6405d --- /dev/null +++ b/manager_dashboard/src/components/NotificationBell.jsx @@ -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 ( +
+ + + {open && ( +
+
+ {t('notifications.title')} + {data.unread > 0 && ( + + )} +
+ {data.items.length === 0 + ?

{t('notifications.empty')}

+ : ( +
    + {data.items.map(n => ( +
  • + +
  • + ))} +
+ )} +
+ )} +
+ ) +} diff --git a/manager_dashboard/src/layouts/AppLayout.jsx b/manager_dashboard/src/layouts/AppLayout.jsx index 31397bb..cd40691 100644 --- a/manager_dashboard/src/layouts/AppLayout.jsx +++ b/manager_dashboard/src/layouts/AppLayout.jsx @@ -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() { /> - {/* Notifications (placeholder) */} - + {/* Platform notifications (2.6f) */} + {/* Divider */}
diff --git a/manager_dashboard/src/live/LiveProvider.jsx b/manager_dashboard/src/live/LiveProvider.jsx new file mode 100644 index 0000000..26139de --- /dev/null +++ b/manager_dashboard/src/live/LiveProvider.jsx @@ -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 {children} +} diff --git a/manager_dashboard/src/live/context.js b/manager_dashboard/src/live/context.js new file mode 100644 index 0000000..971c200 --- /dev/null +++ b/manager_dashboard/src/live/context.js @@ -0,0 +1,4 @@ +import { createContext } from 'react' + +/** { subscribe(type, fn) → unsubscribe } or null outside */ +export const LiveContext = createContext(null) diff --git a/manager_dashboard/src/live/useLiveEvent.js b/manager_dashboard/src/live/useLiveEvent.js new file mode 100644 index 0000000..15b93a1 --- /dev/null +++ b/manager_dashboard/src/live/useLiveEvent.js @@ -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]) +} diff --git a/manager_dashboard/src/main.jsx b/manager_dashboard/src/main.jsx index d913bb7..a44b176 100644 --- a/manager_dashboard/src/main.jsx +++ b/manager_dashboard/src/main.jsx @@ -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: { diff --git a/manager_dashboard/src/pages/Settings/SettingsPage.jsx b/manager_dashboard/src/pages/Settings/SettingsPage.jsx index 96267a2..630ea45 100644 --- a/manager_dashboard/src/pages/Settings/SettingsPage.jsx +++ b/manager_dashboard/src/pages/Settings/SettingsPage.jsx @@ -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 (
- +
{activeTab === 'app-info' && } + {activeTab === 'venue' &&
} {activeTab === 'security' && } {activeTab === 'operation' && } {activeTab === 'colours' && } diff --git a/manager_dashboard/src/pages/Settings/sections/PrintAlertSetting.jsx b/manager_dashboard/src/pages/Settings/sections/PrintAlertSetting.jsx new file mode 100644 index 0000000..c87fcc4 --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/PrintAlertSetting.jsx @@ -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 ( + + + s.save(key, e.target.value)} + options={options} data-testid={`setting-${key}`} /> + ) + const toggle = (key, fallback, label) => ( + s.save(key, v ? 'true' : 'false')} data-testid={`setting-${key}`} /> + ) + const waiterMode = s.get('auth.waiter_login_mode', 'pin') + + return ( + + + {select('auth.manager_login_mode', 'password', opts(['password', 'pin'], 'settings.mode'), idManager)} + + + {toggle('security.autofill_username', 'true', t('settings.signIn.autofill'))} + + + {select('auth.waiter_login_mode', 'pin', opts(['pin', 'password', 'tap'], 'settings.mode'), idWaiter)} + + + {toggle('auth.waiter_require_username', 'false', t('settings.signIn.requireUsername'))} + + + {select('auth.default_login_mode', 'pin', opts(['pin', 'password', 'tap', 'none'], 'settings.mode'), idDevice)} + + + {select('auth.single_session_manager', 'off', opts(SESSION_RULES, 'settings.session'), idSingleManager)} + + + {select('auth.single_session_waiter', 'off', opts(SESSION_RULES, 'settings.session'), idSingleWaiter)} + + + ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/VenueSettings.jsx b/manager_dashboard/src/pages/Settings/sections/VenueSettings.jsx new file mode 100644 index 0000000..6a6c8c2 --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/VenueSettings.jsx @@ -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
+ + return ( + + + s.save('venue.timezone', e.target.value)} + options={zones.map(z => ({ value: z, label: z.replace(/_/g, ' ') }))} /> + + + ) +} diff --git a/manager_dashboard/src/pages/Settings/sections/timeZones.js b/manager_dashboard/src/pages/Settings/sections/timeZones.js new file mode 100644 index 0000000..2cb7a07 --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/timeZones.js @@ -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' } +} diff --git a/manager_dashboard/src/pages/Settings/sections/useSettings.js b/manager_dashboard/src/pages/Settings/sections/useSettings.js new file mode 100644 index 0000000..dce1ac3 --- /dev/null +++ b/manager_dashboard/src/pages/Settings/sections/useSettings.js @@ -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, + } +} diff --git a/manager_dashboard/src/pages/Settings/tabs/PrintFontsTab.jsx b/manager_dashboard/src/pages/Settings/tabs/PrintFontsTab.jsx index 29970bd..10576e6 100644 --- a/manager_dashboard/src/pages/Settings/tabs/PrintFontsTab.jsx +++ b/manager_dashboard/src/pages/Settings/tabs/PrintFontsTab.jsx @@ -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 (
+ {/* 1. Printers */} diff --git a/manager_dashboard/src/pages/Settings/tabs/SecurityTab.jsx b/manager_dashboard/src/pages/Settings/tabs/SecurityTab.jsx index 0c60034..39b444a 100644 --- a/manager_dashboard/src/pages/Settings/tabs/SecurityTab.jsx +++ b/manager_dashboard/src/pages/Settings/tabs/SecurityTab.jsx @@ -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 ( -
- {options.map(opt => ( - - ))} -
- ) -} - function TimeSelect({ value, onChange, disabled }) { return (
@@ -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 (
- {/* ── Μέθοδος σύνδεσης ─────────────────────────────────────────────── */} - - - save('security.login_method', v)} - disabled={busy} - options={[ - { value: 'password', label: 'Κωδικός' }, - { value: 'pin', label: 'PIN' }, - { value: 'none', label: 'Κανένα' }, - ]} - /> - - - {loginMethod === 'none' && ( -
- Προσοχή: με έναν μόνο λογαριασμό διαχειριστή, η εφαρμογή θα ανοίγει χωρίς πιστοποίηση. - Χρησιμοποιήστε αυτό μόνο σε φυσικά ασφαλή, ιδιωτική συσκευή. -
- )} - - - save('security.autofill_username', v ? 'true' : 'false')} - disabled={busy} - /> - -
+ {/* Sign-in (2.6f): the v2 settings auth.* replace the v1 security.login_method card */} + {/* ── Αυτόματο κλείδωμα ────────────────────────────────────────────── */} {errors.venueType}

}
+
+ + +

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

+
+

Venue name

({ + 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 }) diff --git a/manager_dashboard/src/pages/reports/TechnicalPage.jsx b/manager_dashboard/src/pages/reports/TechnicalPage.jsx index 43941d6..6fe195d 100644 --- a/manager_dashboard/src/pages/reports/TechnicalPage.jsx +++ b/manager_dashboard/src/pages/reports/TechnicalPage.jsx @@ -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 (
- +
diff --git a/manager_dashboard/src/pages/reports/operations/LogsPanel.jsx b/manager_dashboard/src/pages/reports/operations/LogsPanel.jsx new file mode 100644 index 0000000..0249a2a --- /dev/null +++ b/manager_dashboard/src/pages/reports/operations/LogsPanel.jsx @@ -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
{t('common:actions.retry')}} />
+ if (!rows) return
+ + return ( +
+

{t('logs.intro')}

+ {error &&

{error}

} + {rows.length === 0 + ? } title={t('logs.empty')} /> + : ( +
+ {rows.map(row => ( +
+
+
+ {f.formatDate(row.date, 'dateLong')}{row.date === new Date().toISOString().slice(0, 10) && {t('logs.current')}} +
+
{row.name} · {t('logs.size', { size: f.formatNumber(Math.max(1, Math.round(row.size / 1024))) })}
+
+ +
+ ))} +
+ )} +
+ ) +} diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index 25a5be3..7e71e87 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -68,5 +68,8 @@ "catalog": { "unknown_category": "Δεν υπάρχει η κατηγορία {{category_id}}.", "primary_not_listed": "Η κύρια κατηγορία ({{category_id}}) πρέπει να είναι μία από τις κατηγορίες του προϊόντος." + }, + "system": { + "log_not_found": "Δεν υπάρχει αρχείο καταγραφής για {{date}}." } } diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index bad7589..a65aad0 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -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": "Η γλώσσα των οθονών του προσωπικού (ο καθένας μπορεί να διαλέξει τη δική του) και των εκτυπωμένων δελτίων και αναφορών." } } diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index 0d281d8..afac416 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -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}}." } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index 4cfba4c..f812907 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -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." } } diff --git a/packages/ui/src/index.js b/packages/ui/src/index.js index 0a65ddc..e9dff64 100644 --- a/packages/ui/src/index.js +++ b/packages/ui/src/index.js @@ -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' diff --git a/packages/ui/src/theme.js b/packages/ui/src/theme.js new file mode 100644 index 0000000..074f28c --- /dev/null +++ b/packages/ui/src/theme.js @@ -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 . 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 +} diff --git a/packages/ui/tests/theme.test.mjs b/packages/ui/tests/theme.test.mjs new file mode 100644 index 0000000..c4979cd --- /dev/null +++ b/packages/ui/tests/theme.test.mjs @@ -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') +}) diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 91a5fb6..5b650a6 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -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 | diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index 8246fe7..8ce0386 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -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-.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() diff --git a/tests/e2e/ui.mjs b/tests/e2e/ui.mjs index a1b1a50..97dceef 100644 --- a/tests/e2e/ui.mjs +++ b/tests/e2e/ui.mjs @@ -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 ', 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 ', 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()