feat(manager): staff permission editor, signed-in sessions, approvals log (platform-v2 2.6e)

- Staff: the 13 perm_* tick columns become one Permissions column (count,
  "changed from role") opening an editor grouped by module, from
  /api/waiters/permission-catalog: switches labelled per key, keys you don't
  hold are disabled with the reason, reset to role defaults (names what it
  can't give), save the whole set; access.cannot_grant explained by label.
- "Signed in now" (/management/sessions): who, where (app or device), since,
  last active, your own session marked; end session; show ended + reason.
- "Manager approvals" (/management/approvals): the override audit with
  action label, asked by, approved by, device, used/not used, order link.
- Backend: sessions list adds device_name/device_app/current/expires_at;
  overrides list adds device_name/expires_at.
- Permission labels for every key in modules.json (en/el), guarded by
  test_module_texts; manager unit tests for the editor logic; e2e 66 checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 08:10:57 +02:00
co-authored by Claude Opus 5.5
parent cc00ec39c7
commit 92bc1b0113
20 changed files with 1135 additions and 189 deletions
+1 -1
View File
@@ -168,7 +168,7 @@ Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overri
Design tokens are CSS variables prefixed `--x-` (`packages/ui/src/tokens.css`), components use `.x-*` classes (`src/components.css`); neither file has element selectors, resets or anything that applies outside `.x-*` (the waiter keeps its own `--bg`/`--text`…; the manager's Tailwind classes keep their meaning). Theme comes from `data-theme` (`light`/`dark`/`system`) and `data-venue-theme` on `<html>`. Tailwind apps use `@xenia/ui/tailwind-preset` (adds `bg-surface`, `text-ink-2`, `rounded-control`… only). A colour change must pass `npm test -w @xenia/ui` (WCAG AA for every pair the components use, every venue theme, light and dark). Components take their visible text as props with English defaults until `@xenia/i18n` (2.4). New components get a section in `packages/ui/gallery/Gallery.jsx` (dev-only `/ui-gallery` in the manager) and checks in `tests/e2e/ui.mjs`.
**CS-17. Frontend text is a key; dates are venue time** (branch `platform-v2`, D-11, D-12, §7.2, §8).
New UI text goes into `packages/i18n/locales/en/<ns>.json` first, then `el` (same keys, same `{{placeholders}}`), and is shown with `t()` from `@xenia/i18n` (`useTranslation`, re-exported). Dates and times are shown only through `useFormat()` (`formatTime`, `formatDateTime`, `formatDate`, `formatRelative`), which use the venue zone from bootstrap; money with `formatMoney`, numbers with `formatNumber`; typed numbers are read with `parseNumber` (comma or dot). Business dates (`YYYY-MM-DD`) go to `formatDate` as they are. `npm test -w @xenia/i18n` runs `scripts/check-i18n.mjs`, which fails on keys missing in English, placeholder mismatches, and `toLocale…String()` / `new Intl.DateTimeFormat(` without `timeZone` in new code (`packages/*`, `terminal/`); it warns for missing Greek. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `<UiLabelsProvider labels={useUiLabels()}>` at the app root.
New UI text goes into `packages/i18n/locales/en/<ns>.json` first, then `el` (same keys, same `{{placeholders}}`), and is shown with `t()` from `@xenia/i18n` (`useTranslation`, re-exported). Dates and times are shown only through `useFormat()` (`formatTime`, `formatDateTime`, `formatDate`, `formatRelative`), which use the venue zone from bootstrap; money with `formatMoney`, numbers with `formatNumber`; typed numbers are read with `parseNumber` (comma or dot). Business dates (`YYYY-MM-DD`) go to `formatDate` as they are. `npm test -w @xenia/i18n` runs `scripts/check-i18n.mjs`, which fails on keys missing in English, placeholder mismatches, and `toLocale…String()` / `new Intl.DateTimeFormat(` without `timeZone` in new code (`packages/*`, `terminal/`); it warns for missing Greek. Module names, their limits and **every permission key** have texts in `modules.json` (`modules:<module>.name`, `.limits.<key>`, `.permissions.<rest of the key, nested by its dots>`); `tests/test_module_texts.py` fails for a new module or key without them in both languages. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `<UiLabelsProvider labels={useUiLabels()}>` at the app root.
**CS-18. Frontends talk to the backend through `@xenia/api` and read access from bootstrap** (branch `platform-v2`, D-7, D-10, §9).
An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. Lock screens never log in again: they call `POST /api/auth/unlock {pin}` with the current session (same token; 5 wrong PINs end the session); manager sign-in sends `client: "manager"` and reads its mode from bootstrap `login`. The app root is `<AccessProvider client token i18n>`: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand).
+4 -1
View File
@@ -11,6 +11,7 @@ from core.access.deps import require
from core.timeutil import iso_z
from database import get_db
from models.access_override import AccessOverride
from models.device import Device
from models.user import User
from routers.deps import get_current_user
@@ -41,6 +42,8 @@ def list_overrides(limit: int = 200, db: Session = Depends(get_db), user=Depends
rows = db.query(AccessOverride).order_by(AccessOverride.id.desc()).limit(max(1, min(limit, 1000))).all()
ids = {r.requested_by for r in rows} | {r.approved_by for r in rows}
names = {u.id: u.full_name or u.username for u in db.query(User).filter(User.id.in_(ids - {None})).all()}
devices = {d.id: d.name for d in db.query(Device).filter(Device.id.in_({r.device_id for r in rows} - {None})).all()}
return [{"id": r.id, "key": r.key, "requested_by": r.requested_by, "requested_by_name": names.get(r.requested_by),
"approved_by": r.approved_by, "approved_by_name": names.get(r.approved_by), "device_id": r.device_id,
"created_at": iso_z(r.created_at), "used_at": iso_z(r.used_at), "target": r.target} for r in rows]
"device_name": devices.get(r.device_id), "created_at": iso_z(r.created_at), "expires_at": iso_z(r.expires_at),
"used_at": iso_z(r.used_at), "target": r.target} for r in rows]
+11 -5
View File
@@ -279,24 +279,30 @@ def support_verify(body: SupportVerifyRequest, request: Request, db: Session = D
# ── Sessions (D-9): who is logged in where ─────────────────────────────────
def _session_out(s, users: dict) -> dict:
def _session_out(s, users: dict, devices: dict, current_sid) -> dict:
u = users.get(s.user_id)
d = devices.get(s.device_id)
return {"id": s.id, "user_id": s.user_id, "username": u.username if u else ("support" if s.client == "support" else None),
"full_name": u.full_name if u else None, "client": s.client, "device_id": s.device_id,
"created_at": iso_z(s.created_at), "last_seen_at": iso_z(s.last_seen_at),
"device_name": d.name if d else None, "device_app": d.app_key if d else None,
"current": s.id == current_sid,
"created_at": iso_z(s.created_at), "last_seen_at": iso_z(s.last_seen_at), "expires_at": iso_z(s.expires_at),
"ended_at": iso_z(s.ended_at), "end_reason": s.end_reason, "ip": s.ip, "user_agent": s.user_agent}
@router.get("/sessions")
def list_sessions(include_ended: bool = False, db: Session = Depends(get_db),
def list_sessions(request: Request, include_ended: bool = False, db: Session = Depends(get_db),
user: User = Depends(require("core.staff.manage"))):
"""Active sessions (optionally the last 200 ended ones too), newest first."""
"""Active sessions (optionally the last 200 ended ones too), newest first. `current`
marks the caller's own session; `device_name`/`device_app` name a terminal's device."""
from models.device import Device
q = db.query(LoginSession)
if not include_ended:
q = q.filter(LoginSession.ended_at.is_(None))
rows = q.order_by(LoginSession.created_at.desc()).limit(200).all()
users = {u.id: u for u in db.query(User).filter(User.id.in_({r.user_id for r in rows if r.user_id})).all()}
return [_session_out(r, users) for r in rows]
devices = {d.id: d for d in db.query(Device).filter(Device.id.in_({r.device_id for r in rows if r.device_id})).all()}
return [_session_out(r, users, devices, getattr(request.state, "xenia_sid", None)) for r in rows]
@router.post("/sessions/{sid}/end")
+11
View File
@@ -296,3 +296,14 @@ def test_waiter_tap_still_needs_device(client, make_user, login):
client.put("/api/settings/auth.waiter_login_mode", headers=admin_h, json={"value": "tap"})
w = make_user(role="waiter")
assert err(client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id})) == "auth.mode_needs_device"
def test_sessions_list_names_the_device_and_the_callers_own(client, owner_h, pair, make_user): # 2.6e
token, _ = pair("kds", "Kitchen")
chef = make_user(role="chef")
client.post("/api/auth/login", headers=dev_h(token), json={"client": "terminal", "user_id": chef.id, "pin": TEST_PIN})
rows = client.get("/api/auth/sessions", headers=owner_h).json()
term = next(s for s in rows if s["user_id"] == chef.id)
assert term["client"] == "terminal" and term["device_name"] == "Kitchen" and term["device_app"] == "kds"
assert term["current"] is False
assert [s["current"] for s in rows].count(True) == 1 # the owner's own session
+22
View File
@@ -24,3 +24,25 @@ def test_every_module_has_texts(lang):
missing.append(f"{m.key}.limits.{lim.key}")
assert missing == []
assert set(texts) == set(registry()), "texts for modules that don't exist"
@pytest.mark.parametrize("lang", ["en", "el"])
def test_every_permission_has_a_label(lang):
"""modules:<module>.permissions.<rest of the key>, nested by its dots (plan step 2.6e)."""
texts = json.loads((LOCALES / lang / "modules.json").read_text(encoding="utf-8"))
missing, known = [], set()
for m in registry().values():
for p in m.permissions:
node = texts.get(m.key, {}).get("permissions", {})
for part in p.key.split(".", 1)[1].split("."):
node = node.get(part, {}) if isinstance(node, dict) else {}
if not isinstance(node, str) or not node:
missing.append(p.key)
known.add(p.key)
assert missing == []
def leaves(prefix, node):
for k, v in node.items():
yield from (leaves(f"{prefix}.{k}", v) if isinstance(v, dict) else [f"{prefix}.{k}"])
labelled = {k for mod, t in texts.items() for k in leaves(mod, t.get("permissions", {}))}
assert labelled - known == set(), "labels for permissions that don't exist"
+1
View File
@@ -87,6 +87,7 @@ def test_waiter_cancels_after_manager_pin(client, db, venue, login):
assert err(client.get("/api/access/overrides", headers=v["waiter_h"])) == "access.denied"
listed = client.get("/api/access/overrides", headers=login(v["manager"])).json()
assert listed[0]["approved_by_name"] == v["manager"].full_name and listed[0]["target"] == f"order:{v['order'].id}"
assert listed[0]["expires_at"].endswith("Z") and listed[0]["device_name"] is None # 2.6e: names the device when there is one
def test_token_is_bound_to_its_key(client, db, venue, make_user, login):
+4
View File
@@ -32,6 +32,8 @@ import TabsPage from './pages/financials/TabsPage'
import ProductsPage from './pages/Management/ProductsPage'
import TablesConfigPage from './pages/Management/TablesConfigPage'
import StaffPage from './pages/Management/StaffPage'
import SessionsPage from './pages/staff/SessionsPage'
import ApprovalsPage from './pages/staff/ApprovalsPage'
import ManagementSchedulePage from './pages/Management/SchedulePage'
import PrepZonesConfigPage from './pages/Management/PrepZonesConfigPage'
import PricingPage from './pages/Management/PricingPage'
@@ -160,6 +162,8 @@ export default function App() {
<Route path="management/products" element={<ProductsPage />} />
<Route path="management/tables" element={<TablesConfigPage />} />
<Route path="management/staff" element={<StaffPage />} />
<Route path="management/sessions" element={<SessionsPage />} />
<Route path="management/approvals" element={<ApprovalsPage />} />
<Route path="management/schedule" element={<ManagementSchedulePage />} />
<Route path="management/prep-zones" element={<PrepZonesConfigPage />} />
<Route path="management/pricing" element={<PricingPage />} />
+29 -139
View File
@@ -4,6 +4,9 @@ import toast from 'react-hot-toast'
import client from '../api/client'
import { ConfirmModal } from '../ui/Modal'
import Button from '../ui/Button'
import { useTranslation } from '@xenia/i18n'
import PermissionEditor from './staff/PermissionEditor'
import { differsFromRole } from './staff/permissionsLogic'
// ── Role definitions (mirrors backend roles.py) ───────────────────────────────
export const ALL_ROLES = [
@@ -22,26 +25,6 @@ export const ALL_ROLES = [
const ROLE_MAP = Object.fromEntries(ALL_ROLES.map(r => [r.value, r]))
// Permission column definitions — grouped for the table header
export const PERM_COLUMNS = [
// Access
{ key: 'perm_access_dashboard', label: 'Dashboard', group: 'Πρόσβαση' },
{ key: 'perm_access_waiter_app', label: 'POS App', group: 'Πρόσβαση' },
{ key: 'perm_access_kds', label: 'KDS', group: 'Πρόσβαση' },
// Orders
{ key: 'perm_open_orders', label: 'Άνοιγμα', group: 'Παραγγελίες' },
{ key: 'perm_close_orders', label: 'Κλείσιμο', group: 'Παραγγελίες' },
{ key: 'perm_cancel_orders', label: 'Ακύρωση', group: 'Παραγγελίες' },
{ key: 'perm_apply_discounts', label: 'Εκπτώσεις', group: 'Παραγγελίες' },
{ key: 'perm_modify_prices', label: 'Τιμές', group: 'Παραγγελίες' },
// Management
{ key: 'perm_view_reports', label: 'Αναφορές', group: 'Διαχείριση' },
{ key: 'perm_manage_staff', label: 'Προσωπικό', group: 'Διαχείριση' },
{ key: 'perm_manage_menu', label: 'Μενού', group: 'Διαχείριση' },
{ key: 'perm_manage_tables', label: 'Τραπέζια', group: 'Διαχείριση' },
{ key: 'perm_manage_settings', label: 'Ρυθμίσεις', group: 'Διαχείριση' },
]
// ── Avatar helpers ─────────────────────────────────────────────────────────────
function avatarColor(name) {
const palette = ['#3758c9', '#7a44c9', '#2f9e5e', '#d94b26', '#8a6d2b', '#0d7a8a', '#c93775']
@@ -110,59 +93,8 @@ function PinInput({ value, onChange }) {
)
}
// ── Permission toggle cell ─────────────────────────────────────────────────────
function PermToggle({ staffId, permKey, value, disabled, onToggle }) {
const [optimistic, setOptimistic] = useState(value)
const [saving, setSaving] = useState(false)
useEffect(() => { setOptimistic(value) }, [value])
async function handleClick() {
if (disabled || saving) return
const next = !optimistic
setOptimistic(next)
setSaving(true)
try {
await onToggle(staffId, permKey, next)
} catch {
setOptimistic(!next) // revert on error
} finally {
setSaving(false)
}
}
const on = optimistic
return (
<button
onClick={handleClick}
disabled={disabled}
title={disabled ? 'Ο superadmin έχει πάντα αυτό το δικαίωμα' : undefined}
style={{
width: 26, height: 26, borderRadius: 6, border: 'none',
background: disabled ? '#e5e7eb' : on ? '#22c55e' : '#f3f4f6',
color: disabled ? '#9ca3af' : on ? '#fff' : '#d1d5db',
cursor: disabled ? 'not-allowed' : 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
transition: 'all 120ms',
opacity: saving ? 0.6 : 1,
flexShrink: 0,
}}
>
{on ? (
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
<polyline points="20 6 9 17 4 12" />
</svg>
) : (
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
<line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
</svg>
)}
</button>
)
}
// ── Actions dropdown ───────────────────────────────────────────────────────────
function ActionsMenu({ member, onEdit, onZones, onResetPin, onBlock, onDelete, onResetPerms, isSuperadmin }) {
function ActionsMenu({ member, onEdit, onZones, onResetPin, onBlock, onDelete, onPermissions, permissionsLabel, isSuperadmin }) {
const [open, setOpen] = useState(false)
const ref = useRef(null)
@@ -177,7 +109,7 @@ function ActionsMenu({ member, onEdit, onZones, onResetPin, onBlock, onDelete, o
{ label: 'Επεξεργασία', icon: editIcon, onClick: onEdit },
{ label: 'Πρόσβαση σε Ζώνες', icon: zonesIcon, onClick: onZones },
{ label: 'Επαναφορά PIN', icon: pinIcon, onClick: onResetPin },
!isSuperadmin && { label: 'Επαναφορά Δικαιωμάτων', icon: resetIcon, onClick: onResetPerms },
{ label: permissionsLabel, icon: resetIcon, onClick: onPermissions },
!isSuperadmin && { label: member.is_active ? 'Μπλοκάρισμα' : 'Ξεμπλοκάρισμα', icon: blockIcon, onClick: onBlock, color: member.is_active ? '#f97316' : '#22c55e' },
!isSuperadmin && { label: 'Διαγραφή', icon: trashIcon, onClick: onDelete, color: '#ef4444' },
].filter(Boolean)
@@ -331,6 +263,8 @@ export default function StaffPage() {
const [editModal, setEditModal] = useState(null)
const [editForm, setEditForm] = useState({ username: '', full_name: '', nickname: '', mobile_phone: '', email: '', note: '', role: 'waiter', hourly_rate: '' })
const [filterRole, setFilterRole] = useState('all')
const [permEditor, setPermEditor] = useState(null)
const { t } = useTranslation('manager')
const avatarInputRef = useRef(null)
const newAvatarInputRef = useRef(null)
@@ -338,6 +272,10 @@ export default function StaffPage() {
queryKey: ['staff'],
queryFn: () => client.get('/api/waiters/').then(r => r.data),
})
const { data: catalog } = useQuery({
queryKey: ['permission-catalog'],
queryFn: () => client.get('/api/waiters/permission-catalog').then(r => r.data),
})
const { data: groups = [] } = useQuery({
queryKey: ['table-groups'],
queryFn: () => client.get('/api/tables/groups').then(r => r.data),
@@ -402,17 +340,6 @@ export default function StaffPage() {
onError: () => toast.error('Σφάλμα'),
})
const resetPerms = useMutation({
mutationFn: (id) => client.put(`/api/waiters/${id}/reset-permissions`),
onSuccess: () => { toast.success('Δικαιώματα επαναφέρθηκαν'); invalidate() },
onError: () => toast.error('Σφάλμα'),
})
async function togglePermission(memberId, permKey, value) {
await client.put(`/api/waiters/${memberId}/permission`, { permission: permKey, value })
invalidate()
}
if (isLoading) return <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
function openEdit(m) {
@@ -436,13 +363,6 @@ export default function StaffPage() {
const filtered = filterRole === 'all' ? staff : staff.filter(m => m.role === filterRole)
// Build column group spans for the table header
const groups2 = [
{ label: 'Πρόσβαση', cols: PERM_COLUMNS.filter(c => c.group === 'Πρόσβαση') },
{ label: 'Παραγγελίες', cols: PERM_COLUMNS.filter(c => c.group === 'Παραγγελίες') },
{ label: 'Διαχείριση', cols: PERM_COLUMNS.filter(c => c.group === 'Διαχείριση') },
]
return (
<div className="flex flex-col h-full min-h-0">
{/* ── Header bar ── */}
@@ -487,47 +407,19 @@ export default function StaffPage() {
<colgroup>
<col style={{ width: 220, minWidth: 220 }} />
<col style={{ width: 90, minWidth: 90 }} />
{PERM_COLUMNS.map(c => (
<col key={c.key} style={{ width: 58, minWidth: 54 }} />
))}
<col style={{ width: 260, minWidth: 200 }} />
<col style={{ width: 120, minWidth: 110 }} />
</colgroup>
<thead>
{/* Group header row */}
<tr style={{ borderBottom: '1px solid #e5e7eb', background: '#f9fafb' }}>
<th style={thBase} />
<th style={thBase} />
{groups2.map(g => (
<th key={g.label} colSpan={g.cols.length} style={{
...thBase,
borderLeft: '1px solid #e5e7eb',
color: '#374151', fontWeight: 700, fontSize: 10,
textTransform: 'uppercase', letterSpacing: '0.06em',
textAlign: 'center', padding: '6px 0',
}}>
{g.label}
</th>
))}
<th style={thBase} />
</tr>
{/* Column label row */}
<tr style={{ borderBottom: '2px solid #e5e7eb', background: '#f9fafb' }}>
<th style={{ ...thBase, textAlign: 'left', padding: '6px 16px', fontWeight: 600, color: '#374151' }}>
Εργαζόμενος
</th>
<th style={{ ...thBase, textAlign: 'center', color: '#6b7280', fontWeight: 500 }}>Κατάσταση</th>
{PERM_COLUMNS.map((c, i) => (
<th key={c.key} style={{
...thBase,
textAlign: 'center', color: '#6b7280', fontWeight: 500,
borderLeft: i === 0 || PERM_COLUMNS[i - 1]?.group !== c.group ? '1px solid #e5e7eb' : undefined,
writingMode: 'vertical-rl', transform: 'rotate(180deg)',
height: 72, padding: '4px 0',
fontSize: 11,
}}>
{c.label}
<th style={{ ...thBase, textAlign: 'left', padding: '6px 12px', color: '#6b7280', fontWeight: 500 }}>
{t('permissions.column')}
</th>
))}
<th style={{ ...thBase, textAlign: 'right', padding: '6px 12px', color: '#6b7280', fontWeight: 500 }}>
Ενέργειες
</th>
@@ -582,23 +474,18 @@ export default function StaffPage() {
</span>
</td>
{/* Permission toggle cells */}
{PERM_COLUMNS.map((col, i) => (
<td key={col.key} style={{
textAlign: 'center', verticalAlign: 'middle', padding: '0 4px',
borderLeft: i === 0 || PERM_COLUMNS[i - 1]?.group !== col.group ? '1px solid #f3f4f6' : undefined,
}}>
<div style={{ display: 'flex', justifyContent: 'center' }}>
<PermToggle
staffId={member.id}
permKey={col.key}
value={isSuperadmin ? true : !!member[col.key]}
disabled={isSuperadmin}
onToggle={togglePermission}
/>
</div>
{/* Permissions (2.6e): count + "custom" when they differ from the role */}
<td style={{ padding: '0 12px', verticalAlign: 'middle' }} data-testid={`staff-perms-${member.id}`}>
<button type="button" onClick={() => setPermEditor(member)}
className="text-left text-label text-ink-2 hover:text-accent-ink inline-flex items-center gap-2">
{isSuperadmin
? t('permissions.all')
: t('permissions.count', { count: member.permissions?.length || 0 })}
{!isSuperadmin && catalog && differsFromRole(member.permissions || [], catalog.role_templates[member.role] || []) && (
<span className="rounded-full px-2 py-0.5 text-caption font-medium bg-warning-soft text-warning-ink">{t('permissions.custom')}</span>
)}
</button>
</td>
))}
{/* Actions cell */}
<td style={{ textAlign: 'right', padding: '0 12px', verticalAlign: 'middle' }}>
@@ -610,7 +497,8 @@ export default function StaffPage() {
onResetPin={() => setPinModal(member.id)}
onBlock={() => toggleBlock.mutate(member.id)}
onDelete={() => setConfirmDelete(member.id)}
onResetPerms={() => resetPerms.mutate(member.id)}
onPermissions={() => setPermEditor(member)}
permissionsLabel={t('permissions.open')}
/>
</td>
</tr>
@@ -687,6 +575,8 @@ export default function StaffPage() {
/>
)}
{permEditor && <PermissionEditor member={permEditor} onClose={() => setPermEditor(null)} />}
{zoneModal && (
<ZoneModal member={zoneModal} groups={groups} onClose={() => setZoneModal(null)} />
)}
@@ -0,0 +1,84 @@
// "Manager approvals" (plan step 2.6e, APPS_PLATFORM D-10): the record of every time a
// manager typed their PIN to allow one action for someone who lacks the permission (cancel
// a sent item, change a price, a discount over the limit…). Backend: GET /api/access/overrides
// (core.staff.manage), newest first, the latest 200. Rows are never deleted.
// An approval is valid for 60 s, once: "Not used" = it expired before the action happened.
import { useCallback, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { ShieldCheck } 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'
import { approvalState, approvalTarget, permLabelKey } from './permissionsLogic'
const STATE_TONE = {
used: 'bg-success-soft text-success-ink',
expired: 'bg-surface-2 text-ink-3',
waiting: 'bg-info-soft text-info-ink',
}
export default function ApprovalsPage() {
const { t } = useTranslation('manager')
const f = useFormat()
const [rows, setRows] = useState(null)
const [error, setError] = useState(null)
const load = useCallback(async () => {
try {
const r = await client.get('/api/access/overrides')
setRows(r.data)
setError(null)
} catch (err) {
setError(errorMessage(err, t))
}
}, [t])
useEffect(() => { load() }, [load])
if (error) 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 lg:p-8 max-w-6xl grid gap-6">
<p className="text-body text-ink-2 max-w-2xl">{t('approvals.intro')}</p>
{rows.length === 0
? <EmptyState icon={<ShieldCheck />} title={t('approvals.empty')} description={t('approvals.emptyBody')} />
: (
<div className="bg-surface border border-line rounded-card shadow-raised overflow-x-auto">
<table className="w-full text-body" data-testid="approvals-table">
<thead>
<tr className="text-left text-label text-ink-3 border-b border-line">
{['when', 'action', 'askedBy', 'approvedBy', 'where', 'result'].map(c => (
<th key={c} className="px-4 py-2.5 font-medium">{t(`approvals.columns.${c}`)}</th>
))}
</tr>
</thead>
<tbody>
{rows.map(r => {
const state = approvalState(r)
const target = approvalTarget(r.target)
return (
<tr key={r.id} className="border-b border-line last:border-0" data-testid={`approval-${r.id}`} data-state={state}>
<td className="px-4 py-3 text-ink-2 whitespace-nowrap">{f.formatDateTime(r.created_at, 'datetimeShort')}</td>
<td className="px-4 py-3 text-ink">{t(permLabelKey(r.key), { defaultValue: r.key })}</td>
<td className="px-4 py-3 text-ink-2">{r.requested_by_name || '—'}</td>
<td className="px-4 py-3 text-ink-2">{r.approved_by_name || '—'}</td>
<td className="px-4 py-3 text-ink-2">{r.device_name || '—'}</td>
<td className="px-4 py-3">
<span className={`rounded-full px-2.5 py-0.5 text-caption font-medium ${STATE_TONE[state]}`}>{t(`approvals.state.${state}`)}</span>
{state === 'used' && target?.order && (
<Link to={`/orders/${target.order}`} className="ml-2 text-label text-accent-ink hover:underline">{t('approvals.order', { id: target.order })}</Link>
)}
{state === 'used' && target?.text && <span className="ml-2 text-caption text-ink-3">{target.text}</span>}
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
</div>
)
}
@@ -0,0 +1,141 @@
// Staff permission editor (plan step 2.6e, APPS_PLATFORM D-7): every permission of the
// licensed modules, grouped by module, from GET /api/waiters/permission-catalog.
// - Saved as the whole key set: PUT /api/waiters/{id}/permissions. Keys of modules that
// aren't licensed aren't shown and are kept as they are.
// - You can only give permissions you hold yourself (backend: access.cannot_grant). Those
// switches are disabled with the reason; removing is always allowed.
// - "Reset to role defaults" fills the draft with the role's template (minus what you
// can't give, which it names); nothing is saved until Save.
// - A superadmin always has everything: read-only.
import { useEffect, useMemo, useState } from 'react'
import toast from 'react-hot-toast'
import { useQueryClient } from '@tanstack/react-query'
import { errorMessage, parseError } from '@xenia/api'
import { useAccess } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { Button, InfoTip, Sheet, Spinner, Switch } from '@xenia/ui'
import client from '../../api/client'
import { canGive, diff, editorGroups, permLabelKey, resetToRole } from './permissionsLogic'
export default function PermissionEditor({ member, onClose }) {
const { t } = useTranslation('manager')
const access = useAccess()
const qc = useQueryClient()
const actorIsSuperadmin = access.user?.role === 'superadmin'
const [data, setData] = useState(null) // { catalog, modules, target, grantable }
const [draft, setDraft] = useState(null)
const [error, setError] = useState('')
const [note, setNote] = useState('')
const [busy, setBusy] = useState(false)
useEffect(() => {
let alive = true
Promise.all([
client.get('/api/waiters/permission-catalog'),
client.get('/api/platform/modules'),
client.get(`/api/waiters/${member.id}/permissions`),
actorIsSuperadmin ? null : client.get(`/api/waiters/${access.user.id}/permissions`),
]).then(([c, m, p, mine]) => {
if (!alive) return
setData({
catalog: c.data.modules, modules: m.data.modules, target: p.data,
original: new Set(p.data.keys), grantable: mine ? new Set(mine.data.keys) : null,
})
setDraft(new Set(p.data.keys))
}).catch(err => alive && setError(errorMessage(err, t)))
return () => { alive = false }
}, [member.id, actorIsSuperadmin, access.user.id, t])
const groups = useMemo(() => (data ? editorGroups(data.catalog, data.modules, { actorIsSuperadmin }) : []), [data, actorIsSuperadmin])
const name = member.full_name || member.username
const label = key => t(permLabelKey(key))
const changes = data && draft ? diff(draft, data.original) : { added: [], removed: [] }
const changed = changes.added.length + changes.removed.length
const readOnly = data?.target.superadmin
function toggle(key, on) {
setNote('')
setError('')
setDraft(prev => {
const next = new Set(prev)
if (on) next.add(key)
else next.delete(key)
return next
})
}
function reset() {
const { keys, skipped } = resetToRole(data.target.role_template, data.original, data.grantable)
setDraft(keys)
setError('')
setNote(skipped.length ? t('permissions.resetSkipped', { list: skipped.map(label).join(', ') }) : t('permissions.resetDone'))
}
async function save() {
setBusy(true)
setError('')
try {
await client.put(`/api/waiters/${member.id}/permissions`, { keys: [...draft].sort() })
toast.success(t('permissions.saved', { name }))
qc.invalidateQueries({ queryKey: ['staff'] })
if (member.id === access.user.id) access.refresh()
onClose()
} catch (err) {
const x = parseError(err)
setError(x.code === 'access.cannot_grant' ? t('permissions.cannotGrant', { label: label(x.params.key) }) : errorMessage(err, t))
} finally {
setBusy(false)
}
}
const footer = readOnly || !data ? null : (
<>
<Button variant="ghost" onClick={reset} className="mr-auto" data-testid="perm-reset">{t('permissions.reset')}</Button>
<Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button>
<Button onClick={save} loading={busy} disabled={!changed}>
{changed ? t('permissions.saveCount', { count: changed }) : t('permissions.save')}
</Button>
</>
)
return (
<Sheet open side="right" onClose={onClose} title={t('permissions.title', { name })}
description={data ? t('permissions.subtitle', { role: t(`roles.${data.target.role}`, { defaultValue: data.target.role }) }) : undefined}
footer={footer}>
{!data && !error && <div className="py-10 flex justify-center"><Spinner /></div>}
{!data && error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
{readOnly && <p className="text-body text-ink-2">{t('permissions.superadmin')}</p>}
{data && !readOnly && (
<div className="grid gap-6" data-testid="perm-editor">
{note && <p className="text-label text-ink-2 bg-surface-2 rounded-card px-3 py-2" data-testid="perm-note">{note}</p>}
{error && <p className="text-label text-danger-ink bg-danger-soft rounded-card px-3 py-2" role="alert" data-testid="perm-error">{error}</p>}
{groups.map(g => (
<section key={g.key} data-testid={`perm-group-${g.key}`}>
<h3 className="text-label font-semibold text-ink mb-1 flex items-center gap-2">
{t(`modules:${g.key}.name`, { defaultValue: g.key })}
{!g.on && <span className="rounded-full px-2 py-0.5 text-caption font-medium bg-surface-2 text-ink-3">{t('permissions.moduleOff')}</span>}
</h3>
<div className="grid gap-2">
{g.permissions.map(p => {
const on = draft.has(p.key)
const allowed = on || canGive(p.key, data.original, data.grantable)
const fromRole = data.target.role_template.includes(p.key)
const hints = []
if (!allowed) hints.push(t('permissions.notYours'))
if (on !== fromRole) hints.push(fromRole ? t('permissions.roleHas') : t('permissions.roleHasNot'))
return (
<div key={p.key} className="flex items-start gap-1" data-testid={`perm-${p.key}`} data-on={on ? 'true' : 'false'}>
<Switch className="flex-1" checked={on} disabled={!allowed} onChange={v => toggle(p.key, v)}
label={label(p.key)} description={hints.join(' · ') || undefined} />
{p.overridable && <InfoTip>{t('permissions.overridable')}</InfoTip>}
</div>
)
})}
</div>
</section>
))}
</div>
)}
</Sheet>
)
}
@@ -0,0 +1,137 @@
// "Signed in now" (plan step 2.6e, APPS_PLATFORM D-9): who is signed in, in which app or on
// which device, since when, last activity; "End session" signs them out at once.
// Backend: GET /api/auth/sessions (?include_ended), POST /api/auth/sessions/{id}/end
// (core.staff.manage; a support session only by a superadmin). Your own session is marked
// and can't be ended here (that's "Sign out"). A session has no time limit (only support's
// 4 hours), so "last active" is what tells an old phone from someone working now.
import { useCallback, useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { LogIn } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useAccess } from '@xenia/access'
import { useTranslation, useFormat } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { canEndSession } from './permissionsLogic'
const REFRESH_MS = 30_000
export default function SessionsPage() {
const { t } = useTranslation('manager')
const f = useFormat()
const access = useAccess()
const actorIsSuperadmin = access.user?.role === 'superadmin'
const [rows, setRows] = useState(null)
const [error, setError] = useState(null)
const [showEnded, setShowEnded] = useState(false)
const [ending, setEnding] = useState(null)
const load = useCallback(async () => {
try {
const r = await client.get('/api/auth/sessions', { params: { include_ended: showEnded } })
setRows(r.data)
setError(null)
} catch (err) {
setError(errorMessage(err, t))
}
}, [showEnded, t])
useEffect(() => {
load()
const id = setInterval(load, REFRESH_MS)
return () => clearInterval(id)
}, [load])
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>
const person = s => (s.client === 'support' ? t('sessions.support') : (s.full_name || s.username || '—'))
const where = s => {
if (s.client === 'terminal') {
const app = s.device_app ? t(`modules:${s.device_app}.name`, { defaultValue: s.device_app }) : ''
return [s.device_name || t('sessions.unknownDevice'), app].filter(Boolean).join(' · ')
}
if (s.client === 'support' && s.expires_at) return t('sessions.client.supportUntil', { time: f.formatTime(s.expires_at) })
return t(`sessions.client.${s.client}`)
}
const live = rows.filter(s => !s.ended_at)
return (
<div className="p-6 lg:p-8 max-w-6xl grid gap-6">
<p className="text-body text-ink-2 max-w-2xl">{t('sessions.intro')}</p>
{live.length === 0 && !showEnded
? <EmptyState icon={<LogIn />} title={t('sessions.empty')} />
: (
<div className="bg-surface border border-line rounded-card shadow-raised overflow-x-auto">
<table className="w-full text-body" data-testid="sessions-table">
<thead>
<tr className="text-left text-label text-ink-3 border-b border-line">
{['person', 'where', 'since', 'active', ...(showEnded ? ['ended'] : []), 'actions'].map(c => (
<th key={c} className="px-4 py-2.5 font-medium">{t(`sessions.columns.${c}`)}</th>
))}
</tr>
</thead>
<tbody>
{rows.map(s => (
<tr key={s.id} className={`border-b border-line last:border-0 ${s.ended_at ? 'text-ink-3' : ''}`}
data-testid={`session-${s.id}`} data-client={s.client} data-user={s.user_id ?? ''} data-ended={s.ended_at ? 'true' : 'false'}>
<td className="px-4 py-3">
<div className={`font-medium ${s.ended_at ? '' : 'text-ink'}`}>{person(s)}</div>
{s.current && <span className="rounded-full px-2 py-0.5 text-caption font-medium bg-accent-soft text-accent-ink">{t('sessions.you')}</span>}
</td>
<td className="px-4 py-3 text-ink-2">{where(s)}</td>
<td className="px-4 py-3 text-ink-2 whitespace-nowrap">{f.formatDateTime(s.created_at, 'datetimeShort')}</td>
<td className="px-4 py-3 text-ink-2 whitespace-nowrap">{s.ended_at ? '—' : f.formatRelative(s.last_seen_at)}</td>
{showEnded && (
<td className="px-4 py-3 text-ink-2">
{s.ended_at ? `${f.formatRelative(s.ended_at)} · ${t(`sessions.reason.${s.end_reason}`, { defaultValue: s.end_reason || '' })}` : '—'}
</td>
)}
<td className="px-4 py-3 text-right whitespace-nowrap">
{canEndSession(s, { actorIsSuperadmin }) && (
<Button size="sm" variant="ghost" className="text-danger-ink" onClick={() => setEnding(s)}>{t('sessions.end')}</Button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<label className="inline-flex items-center gap-2 text-label text-ink-2 cursor-pointer w-fit">
<input type="checkbox" checked={showEnded} onChange={e => setShowEnded(e.target.checked)} />
{t('sessions.showEnded')}
</label>
{ending && (
<EndDialog session={ending} name={person(ending)} where={where(ending)} onClose={() => setEnding(null)}
onDone={() => { setEnding(null); toast.success(t('sessions.ended', { name: person(ending) })); load() }} />
)}
</div>
)
}
function EndDialog({ session, name, where, onClose, onDone }) {
const { t } = useTranslation('manager')
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
async function end() {
setBusy(true)
setError('')
try {
await client.post(`/api/auth/sessions/${session.id}/end`)
onDone()
} catch (err) {
setError(errorMessage(err, t))
setBusy(false)
}
}
return (
<Dialog open size="sm" onClose={onClose} title={t('sessions.endTitle', { name })} description={t('sessions.endBody', { where })}
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button variant="danger" loading={busy} onClick={end}>{t('sessions.end')}</Button></>}>
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
</Dialog>
)
}
@@ -0,0 +1,88 @@
// Pure logic of the staff permission editor, the sessions list and the approvals log
// (plan step 2.6e). No React here, so tests/platform.test.mjs can run it with node --test.
/** The module a permission key belongs to: its first segment ("ordering.orders.cancel" → "ordering"). */
export const moduleOf = key => key.split('.', 1)[0]
/** i18n key of a permission's label: modules:<module>.permissions.<rest>, nested by the dots. */
export const permLabelKey = key => `modules:${moduleOf(key)}.permissions.${key.slice(moduleOf(key).length + 1)}`
/**
* The groups the editor shows.
* catalog GET /api/waiters/permission-catalog → .modules
* modules GET /api/platform/modules → .modules (entitled / effective per module)
* A module that isn't licensed is left out (its keys are kept as they are when saving).
* Keys no role has (core.system.admin) are only shown to a superadmin.
* Order: core, then the modules that are on, then those turned off (catalogue order within).
*/
export function editorGroups(catalog, modules, { actorIsSuperadmin = false } = {}) {
const byKey = Object.fromEntries((modules || []).map(m => [m.key, m]))
return catalog
.filter(m => byKey[m.key]?.entitled !== false)
.map(m => ({
key: m.key,
on: byKey[m.key] ? !!byKey[m.key].effective : true,
permissions: m.permissions.filter(p => actorIsSuperadmin || p.roles.length > 0),
}))
.filter(g => g.permissions.length > 0)
.map((g, i) => ({ g, rank: (g.key === 'core' ? 0 : g.on ? 1 : 2) * 1000 + i }))
.sort((a, b) => a.rank - b.rank)
.map(x => x.g)
}
/** Keys added and removed by the draft, compared with what the user has now. */
export function diff(draft, original) {
return {
added: [...draft].filter(k => !original.has(k)).sort(),
removed: [...original].filter(k => !draft.has(k)).sort(),
}
}
/**
* May the editor switch this key ON? Removing is always allowed. Giving is allowed for a key
* the user already had (it isn't new) or one the editor holds; `grantable` null = superadmin.
* Same rule as the backend's access.cannot_grant.
*/
export function canGive(key, original, grantable) {
return grantable == null || original.has(key) || grantable.has(key)
}
/**
* "Reset to role defaults": the role's template, minus the keys the editor may not give.
* Returns { keys, skipped } so the editor can say what it couldn't add.
*/
export function resetToRole(template, original, grantable) {
const keys = new Set()
const skipped = []
for (const k of template) {
if (canGive(k, original, grantable)) keys.add(k)
else skipped.push(k)
}
return { keys, skipped: skipped.sort() }
}
/** Does this user's key set differ from their role's template? */
export function differsFromRole(keys, template) {
const a = new Set(keys)
const b = new Set(template)
return a.size !== b.size || [...a].some(k => !b.has(k))
}
/** An approval's outcome: used / expired (never used) / waiting (still valid). */
export function approvalState(row, { now = Date.now() } = {}) {
if (row.used_at) return 'used'
return Date.parse(row.expires_at) <= now ? 'expired' : 'waiting'
}
/** An approval's target as something to show: { order: id } or { text } or null. */
export function approvalTarget(target) {
if (!target) return null
const m = /^order:(\d+)$/.exec(target)
return m ? { order: Number(m[1]) } : { text: target }
}
/** May this manager end this session? Not their own (that's "sign out"), not support unless superadmin. */
export function canEndSession(session, { actorIsSuperadmin = false } = {}) {
if (session.ended_at || session.current) return false
return session.client !== 'support' || actorIsSuperadmin
}
+3 -1
View File
@@ -16,7 +16,7 @@ import {
BookUser, Users, Receipt, CreditCard,
Package, TableProperties, UserCog, CalendarDays, Trash2, Boxes,
BarChart2, TrendingUp, Users2, ShoppingCart, Tag, Activity, Printer, ConciergeBell, FileText,
AppWindow, Settings, CookingPot, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone,
AppWindow, Settings, CookingPot, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone, LogIn, ShieldCheck,
} from 'lucide-react'
const DASH = 'core.dashboard.access'
@@ -58,6 +58,8 @@ export const NAV = [
{ to: '/management/products', icon: Package, label: 'nav.products', module: 'catalog', perm: 'catalog.menu.manage' },
{ to: '/management/tables', icon: TableProperties, label: 'nav.tablesConfig', module: 'catalog', perm: 'catalog.tables.manage' },
{ to: '/management/staff', icon: UserCog, label: 'nav.staff', module: 'core', perm: 'core.staff.manage' },
{ to: '/management/sessions', icon: LogIn, label: 'nav.sessions', module: 'core', perm: 'core.staff.manage' },
{ to: '/management/approvals', icon: ShieldCheck, label: 'nav.approvals', module: 'core', perm: 'core.staff.manage' },
{ to: '/management/schedule', icon: CalendarDays, label: 'nav.schedule', module: 'staff_planning', perm: 'core.staff.manage' },
{ to: '/management/prep-zones', icon: CookingPot, label: 'nav.prepZones', module: 'catalog', perm: 'catalog.menu.manage' },
{ to: '/management/pricing', icon: Percent, label: 'nav.pricing', module: 'pricing', perm: 'catalog.menu.manage' },
+55 -1
View File
@@ -1,8 +1,11 @@
// Pure logic of the platform pages (plan steps 2.6c, 2.6d).
// Pure logic of the platform pages (plan steps 2.6c, 2.6d, 2.6e).
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode } from '../src/pages/platform/devicesLogic.js'
import { moduleState, stoppedBy } from '../src/pages/platform/modulesLogic.js'
import {
approvalState, approvalTarget, canEndSession, canGive, diff, differsFromRole, editorGroups, permLabelKey, resetToRole,
} from '../src/pages/staff/permissionsLogic.js'
const mod = (key, extra = {}) => ({ key, depends: [], can_disable: true, entitled: true, enabled: true, effective: true, limits: [], device_app: null, ...extra })
@@ -62,3 +65,54 @@ test('link targets: not itself, not removed', () => {
const devices = [{ id: 1, revoked_at: null }, { id: 2, revoked_at: 'x' }, { id: 3, revoked_at: null }]
assert.deepEqual(linkTargets(devices, 1).map(d => d.id), [3])
})
// ── 2.6e ────────────────────────────────────────────────────────────────────
test('permission label keys follow the dots of the key under the module', () => {
assert.equal(permLabelKey('ordering.orders.cancel'), 'modules:ordering.permissions.orders.cancel')
assert.equal(permLabelKey('kds.access'), 'modules:kds.permissions.access')
})
test('editor groups: licensed modules only (core, on, off), keys no role has only for a superadmin', () => {
const catalog = [
{ key: 'core', permissions: [{ key: 'core.staff.manage', roles: ['owner'] }, { key: 'core.system.admin', roles: [] }] },
{ key: 'kds', permissions: [{ key: 'kds.access', roles: ['chef'] }] },
{ key: 'tabs', permissions: [{ key: 'tabs.manage', roles: ['owner'] }] },
]
catalog.unshift({ key: 'chat', permissions: [{ key: 'chat.use', roles: ['waiter'] }] })
const modules = [mod('chat', { effective: false }), mod('core'), mod('kds'), mod('tabs', { entitled: false, effective: false })]
const g = editorGroups(catalog, modules)
assert.deepEqual(g.map(x => [x.key, x.on, x.permissions.map(p => p.key)]), [['core', true, ['core.staff.manage']], ['kds', true, ['kds.access']], ['chat', false, ['chat.use']]])
assert.deepEqual(editorGroups(catalog, modules, { actorIsSuperadmin: true })[0].permissions.map(p => p.key), ['core.staff.manage', 'core.system.admin'])
})
test('giving: only what you hold or what they already had; reset skips the rest', () => {
const original = new Set(['kds.access'])
const mine = new Set(['kds.bump'])
assert.equal(canGive('kds.bump', original, mine), true)
assert.equal(canGive('kds.access', original, mine), true) // not new
assert.equal(canGive('reports.view', original, mine), false)
assert.equal(canGive('reports.view', original, null), true) // superadmin
const r = resetToRole(['kds.access', 'kds.bump', 'reports.view'], original, mine)
assert.deepEqual([...r.keys].sort(), ['kds.access', 'kds.bump'])
assert.deepEqual(r.skipped, ['reports.view'])
assert.deepEqual(diff(new Set(['kds.bump']), original), { added: ['kds.bump'], removed: ['kds.access'] })
assert.equal(differsFromRole(['a', 'b'], ['b', 'a']), false)
assert.equal(differsFromRole(['a'], ['a', 'b']), true)
})
test('approvals and sessions', () => {
const now = Date.parse('2026-11-13T12:00:00Z')
assert.equal(approvalState({ used_at: '2026-11-13T11:59:00Z', expires_at: '2026-11-13T11:59:30Z' }, { now }), 'used')
assert.equal(approvalState({ used_at: null, expires_at: '2026-11-13T11:59:30Z' }, { now }), 'expired')
assert.equal(approvalState({ used_at: null, expires_at: '2026-11-13T12:00:30Z' }, { now }), 'waiting')
assert.deepEqual(approvalTarget('order:12'), { order: 12 })
assert.deepEqual(approvalTarget('DELETE /api/x/3'), { text: 'DELETE /api/x/3' })
assert.equal(approvalTarget(null), null)
const s = { client: 'waiter', current: false, ended_at: null }
assert.equal(canEndSession(s), true)
assert.equal(canEndSession({ ...s, current: true }), false)
assert.equal(canEndSession({ ...s, ended_at: 'x' }), false)
assert.equal(canEndSession({ ...s, client: 'support' }), false)
assert.equal(canEndSession({ ...s, client: 'support' }, { actorIsSuperadmin: true }), true)
})
+97 -1
View File
@@ -43,7 +43,9 @@
"soon": "σύντομα",
"integrations": "Συνδέσεις",
"license": "Άδεια",
"devices": "Συσκευές"
"devices": "Συσκευές",
"sessions": "Συνδεδεμένοι τώρα",
"approvals": "Εγκρίσεις υπευθύνου"
},
"profile": {
"edit": "Επεξεργασία προφίλ",
@@ -187,5 +189,99 @@
"removeBody": "Σταματά αμέσως και δείχνει την οθόνη σύζευξης. Για να ξαναχρησιμοποιηθεί, κάντε ξανά σύζευξη.",
"changeAppBody": "Όποιος είναι συνδεδεμένος σε αυτή αποσυνδέεται.",
"limitReached": "{{label}}: η άδεια επιτρέπει {{max}}. Αφαιρέστε μία ή ζητήστε μεγαλύτερη άδεια."
},
"roles": {
"superadmin": "Superadmin",
"owner": "Ιδιοκτήτης",
"store_manager": "Διαχειριστής καταστήματος",
"staff_manager": "Διαχειριστής προσωπικού",
"chef": "Σεφ",
"assistant_chef": "Βοηθός σεφ",
"barista": "Barista",
"barman": "Barman / Barwoman",
"waiter": "Σερβιτόρος",
"assistant_waiter": "Βοηθός σερβιτόρου",
"custom": "Προσαρμοσμένος"
},
"permissions": {
"column": "Δικαιώματα",
"open": "Δικαιώματα",
"count_one": "{{count}} δικαίωμα",
"count_other": "{{count}} δικαιώματα",
"all": "Όλα τα δικαιώματα",
"custom": "Αλλαγμένα από τον ρόλο",
"title": "Δικαιώματα: {{name}}",
"subtitle": "Ρόλος: {{role}}. Οι αλλαγές ισχύουν από την επόμενη ενέργειά του.",
"superadmin": "Ο superadmin έχει πάντα όλα τα δικαιώματα. Δεν υπάρχει κάτι να αλλάξει εδώ.",
"moduleOff": "Απενεργοποιημένο",
"notYours": "Δεν έχετε αυτό το δικαίωμα, οπότε δεν μπορείτε να το δώσετε",
"roleHas": "Ο ρόλος το έχει",
"roleHasNot": "Δεν ανήκει στον ρόλο",
"overridable": "Χωρίς αυτό το δικαίωμα, ένας υπεύθυνος μπορεί να το επιτρέψει μία φορά βάζοντας το PIN του στην ίδια οθόνη.",
"reset": "Επαναφορά στα δικαιώματα του ρόλου",
"resetDone": "Ορίστηκαν τα δικαιώματα του ρόλου. Πατήστε Αποθήκευση για να μείνουν.",
"resetSkipped": "Ορίστηκαν τα δικαιώματα του ρόλου, εκτός από όσα δεν μπορείτε να δώσετε: {{list}}. Πατήστε Αποθήκευση για να μείνουν.",
"save": "Αποθήκευση",
"saveCount_one": "Αποθήκευση {{count}} αλλαγής",
"saveCount_other": "Αποθήκευση {{count}} αλλαγών",
"saved": "Τα δικαιώματα του/της {{name}} αποθηκεύτηκαν",
"cannotGrant": "Μπορείτε να δώσετε μόνο δικαιώματα που έχετε κι εσείς: «{{label}}»."
},
"sessions": {
"intro": "Όσοι είναι συνδεδεμένοι αυτή τη στιγμή, και πού. Ο τερματισμός μιας σύνδεσης αποσυνδέει αμέσως το άτομο· μπορεί να συνδεθεί ξανά.",
"empty": "Δεν είναι κανείς συνδεδεμένος",
"columns": {
"person": "Άτομο",
"where": "Πού",
"since": "Σύνδεση",
"active": "Τελευταία δραστηριότητα",
"ended": "Τέλος",
"actions": ""
},
"client": {
"manager": "Διαχείριση",
"waiter": "Εφαρμογή σερβιτόρων",
"terminal": "Συσκευή",
"support": "Πρόσβαση υποστήριξης",
"supportUntil": "Πρόσβαση υποστήριξης, έως {{time}}"
},
"support": "Υποστήριξη Xenia",
"unknownDevice": "Συσκευή που αφαιρέθηκε",
"you": "Εσείς, εδώ",
"end": "Τερματισμός σύνδεσης",
"endTitle": "Τερματισμός της σύνδεσης: {{name}};",
"endBody": "Αποσυνδέεται αμέσως ({{where}}) και πρέπει να συνδεθεί ξανά.",
"ended": "{{name}}: αποσυνδέθηκε",
"showEnded": "Εμφάνιση συνδέσεων που έληξαν",
"reason": {
"logout": "αποσυνδέθηκε",
"replaced": "συνδέθηκε αλλού",
"ended_by_manager": "από υπεύθυνο",
"user_blocked": "ο λογαριασμός μπλοκαρίστηκε",
"refreshed": "ανανεώθηκε",
"device_revoked": "η συσκευή αφαιρέθηκε",
"device_reassigned": "η συσκευή άλλαξε εφαρμογή",
"expired": "έληξε ο χρόνος",
"unlock_failed": "λάθος PIN στην οθόνη κλειδώματος"
}
},
"approvals": {
"intro": "Κάθε φορά που ένας υπεύθυνος έβαλε το PIN του για να επιτρέψει μία ενέργεια σε κάποιον που δεν έχει το δικαίωμα. Μια έγκριση ισχύει μία φορά, μέσα σε ένα λεπτό.",
"empty": "Δεν υπάρχουν εγκρίσεις ακόμα",
"emptyBody": "Όταν ένας σερβιτόρος χρειάζεται υπεύθυνο για μια ενέργεια, π.χ. ακύρωση είδους που έχει σταλεί, η έγκριση εμφανίζεται εδώ.",
"columns": {
"when": "Πότε",
"action": "Ενέργεια",
"askedBy": "Ζήτησε",
"approvedBy": "Ενέκρινε",
"where": "Συσκευή",
"result": "Αποτέλεσμα"
},
"state": {
"used": "Χρησιμοποιήθηκε",
"expired": "Δεν χρησιμοποιήθηκε",
"waiting": "Σε αναμονή"
},
"order": "Παραγγελία #{{id}}"
}
}
+128 -18
View File
@@ -1,35 +1,82 @@
{
"caller_id": {
"name": "Αναγνώριση κλήσης",
"description": "Εισερχόμενες κλήσεις από το τηλεφωνικό κέντρο του καταστήματος (Grandstream UCM)."
"description": "Εισερχόμενες κλήσεις από το τηλεφωνικό κέντρο του καταστήματος (Grandstream UCM).",
"permissions": {
"use": "Προβολή εισερχόμενων κλήσεων"
}
},
"catalog": {
"name": "Κατάλογος",
"description": "Προϊόντα, κατηγορίες, επιλογές, τραπέζια και ζώνες ετοιμασίας."
"description": "Προϊόντα, κατηγορίες, επιλογές, τραπέζια και ζώνες ετοιμασίας.",
"permissions": {
"menu": {
"manage": "Επεξεργασία προϊόντων, κατηγοριών και σημείων παρασκευής"
},
"tables": {
"manage": "Επεξεργασία τραπεζιών και ομάδων τραπεζιών"
}
}
},
"chat": {
"name": "Συνομιλία προσωπικού",
"description": "Συνομιλία του προσωπικού και μηνύματα του υπευθύνου προς το προσωπικό."
"description": "Συνομιλία του προσωπικού και μηνύματα του υπευθύνου προς το προσωπικό.",
"permissions": {
"use": "Χρήση της συνομιλίας προσωπικού",
"broadcast": "Αποστολή μηνυμάτων σε όλο το προσωπικό"
}
},
"connect_menu": {
"name": "QR μενού",
"description": "Το online μενού με QR, συγχρονισμένο με τον κατάλογο."
"description": "Το online μενού με QR, συγχρονισμένο με τον κατάλογο.",
"permissions": {
"manage": "Διαχείριση του QR μενού"
}
},
"connect_orders": {
"name": "Online παραγγελίες",
"description": "Παραγγελίες από το QR μενού, που έρχονται από το cloud."
"description": "Παραγγελίες από το QR μενού, που έρχονται από το cloud.",
"permissions": {
"manage": "Αποδοχή και διαχείριση online παραγγελιών"
}
},
"connect_remote": {
"name": "Απομακρυσμένη διαχείριση",
"description": "Ζωντανά στοιχεία για την εφαρμογή απομακρυσμένης διαχείρισης του ιδιοκτήτη."
"description": "Ζωντανά στοιχεία για την εφαρμογή απομακρυσμένης διαχείρισης του ιδιοκτήτη.",
"permissions": {
"manage": "Ρύθμιση της εφαρμογής απομακρυσμένης διαχείρισης"
}
},
"core": {
"name": "Βασικό σύστημα",
"description": "Σύνδεση, προσωπικό, ρυθμίσεις, άδεια, σύστημα και ζωντανές ενημερώσεις. Πάντα ενεργό."
"description": "Σύνδεση, προσωπικό, ρυθμίσεις, άδεια, σύστημα και ζωντανές ενημερώσεις. Πάντα ενεργό.",
"permissions": {
"dashboard": {
"access": "Είσοδος στη διαχείριση"
},
"staff": {
"manage": "Προσθήκη και επεξεργασία προσωπικού, προβολή συνδεδεμένων"
},
"settings": {
"manage": "Αλλαγή ρυθμίσεων καταστήματος"
},
"modules": {
"manage": "Ενεργοποίηση και απενεργοποίηση εφαρμογών, λειτουργιών και συνδέσεων"
},
"devices": {
"manage": "Σύζευξη, μετονομασία, αλλαγή εφαρμογής και αφαίρεση συσκευών"
},
"system": {
"admin": "Συντήρηση μόνο από την υποστήριξη"
}
}
},
"crm": {
"name": "Πελάτες",
"description": "Αρχείο πελατών."
"description": "Αρχείο πελατών.",
"permissions": {
"manage": "Προσθήκη και επεξεργασία πελατών"
}
},
"customer_display": {
"name": "Οθόνη πελάτη",
@@ -40,28 +87,44 @@
},
"expenses": {
"name": "Έξοδα",
"description": "Έξοδα, πληρωμές και βιβλίο προμηθευτών."
"description": "Έξοδα, πληρωμές και βιβλίο προμηθευτών.",
"permissions": {
"manage": "Καταχώριση εξόδων και προμηθευτών"
}
},
"fiscal": {
"name": "Φορολογικός μηχανισμός",
"description": "Αποστολή αποδείξεων στον φορολογικό μηχανισμό (ΦΗΜ) μέσω του φακέλου γέφυρας."
"description": "Αποστολή αποδείξεων στον φορολογικό μηχανισμό (ΦΗΜ) μέσω του φακέλου γέφυρας.",
"permissions": {
"manage": "Ρύθμιση του φορολογικού μηχανισμού"
}
},
"history": {
"name": "Ιστορικό παραγγελιών",
"description": "Παλιές παραγγελίες και σύνοψη εργάσιμων ημερών (μόνο προβολή). Δωρεάν, με σύντομο ιστορικό.",
"limits": {
"history_days": "Ημέρες ιστορικού για προβολή"
},
"permissions": {
"view": "Προβολή παλιών παραγγελιών και συνόψεων ημέρας"
}
},
"inventory": {
"name": "Αποθήκη",
"description": "Καταγραφή απορριμμάτων και κόστος προϊόντων."
"description": "Καταγραφή απορριμμάτων και κόστος προϊόντων.",
"permissions": {
"manage": "Καταγραφή φθορών και κόστους"
}
},
"kds": {
"name": "Οθόνη κουζίνας",
"description": "Οθόνες στην κουζίνα ή στο μπαρ με τις παραγγελίες προς ετοιμασία.",
"limits": {
"devices": "Οθόνες κουζίνας"
},
"permissions": {
"access": "Χρήση της οθόνης κουζίνας",
"bump": "Σήμανση πιάτων ως έτοιμων"
}
},
"menu_tablet": {
@@ -69,55 +132,102 @@
"description": "Κατάλογος αυτοεξυπηρέτησης σε tablet (έρχεται σύντομα).",
"limits": {
"devices": "Tablet μενού"
},
"permissions": {
"manage": "Ρύθμιση των tablet μενού"
}
},
"notes": {
"name": "Σημειώσεις",
"description": "Σημειώσεις και εργασίες του καταστήματος."
"description": "Σημειώσεις και εργασίες του καταστήματος.",
"permissions": {
"use": "Ανάγνωση και γραφή σημειώσεων και εκκρεμοτήτων"
}
},
"ordering": {
"name": "Παραγγελίες",
"description": "Παραγγελίες, πληρωμές, εργάσιμη ημέρα, βάρδιες, ταμείο και εκτύπωση κουζίνας."
"description": "Παραγγελίες, πληρωμές, εργάσιμη ημέρα, βάρδιες, ταμείο και εκτύπωση κουζίνας.",
"permissions": {
"orders": {
"open": "Άνοιγμα παραγγελιών και προσθήκη ειδών",
"close": "Είσπραξη και κλείσιμο παραγγελιών",
"cancel": "Ακύρωση ειδών που έχουν σταλεί"
},
"prices": {
"modify": "Αλλαγή τιμής είδους"
},
"business_day": {
"manage": "Άνοιγμα και κλείσιμο της εργάσιμης ημέρας"
}
}
},
"pos_counter": {
"name": "Ταμείο πάγκου",
"description": "Τερματικό στον πάγκο για γρήγορες παραγγελίες (έρχεται σύντομα).",
"limits": {
"devices": "Τερματικά πάγκου"
},
"permissions": {
"access": "Χρήση του ταμείου πάγκου"
}
},
"pricing": {
"name": "Τιμολόγηση",
"description": "Ομάδες τιμών, happy hour, τροποποιητές, προσφορές και εκπτώσεις σερβιτόρων."
"description": "Ομάδες τιμών, happy hour, τροποποιητές, προσφορές και εκπτώσεις σερβιτόρων.",
"permissions": {
"manage": "Ρύθμιση ομάδων τιμών, τροποποιητών και προσφορών",
"discounts": {
"apply": "Εκπτώσεις",
"over_limit": "Εκπτώσεις πάνω από τα όρια ανά σερβιτόρο"
}
}
},
"reports": {
"name": "Αναφορές",
"description": "Πλήρεις αναφορές πωλήσεων, προϊόντων, προσωπικού και εκτυπωτών, εξαγωγή CSV και εκτυπωμένες αναφορές.",
"limits": {
"history_days": "Ημέρες που καλύπτουν οι αναφορές"
},
"permissions": {
"view": "Προβολή αναφορών"
}
},
"reservations": {
"name": "Κρατήσεις",
"description": "Κρατήσεις τραπεζιών."
"description": "Κρατήσεις τραπεζιών.",
"permissions": {
"manage": "Προσθήκη και επεξεργασία κρατήσεων"
}
},
"signage": {
"name": "Ψηφιακή σήμανση",
"description": "Μενού και προσφορές σε τηλεοράσεις (έρχεται σύντομα).",
"limits": {
"devices": "Οθόνες σήμανσης"
},
"permissions": {
"manage": "Επεξεργασία περιεχομένου σήμανσης"
}
},
"staff_planning": {
"name": "Προγραμματισμός προσωπικού",
"description": "Πρόγραμμα βαρδιών και μισθοδοσία."
"description": "Πρόγραμμα βαρδιών και μισθοδοσία.",
"permissions": {
"manage": "Προγραμματισμός βαρδιών και προβολή μισθοδοσίας"
}
},
"tabs": {
"name": "Καρτέλες",
"description": "Καρτέλες πληρωμής αργότερα για τακτικούς πελάτες."
"description": "Καρτέλες πληρωμής αργότερα για τακτικούς πελάτες.",
"permissions": {
"manage": "Άνοιγμα, χρέωση και εξόφληση λογαριασμών"
}
},
"waiter_app": {
"name": "Εφαρμογή σερβιτόρων",
"description": "Λήψη παραγγελιών από τα κινητά των σερβιτόρων (web και εφαρμογή Android)."
"description": "Λήψη παραγγελιών από τα κινητά των σερβιτόρων (web και εφαρμογή Android).",
"permissions": {
"access": "Σύνδεση στην εφαρμογή σερβιτόρων"
}
}
}
+97 -1
View File
@@ -43,7 +43,9 @@
"soon": "soon",
"integrations": "Integrations",
"license": "License",
"devices": "Devices"
"devices": "Devices",
"sessions": "Signed in now",
"approvals": "Manager approvals"
},
"profile": {
"edit": "Edit profile",
@@ -187,5 +189,99 @@
"removeBody": "It stops at once and shows the pairing screen. To use it again, pair it again.",
"changeAppBody": "Whoever is signed in on it is signed out.",
"limitReached": "{{label}}: the license allows {{max}}. Remove one or ask for a bigger license."
},
"roles": {
"superadmin": "Superadmin",
"owner": "Owner",
"store_manager": "Store manager",
"staff_manager": "Staff manager",
"chef": "Chef",
"assistant_chef": "Assistant chef",
"barista": "Barista",
"barman": "Bartender",
"waiter": "Waiter",
"assistant_waiter": "Assistant waiter",
"custom": "Custom"
},
"permissions": {
"column": "Permissions",
"open": "Permissions",
"count_one": "{{count}} permission",
"count_other": "{{count}} permissions",
"all": "All permissions",
"custom": "Changed from role",
"title": "Permissions: {{name}}",
"subtitle": "Role: {{role}}. Changes apply from their next action.",
"superadmin": "The superadmin always has every permission. There is nothing to change here.",
"moduleOff": "Turned off",
"notYours": "You don't have this permission yourself, so you can't give it",
"roleHas": "The role has this",
"roleHasNot": "Not part of the role",
"overridable": "Without this permission, a manager can still allow it once by typing their PIN on the same screen.",
"reset": "Reset to role defaults",
"resetDone": "Set to the role's defaults. Save to keep it.",
"resetSkipped": "Set to the role's defaults, except what you can't give: {{list}}. Save to keep it.",
"save": "Save",
"saveCount_one": "Save {{count}} change",
"saveCount_other": "Save {{count}} changes",
"saved": "Permissions of {{name}} saved",
"cannotGrant": "You can only give permissions you have yourself: \"{{label}}\"."
},
"sessions": {
"intro": "Everyone signed in right now, and where. Ending a session signs that person out at once; they can sign in again.",
"empty": "Nobody is signed in",
"columns": {
"person": "Person",
"where": "Where",
"since": "Signed in",
"active": "Last active",
"ended": "Ended",
"actions": ""
},
"client": {
"manager": "Manager dashboard",
"waiter": "Waiter app",
"terminal": "Device",
"support": "Support access",
"supportUntil": "Support access, until {{time}}"
},
"support": "Xenia support",
"unknownDevice": "Removed device",
"you": "You, here",
"end": "End session",
"endTitle": "End the session of {{name}}?",
"endBody": "They are signed out at once ({{where}}) and have to sign in again.",
"ended": "{{name}} was signed out",
"showEnded": "Show ended sessions",
"reason": {
"logout": "signed out",
"replaced": "signed in elsewhere",
"ended_by_manager": "ended by a manager",
"user_blocked": "account blocked",
"refreshed": "renewed",
"device_revoked": "device removed",
"device_reassigned": "device changed app",
"expired": "time ran out",
"unlock_failed": "wrong PIN on the lock screen"
}
},
"approvals": {
"intro": "Every time a manager typed their PIN to allow one action for someone who doesn't have the permission. An approval works once, within a minute.",
"empty": "No approvals yet",
"emptyBody": "When a waiter needs a manager for an action, e.g. cancelling an item already sent, the manager's approval shows here.",
"columns": {
"when": "When",
"action": "Action",
"askedBy": "Asked by",
"approvedBy": "Approved by",
"where": "Device",
"result": "Result"
},
"state": {
"used": "Used",
"expired": "Not used",
"waiting": "Waiting"
},
"order": "Order #{{id}}"
}
}
+128 -18
View File
@@ -1,35 +1,82 @@
{
"caller_id": {
"name": "Caller ID",
"description": "Incoming phone calls from the venue's phone system (Grandstream UCM)."
"description": "Incoming phone calls from the venue's phone system (Grandstream UCM).",
"permissions": {
"use": "See incoming calls"
}
},
"catalog": {
"name": "Catalogue",
"description": "Products, categories, options, tables and prep zones."
"description": "Products, categories, options, tables and prep zones.",
"permissions": {
"menu": {
"manage": "Edit products, categories and prep zones"
},
"tables": {
"manage": "Edit tables and table groups"
}
}
},
"chat": {
"name": "Staff chat",
"description": "Staff chat and manager messages to staff."
"description": "Staff chat and manager messages to staff.",
"permissions": {
"use": "Use staff chat",
"broadcast": "Send messages to all staff"
}
},
"connect_menu": {
"name": "QR menu",
"description": "The online QR menu, kept in sync with the catalogue."
"description": "The online QR menu, kept in sync with the catalogue.",
"permissions": {
"manage": "Manage the QR menu"
}
},
"connect_orders": {
"name": "Online orders",
"description": "Orders placed from the QR menu, brought in from the cloud."
"description": "Orders placed from the QR menu, brought in from the cloud.",
"permissions": {
"manage": "Accept and manage online orders"
}
},
"connect_remote": {
"name": "Remote manager",
"description": "Live figures for the owner's remote manager app."
"description": "Live figures for the owner's remote manager app.",
"permissions": {
"manage": "Set up the remote manager app"
}
},
"core": {
"name": "Core",
"description": "Sign-in, staff, settings, license, system and live updates. Always on."
"description": "Sign-in, staff, settings, license, system and live updates. Always on.",
"permissions": {
"dashboard": {
"access": "Open the manager dashboard"
},
"staff": {
"manage": "Add and edit staff, see who is signed in"
},
"settings": {
"manage": "Change venue settings"
},
"modules": {
"manage": "Turn apps, features and integrations on or off"
},
"devices": {
"manage": "Pair, rename, reassign and remove devices"
},
"system": {
"admin": "Support-only maintenance"
}
}
},
"crm": {
"name": "Customers",
"description": "Customer records."
"description": "Customer records.",
"permissions": {
"manage": "Add and edit customers"
}
},
"customer_display": {
"name": "Customer display",
@@ -40,28 +87,44 @@
},
"expenses": {
"name": "Expenses",
"description": "Expenses, payments and the supplier book."
"description": "Expenses, payments and the supplier book.",
"permissions": {
"manage": "Record expenses and suppliers"
}
},
"fiscal": {
"name": "Fiscal device",
"description": "Sends receipts to the fiscal device (ΦΗΜ) through its folder bridge."
"description": "Sends receipts to the fiscal device (ΦΗΜ) through its folder bridge.",
"permissions": {
"manage": "Set up the fiscal device"
}
},
"history": {
"name": "Order history",
"description": "Past orders and business-day summaries (read only). Free, with a short history.",
"limits": {
"history_days": "Days of history you can view"
},
"permissions": {
"view": "See past orders and day summaries"
}
},
"inventory": {
"name": "Inventory",
"description": "Waste log and product costs."
"description": "Waste log and product costs.",
"permissions": {
"manage": "Log waste and costs"
}
},
"kds": {
"name": "Kitchen display",
"description": "Screens in the kitchen or bar showing the orders to prepare.",
"limits": {
"devices": "Kitchen screens"
},
"permissions": {
"access": "Use the kitchen display",
"bump": "Mark items ready"
}
},
"menu_tablet": {
@@ -69,55 +132,102 @@
"description": "A self-service catalogue on a tablet (coming soon).",
"limits": {
"devices": "Menu tablets"
},
"permissions": {
"manage": "Set up menu tablets"
}
},
"notes": {
"name": "Notes",
"description": "Venue notes and to-dos."
"description": "Venue notes and to-dos.",
"permissions": {
"use": "Read and write notes and to-dos"
}
},
"ordering": {
"name": "Ordering",
"description": "Orders, payments, business day, shifts, cash and kitchen printing."
"description": "Orders, payments, business day, shifts, cash and kitchen printing.",
"permissions": {
"orders": {
"open": "Open orders and add items",
"close": "Take payments and close orders",
"cancel": "Cancel items already sent"
},
"prices": {
"modify": "Change an item's price"
},
"business_day": {
"manage": "Open and close the business day"
}
}
},
"pos_counter": {
"name": "Counter POS",
"description": "A counter terminal for quick orders (coming soon).",
"limits": {
"devices": "Counter terminals"
},
"permissions": {
"access": "Use the counter POS"
}
},
"pricing": {
"name": "Pricing",
"description": "Price groups, happy hours, modifiers, deals and waiter discounts."
"description": "Price groups, happy hours, modifiers, deals and waiter discounts.",
"permissions": {
"manage": "Set up price groups, modifiers and deals",
"discounts": {
"apply": "Give discounts",
"over_limit": "Give discounts beyond the per-waiter limits"
}
}
},
"reports": {
"name": "Reports",
"description": "Full sales, product, staff and printer reports, CSV export and printed reports.",
"limits": {
"history_days": "Days of history reports can cover"
},
"permissions": {
"view": "See reports"
}
},
"reservations": {
"name": "Reservations",
"description": "Table reservations."
"description": "Table reservations.",
"permissions": {
"manage": "Add and edit reservations"
}
},
"signage": {
"name": "Digital signage",
"description": "Menus and promotions on TVs (coming soon).",
"limits": {
"devices": "Signage screens"
},
"permissions": {
"manage": "Edit signage content"
}
},
"staff_planning": {
"name": "Staff planning",
"description": "Shift schedule and payroll."
"description": "Shift schedule and payroll.",
"permissions": {
"manage": "Plan shifts and see payroll"
}
},
"tabs": {
"name": "Tabs",
"description": "Pay-later tabs for regular customers."
"description": "Pay-later tabs for regular customers.",
"permissions": {
"manage": "Open, charge and settle tabs"
}
},
"waiter_app": {
"name": "Waiter app",
"description": "Order taking on the waiters' phones (web and Android app)."
"description": "Order taking on the waiters' phones (web and Android app).",
"permissions": {
"access": "Sign in to the waiter app"
}
}
}
+1 -1
View File
@@ -41,7 +41,7 @@ Or run one suite at a time:
| `node install.mjs` | `install.sh`: VPN-safe `HOST_IP` detection (simulated WireGuard/WiFi hosts); fresh install, upgrade, re-run; proxy config identical to `nginx-proxy/nginx.conf` | Docker | ~1 min |
| `python license_e2e.py` | Offline licensing with a real cloud + site process: 400 days offline, tampered file, clock set back, expiry deferred to workday close, renewal, remote lock | Python deps of both backends | ~2 min |
| `node ui.mjs` | `@xenia/ui` components on the dev-only gallery (`/ui-gallery`, manager Vite :5185): dialog focus/Escape/backdrop, sheet, toasts, field wiring, switch, InfoTip, PinPad, themes; `@xenia/i18n` on `/i18n-sample` with the browser in New York: venue time, live language switch, el/en money and numbers, price input, translated component labels | Edge | ~40 s |
| `node manager.mjs` | Manager on `@xenia/api`/`@xenia/access` (backend :8057 on a demo DB, manager Vite :5186): bootstrap before/after login, wrong password and wrong lock PIN stay on screen, sidebar from keys, KDS module off → "turned off" screen, session ended elsewhere → /login, a waiter's cancel approved by a manager PIN (wrong PIN first) and audited | 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) | 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 |
+91
View File
@@ -339,6 +339,97 @@ try {
r.check('the approval is audited', audit[0]?.key === 'ordering.orders.cancel' && audit[0]?.target === `order:${order.id}` && !!audit[0]?.used_at, JSON.stringify(audit[0]))
await w.screenshot({ path: path.join(OUT, 'manager-after-approval.png') })
// ── 2.6e: approvals log, who is signed in, staff permissions ───────────────
await uiLogin(page, 'password')
await page.waitForURL(u => u.pathname === '/dashboard', { timeout: 15_000 }).catch(() => {})
const staffList = await api('GET', '/api/waiters/', { token: boss })
const maria = staffList.find(u => u.username === 'demo_maria')
await page.goto(`${APP}/management/approvals`)
const approval = page.locator(`[data-testid="approval-${audit[0].id}"]`)
await approval.waitFor({ timeout: 10_000 }).catch(() => {})
const approvalText = await approval.textContent().catch(() => '')
r.check('approvals: the cancel is listed: action, who asked, who approved, used on the order',
await approval.getAttribute('data-state').catch(() => '') === 'used' && approvalText.includes('Cancel items already sent') &&
approvalText.includes(maria.full_name) && approvalText.includes(`Order #${order.id}`), approvalText)
await page.goto(`${APP}/management/sessions`)
await page.getByTestId('sessions-table').waitFor({ timeout: 10_000 }).catch(() => {})
const mariaRow = page.locator(`[data-user="${maria.id}"][data-client="waiter"][data-ended="false"]`)
r.check('sessions: the waiter is listed (Waiter app) and my own row is "You, here" with no end button',
await mariaRow.count() >= 1 && (await mariaRow.first().textContent()).includes('Waiter app') &&
await page.locator('tr', { hasText: 'You, here' }).getByRole('button', { name: 'End session' }).count() === 0)
await mariaRow.first().getByRole('button', { name: 'End session' }).click()
await page.getByRole('dialog').getByRole('button', { name: 'End session' }).click()
await page.waitForFunction(id => !document.querySelector(`[data-user="${id}"][data-client="waiter"][data-ended="false"]`), maria.id, { timeout: 8000 }).catch(() => {})
const mariaMe = await fetch(`${backend.url}/api/auth/me`, { headers: { authorization: `Bearer ${waiter}` } })
r.check('sessions: "End session" → gone from the list, the waiter\'s next call is refused',
await mariaRow.count() === 0 && mariaMe.status === 401 && (await mariaMe.json()).error.code === 'auth.session_ended')
await page.getByLabel('Show ended sessions').check()
await page.waitForFunction(id => document.querySelector(`[data-user="${id}"][data-ended="true"]`), maria.id, { timeout: 8000 }).catch(() => {})
r.check('sessions: "show ended" lists it as ended by a manager',
(await page.locator(`[data-user="${maria.id}"][data-ended="true"]`).first().textContent().catch(() => '')).includes('ended by a manager'))
await page.screenshot({ path: path.join(OUT, 'manager-sessions.png'), fullPage: true })
// the permission editor: give one key, see it differ from the role, reset
const mariaPerms = () => api('GET', `/api/waiters/${maria.id}/permissions`, { token: boss })
const before = await mariaPerms()
await page.goto(`${APP}/management/staff`)
const permCell = page.getByTestId(`staff-perms-${maria.id}`)
await permCell.waitFor({ timeout: 10_000 })
r.check('staff: a Permissions column with the count instead of 13 tick columns',
(await permCell.textContent()).includes(`${before.keys.length} permissions`) && await page.getByText('Ακύρωση', { exact: true }).count() === 0)
await permCell.getByRole('button').click()
const editor = page.getByTestId('perm-editor')
await editor.waitFor({ timeout: 10_000 })
const cancelRow = page.getByTestId('perm-ordering.orders.cancel')
r.check('editor: grouped by module (Ordering, Kitchen display, Core…), cancel is off for a waiter',
await page.getByTestId('perm-group-ordering').count() === 1 && await page.getByTestId('perm-group-core').count() === 1 &&
await cancelRow.getAttribute('data-on') === 'false' && (await cancelRow.textContent()).includes('Cancel items already sent'))
await cancelRow.getByRole('switch').click()
await page.getByRole('button', { name: 'Save 1 change' }).click()
await editor.waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
const afterGive = await mariaPerms()
await page.waitForFunction(id => document.querySelector(`[data-testid="staff-perms-${id}"]`)?.textContent.includes('Changed from role'), maria.id, { timeout: 8000 }).catch(() => {})
r.check('editor: saved → the waiter has the key, the row says "Changed from role"',
afterGive.keys.includes('ordering.orders.cancel') && (await permCell.textContent()).includes('Changed from role'), JSON.stringify(afterGive.keys))
await page.screenshot({ path: path.join(OUT, 'manager-staff.png'), fullPage: true })
await permCell.getByRole('button').click()
await editor.waitFor({ timeout: 10_000 })
await page.screenshot({ path: path.join(OUT, 'manager-permissions.png') })
await page.getByTestId('perm-reset').click()
await page.screenshot({ path: path.join(OUT, 'manager-permissions-reset.png') })
r.check('editor: reset → the draft is the role\'s defaults (cancel off again), saying so',
await cancelRow.getAttribute('data-on') === 'false' && await page.getByTestId('perm-note').count() === 1)
await page.getByRole('button', { name: /^Save \d+ change/ }).click()
await editor.waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
const afterReset = await mariaPerms()
r.check('editor: reset saved → keys = the role template',
JSON.stringify(afterReset.keys) === JSON.stringify(afterReset.role_template), JSON.stringify(afterReset.keys))
// a staff manager can't give what they don't have (disabled), and the backend's refusal is explained
const sm = await api('POST', '/api/waiters/', { token: boss, body: { username: 'e2e_staffmgr', full_name: 'Stella Staff', pin: '5151', role: 'staff_manager', is_active: true } })
const smToken = await loginApi('e2e_staffmgr', { pin: '5151' })
const s2 = await (await browser.newContext({ viewport: { width: 1400, height: 900 } })).newPage()
s2.on('pageerror', e => errors.push(e.message))
await s2.goto(`${APP}/login`)
await s2.evaluate(t => { localStorage.setItem('manager_token', t); localStorage.setItem('manager_username', 'e2e_staffmgr') }, smToken)
await s2.goto(`${APP}/management/staff`)
await s2.getByTestId(`staff-perms-${maria.id}`).getByRole('button').click()
await s2.getByTestId('perm-editor').waitFor({ timeout: 10_000 })
const smCancel = s2.getByTestId('perm-ordering.orders.cancel')
r.check('staff manager: "cancel" is disabled with the reason (they don\'t have it)',
await smCancel.getByRole('switch').isDisabled() && (await smCancel.textContent()).includes("You don't have this permission yourself"))
// they had "See reports" when the editor opened; the owner takes it away before they save
const smKeys = (await api('GET', `/api/waiters/${sm.id}/permissions`, { token: boss })).keys
await api('PUT', `/api/waiters/${sm.id}/permissions`, { token: boss, body: { keys: smKeys.filter(k => k !== 'reports.view') } })
await s2.getByTestId('perm-reports.view').getByRole('switch').click()
await s2.getByRole('button', { name: 'Save 1 change' }).click()
await s2.getByTestId('perm-error').waitFor({ timeout: 8000 }).catch(() => {})
r.check('staff manager: the backend refuses (access.cannot_grant), named by its label',
(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'))
r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | '))
} finally {
await browser.close()