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