Compare commits
10
Commits
0d0b2d78e1
...
034426f870
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
034426f870 | ||
|
|
f1f20f7bba | ||
|
|
cc4e76019b | ||
|
|
e9b6ef57e0 | ||
|
|
7cbd0325a4 | ||
|
|
eb22997f8e | ||
|
|
2426ffddad | ||
|
|
92bc1b0113 | ||
|
|
cc00ec39c7 | ||
|
|
1f28016122 |
@@ -1,4 +0,0 @@
|
|||||||
# vite-plugin-pwa 1.2 (waiter) does not list Vite 8 as a peer yet; the waiter always
|
|
||||||
# installed with --legacy-peer-deps. One setting for the whole workspace so local
|
|
||||||
# installs, npm ci in the Dockerfiles and the e2e builds resolve the same way.
|
|
||||||
legacy-peer-deps=true
|
|
||||||
+7
-6
@@ -84,7 +84,7 @@ Prices, costs and discounts are copied onto order items and logs when the action
|
|||||||
The plain-HTTP servers (80 default_server, 8081) must keep their LAN-only `allow`/`deny` block.
|
The plain-HTTP servers (80 default_server, 8081) must keep their LAN-only `allow`/`deny` block.
|
||||||
|
|
||||||
**CS-6. Permissions are checked on the backend.**
|
**CS-6. Permissions are checked on the backend.**
|
||||||
Hiding a button in the UI is not access control. Every new endpoint declares its role or `perm_*` requirement through `routers/deps.py`.
|
Hiding a button in the UI is not access control. Every new endpoint declares its access with a marker from `core/access/deps.py` (see CS-14).
|
||||||
|
|
||||||
**CS-8. The waiter app never assumes it's served by the backend.**
|
**CS-8. The waiter app never assumes it's served by the backend.**
|
||||||
The same waiter build runs same-origin (https domain, or plain `http://<LAN IP>`) **and** inside the native app talking to a remote venue server. So in `waiter_pwa`:
|
The same waiter build runs same-origin (https domain, or plain `http://<LAN IP>`) **and** inside the native app talking to a remote venue server. So in `waiter_pwa`:
|
||||||
@@ -131,6 +131,7 @@ npm run apk:release # releases/xenia-waiter-<ver>.apk, signed, AND copied to p
|
|||||||
- **Native specifics:**
|
- **Native specifics:**
|
||||||
- `androidScheme: http` (origin `http://localhost`)
|
- `androidScheme: http` (origin `http://localhost`)
|
||||||
- cleartext allowed via `network_security_config.xml`
|
- cleartext allowed via `network_security_config.xml`
|
||||||
|
- the updater may download bundles over plain HTTP (`httpsOnly: false` in `capacitor.config.json`; capacitor-updater 8.54 refuses http by default). Venues have no domains, and each zip is checked against the manifest's sha256
|
||||||
- no service worker (`vite build --mode native` → `dist-native/`)
|
- no service worker (`vite build --mode native` → `dist-native/`)
|
||||||
- back button handled in `src/native/backButton.js`
|
- back button handled in `src/native/backButton.js`
|
||||||
- first run shows only the pairing screen
|
- first run shows only the pairing screen
|
||||||
@@ -148,7 +149,7 @@ The native plugins (`@capacitor/*`, `@capgo/*`) are pinned to **exact** versions
|
|||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
Automated tests cover the native-app/LAN work and licensing. See **[tests/e2e/README.md](../tests/e2e/README.md)**.
|
Automated tests cover the native-app/LAN work and licensing. See **[tests/e2e/README.md](../tests/e2e/README.md)**.
|
||||||
- **Unit (seconds):** `python -m pytest tests -q` in `local_backend/`, `npm test` in `waiter_pwa/`, and `npm test -w @xenia/<ui|i18n|api|access>` at the workspace root.
|
- **Unit (seconds):** `python -m pytest tests -q` in `local_backend/`, `npm test` in `waiter_pwa/`, and `npm test -w <@xenia/ui|@xenia/i18n|@xenia/api|@xenia/access|manager-dashboard>` at the workspace root.
|
||||||
- **End-to-end:** `node run-all.mjs` in `tests/e2e/`. That covers install.sh, licensing with a real cloud, browser modes, and the Android emulator suites. `--no-android` skips the emulator.
|
- **End-to-end:** `node run-all.mjs` in `tests/e2e/`. That covers install.sh, licensing with a real cloud, browser modes, and the Android emulator suites. `--no-android` skips the emulator.
|
||||||
|
|
||||||
**CS-11. Tests follow the code.** When you change something a test covers (licensing, LAN IP, TLS, pairing, rediscovery, bundles, install.sh, the proxy config), run its suite and update the test in the same commit. Run `node run-all.mjs` before every release.
|
**CS-11. Tests follow the code.** When you change something a test covers (licensing, LAN IP, TLS, pairing, rediscovery, bundles, install.sh, the proxy config), run its suite and update the test in the same commit. Run `node run-all.mjs` before every release.
|
||||||
@@ -157,10 +158,10 @@ Automated tests cover the native-app/LAN work and licensing. See **[tests/e2e/RE
|
|||||||
New and touched endpoints raise `core.errors.XeniaError("<code>", **params)`; register the code with its status and English message in `CODES`. Responses look like `{"error": {code, params, message}, "detail"}`; plain `HTTPException`s are wrapped as `http.<status>` until converted. Text the backend renders itself (printed tickets and reports, later notifications) goes through `core.i18n.t(key, lang)` with keys in `core/i18n/en.json` + `el.json` (same keys, same placeholders; Greek print text without accents). Kitchen tickets print in the prep zone's language, everything else in `venue.language`.
|
New and touched endpoints raise `core.errors.XeniaError("<code>", **params)`; register the code with its status and English message in `CODES`. Responses look like `{"error": {code, params, message}, "detail"}`; plain `HTTPException`s are wrapped as `http.<status>` until converted. Text the backend renders itself (printed tickets and reports, later notifications) goes through `core.i18n.t(key, lang)` with keys in `core/i18n/en.json` + `el.json` (same keys, same placeholders; Greek print text without accents). Kitchen tickets print in the prep zone's language, everything else in `venue.language`.
|
||||||
|
|
||||||
**CS-13. Every router belongs to a module** (branch `platform-v2`, D-19, §4).
|
**CS-13. Every router belongs to a module** (branch `platform-v2`, D-19, §4).
|
||||||
Routers are mounted from the module manifests (`local_backend/modules/<key>/manifest.py` → `Mount(...)`), not from a list in `main.py`. A new router gets a `Mount` in its module's manifest (or a new module folder); a test fails if any router in `routers/` isn't mounted. New settings are declared as `SettingDef` in the owning manifest (the settings API reads them from there). Background loops that belong to a module are manifest `workers`, started and stopped by the supervisor, never started by hand in `main.py`.
|
Routers are mounted from the module manifests (`local_backend/modules/<key>/manifest.py` → `Mount(...)`), not from a list in `main.py`. A new router gets a `Mount` in its module's manifest (or a new module folder); a test fails if any router in `routers/` isn't mounted. New settings are declared as `SettingDef` in the owning manifest (the settings API reads them from there). Background loops that belong to a module are manifest `workers`, started and stopped by the supervisor, never started by hand in `main.py`. A new module (or a new limit) also needs its staff-facing name, description and limit labels in `packages/i18n/locales/{en,el}/modules.json`; `tests/test_module_texts.py` fails until they exist.
|
||||||
|
|
||||||
**CS-14. Every route declares who may call it** (branch `platform-v2`, D-7, D-17).
|
**CS-14. Every route declares who may call it** (branch `platform-v2`, D-7, D-17).
|
||||||
Use `core.access.deps.require("<module>.<area>.<action>")` (or `require_any`, `public()`, `require_device(app)`), or `Depends(get_current_user)` for "any signed-in user". The guard `tests/guards/test_route_access.py` fails a route with no marker or with an unknown key. New keys are declared as `Perm(...)` in the owning manifest, with their default roles. Inside code use `core.access.check.holds(user, key)` / `can(user, key)`, never role names or `perm_*` attributes (`tests/guards/test_no_perm_reads.py`). The v1 booleans exist only in `core/access/legacy.py` for the current frontends.
|
Use `core.access.deps.require("<module>.<area>.<action>")` (or `require_any`, `public()`, `require_device(app)`), or `Depends(get_current_user)` for "any signed-in user". The guard `tests/guards/test_route_access.py` fails a route with no marker or with an unknown key. New keys are declared as `Perm(...)` in the owning manifest, with their default roles. Inside code use `core.access.check.holds(user, key)` / `can(user, key)`, never role names or `perm_*` attributes (`tests/guards/test_no_perm_reads.py`). The v1 booleans are gone (step 2.99): `UserOut` carries only `permissions` (keys).
|
||||||
Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: <token>`; a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.access`. Device-only endpoints use `require_device("<app>")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header.
|
Paired devices (D-8, `routers/devices.py`, `core/access/context.py`) send `X-Xenia-Device: <token>`; a device may only use keys matching its app's `DeviceApp.scope` (plus `<app>.*`) and only reach routes of those modules. A new device app with user logins must declare `<app>.access`. Device-only endpoints use `require_device("<app>")`; users log in on a device with `POST /api/auth/login {client: "terminal"}`, and that session only works together with the device's header.
|
||||||
Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overridable=True)` and a user without it gets `access.override_possible`; the client gets a manager's one-time token from `POST /api/access/override {key, username, pin}` and retries with `X-Xenia-Override`. `require()` routes handle it in `check()`; an endpoint with its own rule calls `require_override(request, db, key, target="order:12")` where the rule says no, **after** its other checks (a used token is spent).
|
Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overridable=True)` and a user without it gets `access.override_possible`; the client gets a manager's one-time token from `POST /api/access/override {key, username, pin}` and retries with `X-Xenia-Override`. `require()` routes handle it in `check()`; an endpoint with its own rule calls `require_override(request, db, key, target="order:12")` where the rule says no, **after** its other checks (a used token is spent).
|
||||||
|
|
||||||
@@ -168,10 +169,10 @@ 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`.
|
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).
|
**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).
|
**CS-18. Frontends talk to the backend through `@xenia/api` and read access from bootstrap** (branch `platform-v2`, D-7, D-10, §9).
|
||||||
An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. Lock screens never log in again: they call `POST /api/auth/unlock {pin}` with the current session (same token; 5 wrong PINs end the session); manager sign-in sends `client: "manager"` and reads its mode from bootstrap `login`. The app root is `<AccessProvider client token i18n>`: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand).
|
An app makes one client with `createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized })` (its own axios; the waiter passes `baseURL: () => apiBase()` when it moves, CS-8). Errors carry `err.xenia = { code, params, message, status, offline }`; show them with `errorMessage(err, t)` (texts in `packages/i18n/locales/*/errors.json`, which a test keeps complete against `core/errors.py`: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes `{ xenia: { ignoreUnauthorized: true } }`. Lock screens never log in again: they call `POST /api/auth/unlock {pin}` with the current session (same token; 5 wrong PINs end the session); manager sign-in sends `client: "manager"` and reads its mode from bootstrap `login`. The app root is `<AccessProvider client token i18n>`: it reloads bootstrap whenever the token changes and mounts the manager-approval dialog, so any request refused with `access.override_possible` is retried after a manager's PIN without extra code. Hide UI with `useCan(key)` / `<Can>` / `<RequireModule>` (the backend still checks, CS-14). Live events: `createLiveClient` (one implementation; don't open sockets by hand). In the manager there is one connection, `live/LiveProvider.jsx` (opened with the signed-in shell); components listen with `useLiveEvent(type, handler)` (`'ready'` fires after each reconnect: refetch then).
|
||||||
|
|
||||||
**CS-15. Support access is a challenge code, never a password** (branch `platform-v2`, D-16).
|
**CS-15. Support access is a challenge code, never a password** (branch `platform-v2`, D-16).
|
||||||
There is no master account. A site's `SUPPORT_SECRET` (env only) comes from `tools/support_code.py --site-secret <SITE_ID>`, derived from the builder's master key in `%USERPROFILE%\.xenia\support_master_key.txt` (outside the repo, back it up). The derivation lives in `local_backend/core/support_codes.py` (stdlib only, the tool loads it by path) and is re-implemented for the e2e suites in `tests/e2e/lib/support.mjs`; `tests/test_support.py` pins a vector both must match. The e2e backends log in through support access (`login()` in `lib/proc.mjs`).
|
There is no master account. A site's `SUPPORT_SECRET` (env only) comes from `tools/support_code.py --site-secret <SITE_ID>`, derived from the builder's master key in `%USERPROFILE%\.xenia\support_master_key.txt` (outside the repo, back it up). The derivation lives in `local_backend/core/support_codes.py` (stdlib only, the tool loads it by path) and is re-implemented for the e2e suites in `tests/e2e/lib/support.mjs`; `tests/test_support.py` pins a vector both must match. The e2e backends log in through support access (`login()` in `lib/proc.mjs`).
|
||||||
|
|||||||
@@ -26,6 +26,6 @@ access.override_possible instead of access.denied; a manager's PIN gives a one-t
|
|||||||
token (POST /api/access/override) that check() or require_override() consumes.
|
token (POST /api/access/override) that check() or require_override() consumes.
|
||||||
|
|
||||||
Files: override.py (approval tokens), context.py (device lookup, scope, get_context, authorize), templates.py (role templates from manifests), check.py (the decision),
|
Files: override.py (approval tokens), context.py (device lookup, scope, get_context, authorize), templates.py (role templates from manifests), check.py (the decision),
|
||||||
deps.py (route markers), legacy.py (temporary v1 perm_* projection for the current
|
deps.py (route markers), queries.py (find users holding a key). The v1 perm_* projection
|
||||||
frontends, §3.3), queries.py (find users holding a key).
|
(legacy.py) was removed in step 2.99: no frontend reads or writes the booleans.
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
"""TEMPORARY v1 projection (APPS_PLATFORM §3.3). Delete with the last frontend that reads it.
|
|
||||||
|
|
||||||
The current manager dashboard and waiter app still read and write 13 boolean fields
|
|
||||||
(perm_access_dashboard ...). This file is the ONLY place that knows them:
|
|
||||||
- project(user): booleans computed from the user's keys, for UserOut
|
|
||||||
- apply_booleans(user, {field: bool}): a frontend toggled a boolean -> grant/revoke keys
|
|
||||||
Not for deployed v1 sites (D-21): it only keeps our own unconverted screens usable on
|
|
||||||
the branch. Plan: removed when the manager (phase 2/6) and waiter app (phase 4) use keys.
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from core.access.check import holds, user_keys
|
|
||||||
|
|
||||||
# boolean -> keys it stands for. Projection: True if the user holds the FIRST key.
|
|
||||||
LEGACY_MAP: dict[str, tuple[str, ...]] = {
|
|
||||||
"perm_access_dashboard": ("core.dashboard.access",),
|
|
||||||
"perm_access_waiter_app": ("waiter_app.access",),
|
|
||||||
"perm_access_kds": ("kds.access", "kds.bump"),
|
|
||||||
"perm_cancel_orders": ("ordering.orders.cancel",),
|
|
||||||
"perm_apply_discounts": ("pricing.discounts.apply",),
|
|
||||||
"perm_modify_prices": ("ordering.prices.modify",),
|
|
||||||
"perm_open_orders": ("ordering.orders.open",),
|
|
||||||
"perm_close_orders": ("ordering.orders.close",),
|
|
||||||
"perm_view_reports": ("reports.view", "history.view"),
|
|
||||||
"perm_manage_staff": ("core.staff.manage",),
|
|
||||||
"perm_manage_tables": ("catalog.tables.manage",),
|
|
||||||
"perm_manage_menu": ("catalog.menu.manage",),
|
|
||||||
"perm_manage_settings": ("core.settings.manage",),
|
|
||||||
}
|
|
||||||
LEGACY_FIELDS = tuple(LEGACY_MAP)
|
|
||||||
|
|
||||||
|
|
||||||
def project(user) -> dict[str, bool]:
|
|
||||||
return {field: holds(user, keys[0]) for field, keys in LEGACY_MAP.items()}
|
|
||||||
|
|
||||||
|
|
||||||
def apply_booleans(user, values: dict) -> None:
|
|
||||||
"""Grant/revoke the keys behind each boolean present in `values` (None = untouched)."""
|
|
||||||
from core.access.templates import set_user_keys
|
|
||||||
keys = set(user_keys(user))
|
|
||||||
for field, val in values.items():
|
|
||||||
if field not in LEGACY_MAP or val is None:
|
|
||||||
continue
|
|
||||||
if val:
|
|
||||||
keys |= set(LEGACY_MAP[field])
|
|
||||||
else:
|
|
||||||
keys -= set(LEGACY_MAP[field])
|
|
||||||
set_user_keys(user, keys)
|
|
||||||
@@ -86,6 +86,7 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
# domain
|
# domain
|
||||||
"order.not_found": (404, "Order {order_id} not found."),
|
"order.not_found": (404, "Order {order_id} not found."),
|
||||||
"notification.not_found": (404, "Notification {notification_id} not found."),
|
"notification.not_found": (404, "Notification {notification_id} not found."),
|
||||||
|
"system.log_not_found": (404, "There is no log file for {date}."),
|
||||||
"catalog.unknown_category": (422, "There is no category {category_id}."),
|
"catalog.unknown_category": (422, "There is no category {category_id}."),
|
||||||
"catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."),
|
"catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -277,3 +277,30 @@ class RequestContextMiddleware:
|
|||||||
lvl = logging.WARNING if (code or 500) >= 500 else logging.INFO
|
lvl = logging.WARNING if (code or 500) >= 500 else logging.INFO
|
||||||
_http_log.log(lvl, "http %s %s status=%s ms=%d", method, scope.get("path"), code, ms)
|
_http_log.log(lvl, "http %s %s status=%s ms=%d", method, scope.get("path"), code, ms)
|
||||||
_ctx.reset(token)
|
_ctx.reset(token)
|
||||||
|
|
||||||
|
|
||||||
|
# ── download (plan step 2.6f) ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def log_dir() -> Path:
|
||||||
|
"""Where the daily files are: the active handler's folder, else the default."""
|
||||||
|
return _file_handler.directory if _file_handler is not None else default_log_dir()
|
||||||
|
|
||||||
|
|
||||||
|
def list_log_files(directory: Path | None = None) -> list[dict]:
|
||||||
|
"""[{date, name, size}] newest first, for the manager's log download."""
|
||||||
|
d = directory or log_dir()
|
||||||
|
out = []
|
||||||
|
if d.is_dir():
|
||||||
|
for f in d.glob(f"{FILE_PREFIX}*.log"):
|
||||||
|
m = _FILE_RE.match(f.name)
|
||||||
|
if m:
|
||||||
|
out.append({"date": m.group(1), "name": f.name, "size": f.stat().st_size})
|
||||||
|
return sorted(out, key=lambda x: x["date"], reverse=True)
|
||||||
|
|
||||||
|
|
||||||
|
def log_file_for(date_str: str, directory: Path | None = None) -> Path | None:
|
||||||
|
"""The file of one UTC day, or None (bad date or no file). Only names we write."""
|
||||||
|
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date_str or ""):
|
||||||
|
return None
|
||||||
|
f = (directory or log_dir()) / f"{FILE_PREFIX}{date_str}.log"
|
||||||
|
return f if f.is_file() else None
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ Sessions
|
|||||||
Results are cached for CACHE_TTL_S; end()/end_for_user() drop the cache entry at once,
|
Results are cached for CACHE_TTL_S; end()/end_for_user() drop the cache entry at once,
|
||||||
so an ended session is refused on its very next request.
|
so an ended session is refused on its very next request.
|
||||||
- last_seen_at is written at most every LAST_SEEN_EVERY_S, in its own DB session.
|
- last_seen_at is written at most every LAST_SEEN_EVERY_S, in its own DB session.
|
||||||
|
- Idle sessions (owner decision 2026-11-14, plan 2.99d): a session unused for
|
||||||
|
auth.idle_days days (default 14, 0 = never) ends with reason "idle" on its next request
|
||||||
|
(validate) or when someone lists sessions (end_idle). Support sessions use expires_at.
|
||||||
|
|
||||||
Login modes (settings, declared in modules/core/manifest.py)
|
Login modes (settings, declared in modules/core/manifest.py)
|
||||||
- auth.manager_login_mode: password | pin (manager in a browser: never tap/none, D-8)
|
- auth.manager_login_mode: password | pin (manager in a browser: never tap/none, D-8)
|
||||||
@@ -62,7 +65,7 @@ def single_session_rule(db, client: str) -> str:
|
|||||||
|
|
||||||
# ── lifecycle ────────────────────────────────────────────────────────────────
|
# ── lifecycle ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def start(db, user, client: str, request=None, *, legacy_manager: bool = False, device=None, expires_at=None):
|
def start(db, user, client: str, request=None, *, device=None, expires_at=None):
|
||||||
"""Create a session for user (None user_id for the support account). Commits.
|
"""Create a session for user (None user_id for the support account). Commits.
|
||||||
`device`: the paired device of a terminal login; its previous sessions are replaced
|
`device`: the paired device of a terminal login; its previous sessions are replaced
|
||||||
(a shared screen shows one user at a time)."""
|
(a shared screen shows one user at a time)."""
|
||||||
@@ -71,10 +74,6 @@ def start(db, user, client: str, request=None, *, legacy_manager: bool = False,
|
|||||||
raise ValueError(f"unknown client {client!r}")
|
raise ValueError(f"unknown client {client!r}")
|
||||||
user_id = getattr(user, "id", None) or None
|
user_id = getattr(user, "id", None) or None
|
||||||
rule = single_session_rule(db, client)
|
rule = single_session_rule(db, client)
|
||||||
if legacy_manager and rule == "refuse_new":
|
|
||||||
# The current manager UI re-logs-in to unlock its lock screen; refusing would lock
|
|
||||||
# the owner out. Until the phase 2 manager has a real unlock, treat it as end_old.
|
|
||||||
rule = "end_old"
|
|
||||||
if user_id is not None and rule != "off":
|
if user_id is not None and rule != "off":
|
||||||
active = db.query(LoginSession).filter(LoginSession.user_id == user_id, LoginSession.client == client,
|
active = db.query(LoginSession).filter(LoginSession.user_id == user_id, LoginSession.client == client,
|
||||||
LoginSession.ended_at.is_(None)).all()
|
LoginSession.ended_at.is_(None)).all()
|
||||||
@@ -132,6 +131,33 @@ def end_for_device(db, device_id: int, reason: str) -> int:
|
|||||||
return len(rows)
|
return len(rows)
|
||||||
|
|
||||||
|
|
||||||
|
def idle_days(db) -> int:
|
||||||
|
try:
|
||||||
|
return max(0, int(_setting(db, "auth.idle_days", "14")))
|
||||||
|
except ValueError:
|
||||||
|
return 14
|
||||||
|
|
||||||
|
|
||||||
|
def _idle(row, days: int, now) -> bool:
|
||||||
|
return days > 0 and row.client != "support" and now - row.last_seen_at > timedelta(days=days)
|
||||||
|
|
||||||
|
|
||||||
|
def end_idle(db) -> int:
|
||||||
|
"""End every active session unused for auth.idle_days. Returns how many."""
|
||||||
|
from models.session import LoginSession
|
||||||
|
days = idle_days(db)
|
||||||
|
if not days:
|
||||||
|
return 0
|
||||||
|
now = utcnow()
|
||||||
|
rows = db.query(LoginSession).filter(LoginSession.ended_at.is_(None), LoginSession.client != "support",
|
||||||
|
LoginSession.last_seen_at < now - timedelta(days=days)).all()
|
||||||
|
for r in rows:
|
||||||
|
_end_row(r, "idle")
|
||||||
|
if rows:
|
||||||
|
db.commit()
|
||||||
|
return len(rows)
|
||||||
|
|
||||||
|
|
||||||
def validate(sid: str | None, db=None) -> Active:
|
def validate(sid: str | None, db=None) -> Active:
|
||||||
"""(user_id, device_id) of an active session. Raises auth.session_ended."""
|
"""(user_id, device_id) of an active session. Raises auth.session_ended."""
|
||||||
if not sid:
|
if not sid:
|
||||||
@@ -151,6 +177,9 @@ def validate(sid: str | None, db=None) -> Active:
|
|||||||
if row is not None and row.ended_at is None and row.expires_at is not None and row.expires_at <= utcnow():
|
if row is not None and row.ended_at is None and row.expires_at is not None and row.expires_at <= utcnow():
|
||||||
_end_row(row, "expired")
|
_end_row(row, "expired")
|
||||||
db.commit()
|
db.commit()
|
||||||
|
elif row is not None and row.ended_at is None and _idle(row, idle_days(db), utcnow()):
|
||||||
|
_end_row(row, "idle")
|
||||||
|
db.commit()
|
||||||
if row is None or row.ended_at is not None:
|
if row is None or row.ended_at is not None:
|
||||||
with _lock:
|
with _lock:
|
||||||
_cache.pop(sid, None)
|
_cache.pop(sid, None)
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ MODULE = Module(
|
|||||||
SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'),
|
SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'),
|
||||||
SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
||||||
SettingDef('auth.single_session_waiter', 'off', "One waiter session per user (no double login): 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
SettingDef('auth.single_session_waiter', 'off', "One waiter session per user (no double login): 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
||||||
|
SettingDef('auth.idle_days', '14', 'Sign people out after this many days without using the app (manager, waiter, paired-device sessions; support has its own 4 h). 0 = never.', type='int'),
|
||||||
SettingDef('system.log_retention_days', '30', 'Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.', type='int'),
|
SettingDef('system.log_retention_days', '30', 'Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.', type='int'),
|
||||||
SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'),
|
SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'),
|
||||||
SettingDef('venue.timezone', 'Europe/Athens', 'IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.', type='str'),
|
SettingDef('venue.timezone', 'Europe/Athens', 'IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.', type='str'),
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from core.access.deps import require
|
|||||||
from core.timeutil import iso_z
|
from core.timeutil import iso_z
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from models.access_override import AccessOverride
|
from models.access_override import AccessOverride
|
||||||
|
from models.device import Device
|
||||||
from models.user import User
|
from models.user import User
|
||||||
from routers.deps import get_current_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()
|
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}
|
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()}
|
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),
|
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,
|
"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]
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ def _check_secret(user, pin, password, db) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def do_login(db: Session, request: Request, *, client: str, username: str | None, user_id: int | None,
|
def do_login(db: Session, request: Request, *, client: str, username: str | None, user_id: int | None,
|
||||||
pin: str | None, password: str | None, legacy: bool = False) -> TokenResponse:
|
pin: str | None, password: str | None) -> TokenResponse:
|
||||||
"""The one login path. Applies the client's login mode, its access key and the
|
"""The one login path. Applies the client's login mode, its access key and the
|
||||||
single-session rule, then creates a session (core/sessions.py)."""
|
single-session rule, then creates a session (core/sessions.py)."""
|
||||||
if client not in ("manager", "waiter", "terminal"):
|
if client not in ("manager", "waiter", "terminal"):
|
||||||
@@ -57,11 +57,10 @@ def do_login(db: Session, request: Request, *, client: str, username: str | None
|
|||||||
|
|
||||||
if client == "manager":
|
if client == "manager":
|
||||||
mode = sessions.manager_login_mode(db)
|
mode = sessions.manager_login_mode(db)
|
||||||
if not legacy: # the current manager UI (no `client`) keeps v1 behaviour: pin or password
|
if mode == "password" and not password:
|
||||||
if mode == "password" and not password:
|
raise XeniaError("auth.login_mode_not_allowed", mode="pin")
|
||||||
raise XeniaError("auth.login_mode_not_allowed", mode="pin")
|
if mode == "pin" and not (pin or password):
|
||||||
if mode == "pin" and not (pin or password):
|
raise XeniaError("auth.invalid_credentials")
|
||||||
raise XeniaError("auth.invalid_credentials")
|
|
||||||
if not username:
|
if not username:
|
||||||
raise XeniaError("auth.username_required")
|
raise XeniaError("auth.username_required")
|
||||||
else:
|
else:
|
||||||
@@ -85,7 +84,7 @@ def do_login(db: Session, request: Request, *, client: str, username: str | None
|
|||||||
if not holds(user, needed):
|
if not holds(user, needed):
|
||||||
raise XeniaError("auth.client_not_allowed", client=client)
|
raise XeniaError("auth.client_not_allowed", client=client)
|
||||||
|
|
||||||
row = sessions.start(db, user, client, request, legacy_manager=legacy and client == "manager")
|
row = sessions.start(db, user, client, request)
|
||||||
return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user))
|
return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user))
|
||||||
|
|
||||||
|
|
||||||
@@ -124,10 +123,9 @@ def _terminal_login(db: Session, request: Request, *, username, user_id, pin, pa
|
|||||||
@router.post("/login", response_model=TokenResponse, dependencies=[Depends(public())])
|
@router.post("/login", response_model=TokenResponse, dependencies=[Depends(public())])
|
||||||
def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)):
|
def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)):
|
||||||
"""POST {client: "manager"|"waiter"|"terminal", username?, user_id?, pin?, password?}.
|
"""POST {client: "manager"|"waiter"|"terminal", username?, user_id?, pin?, password?}.
|
||||||
"terminal" = a user on a paired device: send the X-Xenia-Device header.
|
"terminal" = a user on a paired device: send the X-Xenia-Device header."""
|
||||||
Without `client` (the current manager UI): a manager login with v1 rules (pin or password)."""
|
return do_login(db, request, client=body.client, username=body.username,
|
||||||
return do_login(db, request, client=body.client or "manager", username=body.username,
|
user_id=body.user_id, pin=body.pin, password=body.password)
|
||||||
user_id=body.user_id, pin=body.pin, password=body.password, legacy=body.client is None)
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/login-by-id", response_model=TokenResponse, dependencies=[Depends(public())], deprecated=True)
|
@router.post("/login-by-id", response_model=TokenResponse, dependencies=[Depends(public())], deprecated=True)
|
||||||
@@ -279,24 +277,31 @@ def support_verify(body: SupportVerifyRequest, request: Request, db: Session = D
|
|||||||
|
|
||||||
# ── Sessions (D-9): who is logged in where ─────────────────────────────────
|
# ── 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)
|
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),
|
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,
|
"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}
|
"ended_at": iso_z(s.ended_at), "end_reason": s.end_reason, "ip": s.ip, "user_agent": s.user_agent}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/sessions")
|
@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"))):
|
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
|
||||||
|
sessions.end_idle(db) # so "Signed in now" never lists someone gone for weeks (auth.idle_days)
|
||||||
q = db.query(LoginSession)
|
q = db.query(LoginSession)
|
||||||
if not include_ended:
|
if not include_ended:
|
||||||
q = q.filter(LoginSession.ended_at.is_(None))
|
q = q.filter(LoginSession.ended_at.is_(None))
|
||||||
rows = q.order_by(LoginSession.created_at.desc()).limit(200).all()
|
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()}
|
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")
|
@router.post("/sessions/{sid}/end")
|
||||||
|
|||||||
@@ -1,19 +1,16 @@
|
|||||||
from core.access.deps import public
|
|
||||||
from core.timeutil import utcnow
|
from core.timeutil import utcnow
|
||||||
import secrets
|
import secrets
|
||||||
import bcrypt
|
import bcrypt
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
from fastapi import APIRouter, Depends
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from models.user import User
|
from models.user import User
|
||||||
from models.recovery_code import RecoveryCode
|
from models.recovery_code import RecoveryCode
|
||||||
from schemas.user import UserOut
|
from routers.deps import get_current_user
|
||||||
from schemas.auth import TokenResponse
|
|
||||||
from routers.deps import get_current_user, make_token
|
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
@@ -50,26 +47,6 @@ def try_recovery_code(plain: str, user: "User", db: "Session") -> bool:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
# ─── Public: use a recovery code to log in (kept for direct API use) ─────────
|
|
||||||
|
|
||||||
class UseRecoveryCodeRequest(BaseModel):
|
|
||||||
username: str
|
|
||||||
code: str
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/use", response_model=TokenResponse, dependencies=[Depends(public())])
|
|
||||||
def use_recovery_code(body: UseRecoveryCodeRequest, request: Request, db: Session = Depends(get_db)):
|
|
||||||
user = db.query(User).filter(
|
|
||||||
User.username == body.username,
|
|
||||||
User.is_active == True,
|
|
||||||
).first()
|
|
||||||
if not user or not try_recovery_code(body.code, user, db):
|
|
||||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
|
||||||
from core import sessions
|
|
||||||
row = sessions.start(db, user, "manager", request, legacy_manager=True)
|
|
||||||
return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user))
|
|
||||||
|
|
||||||
|
|
||||||
# ─── Authenticated: generate a new batch (burns all existing unused codes) ───
|
# ─── Authenticated: generate a new batch (burns all existing unused codes) ───
|
||||||
|
|
||||||
class RecoveryCodesGenerated(BaseModel):
|
class RecoveryCodesGenerated(BaseModel):
|
||||||
|
|||||||
@@ -1716,6 +1716,15 @@ def meta_products(
|
|||||||
# CSV export endpoints
|
# CSV export endpoints
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _csv_response_fields(rows: list, fields: list, filename: str) -> StreamingResponse:
|
||||||
|
output = io.StringIO()
|
||||||
|
writer = csv.DictWriter(output, fieldnames=fields)
|
||||||
|
writer.writeheader()
|
||||||
|
writer.writerows(rows)
|
||||||
|
return StreamingResponse(iter([output.getvalue()]), media_type="text/csv",
|
||||||
|
headers={"Content-Disposition": f'attachment; filename="{filename}"'})
|
||||||
|
|
||||||
|
|
||||||
def _csv_response(rows: list, filename: str) -> StreamingResponse:
|
def _csv_response(rows: list, filename: str) -> StreamingResponse:
|
||||||
if not rows:
|
if not rows:
|
||||||
rows = [{}]
|
rows = [{}]
|
||||||
@@ -1769,26 +1778,27 @@ def orders_export(
|
|||||||
waiter_id: Optional[int] = None,
|
waiter_id: Optional[int] = None,
|
||||||
order_status: Optional[str] = Query(default=None, alias="status"),
|
order_status: Optional[str] = Query(default=None, alias="status"),
|
||||||
table_id: Optional[int] = None,
|
table_id: Optional[int] = None,
|
||||||
|
business_day_id: Optional[int] = None,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
user: User = Depends(require_reports),
|
user: User = Depends(require_reports),
|
||||||
):
|
):
|
||||||
orders = order_history(from_date=from_date, to_date=to_date, waiter_id=waiter_id, order_status=order_status, table_id=table_id, page=1, page_size=10000, db=db, user=user)
|
"""Orders as CSV, same filters as GET /orders/history (KI-008: it read the history's
|
||||||
tables_db = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
|
dicts as ORM rows and always failed; business_day_id was ignored). Times are UTC ISO,
|
||||||
waiters_db = {u.id: u for u in db.query(User).all()}
|
like the other exports."""
|
||||||
rows = []
|
orders = order_history(from_date=from_date, to_date=to_date, waiter_id=waiter_id, order_status=order_status,
|
||||||
for o in orders:
|
table_id=table_id, business_day_id=business_day_id, page=1, page_size=10000, db=db, user=user)
|
||||||
waiter = waiters_db.get(o.opened_by)
|
rows = [{
|
||||||
rows.append({
|
"id": o["id"],
|
||||||
"id": o.id,
|
"table": o["table_name"] or "",
|
||||||
"table": tables_db.get(o.table_id, ""),
|
"waiter": o["opened_by_name"] or "",
|
||||||
"waiter": (waiter.full_name or waiter.username) if waiter else "",
|
"opened_at": o["opened_at"] or "",
|
||||||
"opened_at": _dt(o.opened_at),
|
"closed_at": o["closed_at"] or "",
|
||||||
"closed_at": _dt(o.closed_at) if o.closed_at else "",
|
"status": o["status"],
|
||||||
"status": o.status,
|
"total": round(sum((i["unit_price"] + i["price_adjustment"]) * i["quantity"]
|
||||||
"total": round(sum(_item_val(i) for i in o.items if i.status in ("active", "paid")), 2),
|
for i in o["items"] if i["status"] in ("active", "paid")), 2),
|
||||||
})
|
} for o in orders]
|
||||||
date_str = (from_date or "")[:10]
|
fields = ["id", "table", "waiter", "opened_at", "closed_at", "status", "total"] # header even when empty
|
||||||
return _csv_response(rows, f"orders-{date_str}.csv")
|
return _csv_response_fields(rows, fields, f"orders-{(from_date or '')[:10]}.csv")
|
||||||
|
|
||||||
|
|
||||||
@router.get("/products/export")
|
@router.get("/products/export")
|
||||||
|
|||||||
@@ -26,31 +26,14 @@ class SetupInitRequest(BaseModel):
|
|||||||
venue_type: Optional[str] = None
|
venue_type: Optional[str] = None
|
||||||
venue_name: Optional[str] = None
|
venue_name: Optional[str] = None
|
||||||
pin: Optional[str] = None
|
pin: Optional[str] = None
|
||||||
|
language: Optional[str] = None # venue.language (2.6f): v2 defaults to English otherwise
|
||||||
|
timezone: Optional[str] = None # venue.timezone, IANA (the browser's zone)
|
||||||
|
|
||||||
|
|
||||||
class SetupInitResponse(BaseModel):
|
class SetupInitResponse(BaseModel):
|
||||||
ok: bool
|
ok: bool
|
||||||
|
|
||||||
|
|
||||||
class SecurityConfigResponse(BaseModel):
|
|
||||||
login_method: str
|
|
||||||
autofill_username: bool
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/security-config", response_model=SecurityConfigResponse, dependencies=[Depends(public())])
|
|
||||||
def security_config(db: Session = Depends(get_db)):
|
|
||||||
"""Public endpoint — returns only the security settings needed by the login page."""
|
|
||||||
from models.settings import PosSettings
|
|
||||||
rows = {r.key: r.value for r in db.query(PosSettings).filter(
|
|
||||||
PosSettings.key.in_(["auth.manager_login_mode", "security.autofill_username"])
|
|
||||||
).all()}
|
|
||||||
# `login_method` is what the current manager login page reads; "none" no longer exists (D-8)
|
|
||||||
return SecurityConfigResponse(
|
|
||||||
login_method=rows.get("auth.manager_login_mode", "password"),
|
|
||||||
autofill_username=rows.get("security.autofill_username", "true") == "true",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/status", response_model=SetupStatusResponse, dependencies=[Depends(public())])
|
@router.get("/status", response_model=SetupStatusResponse, dependencies=[Depends(public())])
|
||||||
def setup_status(db: Session = Depends(get_db)):
|
def setup_status(db: Session = Depends(get_db)):
|
||||||
has_manager = db.query(User).filter(
|
has_manager = db.query(User).filter(
|
||||||
@@ -81,6 +64,16 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
|
|||||||
if existing:
|
if existing:
|
||||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken.")
|
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken.")
|
||||||
|
|
||||||
|
from core import i18n, timeutil
|
||||||
|
from core.errors import XeniaError
|
||||||
|
if body.language and not i18n.is_supported(body.language):
|
||||||
|
raise XeniaError("validation.unknown_language", language=body.language)
|
||||||
|
if body.timezone:
|
||||||
|
try:
|
||||||
|
timeutil.validate_tz(body.timezone)
|
||||||
|
except ValueError:
|
||||||
|
raise XeniaError("validation.unknown_timezone", timezone=body.timezone)
|
||||||
|
|
||||||
password_hash = bcrypt.hashpw(body.password.encode(), bcrypt.gensalt()).decode()
|
password_hash = bcrypt.hashpw(body.password.encode(), bcrypt.gensalt()).decode()
|
||||||
|
|
||||||
raw_pin = body.pin if (body.pin and body.pin.isdigit() and 4 <= len(body.pin) <= 6) else "0000"
|
raw_pin = body.pin if (body.pin and body.pin.isdigit() and 4 <= len(body.pin) <= 6) else "0000"
|
||||||
@@ -100,6 +93,19 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
|
|||||||
db.add(user)
|
db.add(user)
|
||||||
|
|
||||||
# Persist venue settings if provided
|
# Persist venue settings if provided
|
||||||
|
from models.settings import PosSettings
|
||||||
|
|
||||||
|
def _put(key, value):
|
||||||
|
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||||
|
if row:
|
||||||
|
row.value = value
|
||||||
|
row.updated_at = utcnow()
|
||||||
|
else:
|
||||||
|
db.add(PosSettings(key=key, value=value, updated_at=utcnow()))
|
||||||
|
if body.language:
|
||||||
|
_put("venue.language", body.language)
|
||||||
|
if body.timezone:
|
||||||
|
_put("venue.timezone", body.timezone)
|
||||||
if body.venue_name or body.venue_type:
|
if body.venue_name or body.venue_type:
|
||||||
from models.settings import PosSettings
|
from models.settings import PosSettings
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
@@ -119,7 +125,14 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
|
|||||||
else:
|
else:
|
||||||
db.add(PosSettings(key="venue.type", value=body.venue_type, updated_at=now))
|
db.add(PosSettings(key="venue.type", value=body.venue_type, updated_at=now))
|
||||||
|
|
||||||
|
from services.defaults import seed_starter_content # table flags + quick messages (KI-007)
|
||||||
|
from core.sessions import _setting
|
||||||
|
seed_starter_content(db, body.language or _setting(db, "venue.language", "en"))
|
||||||
|
|
||||||
db.commit()
|
db.commit()
|
||||||
|
if body.language or body.timezone:
|
||||||
|
i18n.invalidate()
|
||||||
|
timeutil.invalidate()
|
||||||
db.refresh(user)
|
db.refresh(user)
|
||||||
add_user_to_system_group(db, user.id)
|
add_user_to_system_group(db, user.id)
|
||||||
return SetupInitResponse(ok=True)
|
return SetupInitResponse(ok=True)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from core.access.deps import public
|
from core.access.deps import public
|
||||||
from core.access.queries import holders_filter
|
from core.access.queries import holders_filter
|
||||||
|
from core.access.deps import require
|
||||||
import asyncio
|
import asyncio
|
||||||
import ipaddress
|
import ipaddress
|
||||||
import json
|
import json
|
||||||
@@ -77,6 +78,29 @@ def _lock_reason() -> str | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ── Log download (plan step 2.6f, APPS_PLATFORM §10) ───────────────────────────
|
||||||
|
# The daily files of core/logging.py. Owner-level (core.settings.manage): lines carry
|
||||||
|
# usernames, IPs and order ids (never secrets).
|
||||||
|
|
||||||
|
@router.get("/logs")
|
||||||
|
def list_logs(user: User = Depends(require("core.settings.manage"))):
|
||||||
|
"""[{date, name, size}] newest first (UTC days)."""
|
||||||
|
from core.logging import list_log_files
|
||||||
|
return list_log_files()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/logs/{date}")
|
||||||
|
def download_log(date: str, user: User = Depends(require("core.settings.manage"))):
|
||||||
|
"""One day's file as an attachment (today's is still being written: a snapshot)."""
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
from core.errors import XeniaError
|
||||||
|
from core.logging import log_file_for
|
||||||
|
f = log_file_for(date)
|
||||||
|
if f is None:
|
||||||
|
raise XeniaError("system.log_not_found", date=date)
|
||||||
|
return FileResponse(f, media_type="text/plain; charset=utf-8", filename=f.name)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/status")
|
@router.get("/status")
|
||||||
def system_status(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
def system_status(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||||
printers = db.query(Printer).filter(Printer.is_active == True).all()
|
printers = db.query(Printer).filter(Printer.is_active == True).all()
|
||||||
|
|||||||
@@ -10,12 +10,11 @@ from pydantic import BaseModel
|
|||||||
from database import get_db
|
from database import get_db
|
||||||
from models.user import User, AssistantAssignment, WaiterZone
|
from models.user import User, AssistantAssignment, WaiterZone
|
||||||
from models.shift import WaiterShift
|
from models.shift import WaiterShift
|
||||||
from schemas.user import UserCreate, UserUpdate, UserOut, AssistantAssignmentOut, SetZonesRequest, PermissionToggle
|
from schemas.user import UserCreate, UserUpdate, UserOut, AssistantAssignmentOut, SetZonesRequest
|
||||||
from routers.deps import require_staff_manager, get_current_user
|
from routers.deps import require_staff_manager, get_current_user
|
||||||
from services.chat_service import add_user_to_system_group
|
from services.chat_service import add_user_to_system_group
|
||||||
from roles import ALL_ROLES, VALID_ROLES
|
from roles import ALL_ROLES, VALID_ROLES
|
||||||
from core.access.check import holds, user_keys
|
from core.access.check import holds, user_keys
|
||||||
from core.access.legacy import LEGACY_FIELDS, LEGACY_MAP, apply_booleans
|
|
||||||
from core.access.queries import holders_filter
|
from core.access.queries import holders_filter
|
||||||
from core.access.templates import apply_role_template, role_template, set_user_keys
|
from core.access.templates import apply_role_template, role_template, set_user_keys
|
||||||
from core.errors import XeniaError
|
from core.errors import XeniaError
|
||||||
@@ -136,13 +135,7 @@ def create_staff(body: UserCreate, db: Session = Depends(get_db), user: User = D
|
|||||||
note=body.note,
|
note=body.note,
|
||||||
hourly_rate=body.hourly_rate,
|
hourly_rate=body.hourly_rate,
|
||||||
)
|
)
|
||||||
# Role template (manifests), then any legacy booleans the current manager UI sent
|
apply_role_template(new_user) # keys from the role's template (manifests); edit them with PUT /{id}/permissions
|
||||||
apply_role_template(new_user)
|
|
||||||
# only flags the client actually sent (UserCreate has v1 defaults for all 13)
|
|
||||||
legacy = {f: getattr(body, f) for f in LEGACY_FIELDS if f in body.model_fields_set}
|
|
||||||
before = set(user_keys(new_user))
|
|
||||||
apply_booleans(new_user, legacy)
|
|
||||||
_guard_grant(user, set(user_keys(new_user)) - before)
|
|
||||||
|
|
||||||
db.add(new_user)
|
db.add(new_user)
|
||||||
db.commit()
|
db.commit()
|
||||||
@@ -170,13 +163,8 @@ def update_staff(waiter_id: int, body: UserUpdate, db: Session = Depends(get_db)
|
|||||||
if body.language is not None:
|
if body.language is not None:
|
||||||
body.language = normalize_language(body.language) or ""
|
body.language = normalize_language(body.language) or ""
|
||||||
data = body.model_dump(exclude_none=True)
|
data = body.model_dump(exclude_none=True)
|
||||||
legacy = {f: data.pop(f) for f in list(data) if f in LEGACY_MAP}
|
|
||||||
for field, value in data.items():
|
for field, value in data.items():
|
||||||
setattr(target, field, value)
|
setattr(target, field, value)
|
||||||
if legacy: # the current manager UI still sends perm_* booleans (core/access/legacy.py)
|
|
||||||
before = set(user_keys(target))
|
|
||||||
apply_booleans(target, legacy)
|
|
||||||
_guard_grant(user, set(user_keys(target)) - before)
|
|
||||||
if target.language == "":
|
if target.language == "":
|
||||||
target.language = None # "" means inherit
|
target.language = None # "" means inherit
|
||||||
|
|
||||||
@@ -206,43 +194,6 @@ def toggle_block(waiter_id: int, db: Session = Depends(get_db), user: User = Dep
|
|||||||
return {"is_active": target.is_active}
|
return {"is_active": target.is_active}
|
||||||
|
|
||||||
|
|
||||||
@router.put("/{waiter_id}/permission")
|
|
||||||
def toggle_permission(
|
|
||||||
waiter_id: int,
|
|
||||||
body: PermissionToggle,
|
|
||||||
db: Session = Depends(get_db),
|
|
||||||
user: User = Depends(require_staff_manager),
|
|
||||||
):
|
|
||||||
"""Grant/revoke one permission: a key ("reports.view") or a legacy v1 flag name."""
|
|
||||||
target = _user_or_404(waiter_id, db)
|
|
||||||
_guard_superadmin_target(target, user)
|
|
||||||
|
|
||||||
if body.permission in LEGACY_MAP:
|
|
||||||
keys = set(LEGACY_MAP[body.permission])
|
|
||||||
if body.value:
|
|
||||||
_guard_grant(user, keys)
|
|
||||||
apply_booleans(target, {body.permission: body.value})
|
|
||||||
else:
|
|
||||||
current = set(user_keys(target))
|
|
||||||
if body.value:
|
|
||||||
_guard_grant(user, {body.permission})
|
|
||||||
set_user_keys(target, current | {body.permission} if body.value else current - {body.permission})
|
|
||||||
db.commit()
|
|
||||||
return {"permission": body.permission, "value": body.value}
|
|
||||||
|
|
||||||
|
|
||||||
@router.put("/{waiter_id}/reset-permissions", response_model=UserOut)
|
|
||||||
def reset_permissions(waiter_id: int, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
|
|
||||||
"""Reset a staff member's permissions to their role's template (from the manifests)."""
|
|
||||||
target = _user_or_404(waiter_id, db)
|
|
||||||
_guard_superadmin_target(target, user)
|
|
||||||
_guard_grant(user, role_template(target.role))
|
|
||||||
apply_role_template(target)
|
|
||||||
db.commit()
|
|
||||||
db.refresh(target)
|
|
||||||
return target
|
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/{waiter_id}", status_code=status.HTTP_204_NO_CONTENT)
|
@router.delete("/{waiter_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
def delete_staff(waiter_id: int, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
|
def delete_staff(waiter_id: int, db: Session = Depends(get_db), user: User = Depends(require_staff_manager)):
|
||||||
target = _user_or_404(waiter_id, db)
|
target = _user_or_404(waiter_id, db)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ from schemas.user import UserOut
|
|||||||
|
|
||||||
|
|
||||||
class LoginRequest(BaseModel):
|
class LoginRequest(BaseModel):
|
||||||
client: str | None = None # "manager" | "waiter" | "terminal" (paired device); None = the current manager UI (v1 rules)
|
client: str # "manager" | "waiter" | "terminal" (paired device)
|
||||||
username: str | None = None
|
username: str | None = None
|
||||||
user_id: int | None = None # waiter picks their name (when the username isn't required)
|
user_id: int | None = None # waiter picks their name (when the username isn't required)
|
||||||
pin: str | None = None
|
pin: str | None = None
|
||||||
|
|||||||
@@ -17,22 +17,6 @@ class UserBase(BaseModel):
|
|||||||
language: Optional[str] = None # NULL = inherit (device -> venue -> en)
|
language: Optional[str] = None # NULL = inherit (device -> venue -> en)
|
||||||
# Phase 2B — payroll
|
# Phase 2B — payroll
|
||||||
hourly_rate: Optional[float] = None
|
hourly_rate: Optional[float] = None
|
||||||
# v1 permission booleans: OUTPUT ONLY, computed from keys (core/access/legacy.py, §3.3)
|
|
||||||
perm_access_dashboard: bool = False
|
|
||||||
perm_access_waiter_app: bool = True
|
|
||||||
perm_access_kds: bool = False
|
|
||||||
# Order action permissions
|
|
||||||
perm_cancel_orders: bool = False
|
|
||||||
perm_apply_discounts: bool = False
|
|
||||||
perm_modify_prices: bool = False
|
|
||||||
perm_open_orders: bool = True
|
|
||||||
perm_close_orders: bool = True
|
|
||||||
# Management permissions
|
|
||||||
perm_view_reports: bool = False
|
|
||||||
perm_manage_staff: bool = False
|
|
||||||
perm_manage_tables: bool = False
|
|
||||||
perm_manage_menu: bool = False
|
|
||||||
perm_manage_settings: bool = False
|
|
||||||
|
|
||||||
|
|
||||||
class UserCreate(UserBase):
|
class UserCreate(UserBase):
|
||||||
@@ -51,22 +35,6 @@ class UserUpdate(BaseModel):
|
|||||||
language: Optional[str] = None # "" clears it (inherit)
|
language: Optional[str] = None # "" clears it (inherit)
|
||||||
# Phase 2B — payroll
|
# Phase 2B — payroll
|
||||||
hourly_rate: Optional[float] = None
|
hourly_rate: Optional[float] = None
|
||||||
# Access permissions
|
|
||||||
perm_access_dashboard: Optional[bool] = None
|
|
||||||
perm_access_waiter_app: Optional[bool] = None
|
|
||||||
perm_access_kds: Optional[bool] = None
|
|
||||||
# Order action permissions
|
|
||||||
perm_cancel_orders: Optional[bool] = None
|
|
||||||
perm_apply_discounts: Optional[bool] = None
|
|
||||||
perm_modify_prices: Optional[bool] = None
|
|
||||||
perm_open_orders: Optional[bool] = None
|
|
||||||
perm_close_orders: Optional[bool] = None
|
|
||||||
# Management permissions
|
|
||||||
perm_view_reports: Optional[bool] = None
|
|
||||||
perm_manage_staff: Optional[bool] = None
|
|
||||||
perm_manage_tables: Optional[bool] = None
|
|
||||||
perm_manage_menu: Optional[bool] = None
|
|
||||||
perm_manage_settings: Optional[bool] = None
|
|
||||||
|
|
||||||
|
|
||||||
class WaiterZoneOut(BaseModel):
|
class WaiterZoneOut(BaseModel):
|
||||||
@@ -89,16 +57,13 @@ class UserOut(UserBase):
|
|||||||
@model_validator(mode="before")
|
@model_validator(mode="before")
|
||||||
@classmethod
|
@classmethod
|
||||||
def _from_user(cls, obj):
|
def _from_user(cls, obj):
|
||||||
"""ORM user -> dict with the v1 perm_* booleans computed from its keys
|
"""ORM user -> dict with its permission keys."""
|
||||||
(core/access/legacy.py, temporary) and the keys themselves."""
|
|
||||||
if isinstance(obj, dict):
|
if isinstance(obj, dict):
|
||||||
return obj
|
return obj
|
||||||
from core.access.check import user_keys
|
from core.access.check import user_keys
|
||||||
from core.access.legacy import project
|
|
||||||
data = {name: getattr(obj, name, None) for name in cls.model_fields
|
data = {name: getattr(obj, name, None) for name in cls.model_fields
|
||||||
if name not in ("permissions",) and not name.startswith("perm_")}
|
if name != "permissions"}
|
||||||
data["zone_assignments"] = list(getattr(obj, "zone_assignments", None) or [])
|
data["zone_assignments"] = list(getattr(obj, "zone_assignments", None) or [])
|
||||||
data.update(project(obj))
|
|
||||||
data["permissions"] = sorted(user_keys(obj))
|
data["permissions"] = sorted(user_keys(obj))
|
||||||
return {k: v for k, v in data.items() if v is not None or k in ("full_name",)}
|
return {k: v for k, v in data.items() if v is not None or k in ("full_name",)}
|
||||||
|
|
||||||
@@ -118,9 +83,3 @@ class AssistantAssignmentOut(BaseModel):
|
|||||||
assigned_at: UTCDatetime
|
assigned_at: UTCDatetime
|
||||||
|
|
||||||
model_config = {"from_attributes": True}
|
model_config = {"from_attributes": True}
|
||||||
|
|
||||||
|
|
||||||
class PermissionToggle(BaseModel):
|
|
||||||
"""Patch a single permission flag for a staff member."""
|
|
||||||
permission: str
|
|
||||||
value: bool
|
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""Starter content for a new venue (KI-007, platform-v2 cleanup before phase 3).
|
||||||
|
|
||||||
|
The setup wizard (POST /api/setup/init) calls seed_starter_content() once, in the language
|
||||||
|
the owner picked. It is ordinary data: managers rename, hide or delete it under
|
||||||
|
Settings -> Operation (table flags, quick messages). Nothing is added when a table already
|
||||||
|
has rows (a re-run, or data brought over by the v1 migration, 7.1).
|
||||||
|
|
||||||
|
v1 tried to seed the same lists in main.py, but its INSERTs left out NOT NULL columns and
|
||||||
|
failed silently, so no v1 site ever got them.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
# (emoji, colour, {language: name}) — the v1 list, in its order
|
||||||
|
TABLE_FLAGS = (
|
||||||
|
("🧹", "#ef4444", {"en": "Needs cleaning", "el": "Χρειάζεται καθάρισμα"}),
|
||||||
|
("🆘", "#f97316", {"en": "Needs help", "el": "Χρειάζεται βοήθεια"}),
|
||||||
|
("🔔", "#eab308", {"en": "Wants a waiter", "el": "Χρειάζεται σερβιτόρο"}),
|
||||||
|
("💳", "#3b82f6", {"en": "Waiting to pay", "el": "Περιμένει να πληρώσει"}),
|
||||||
|
("⭐", "#8b5cf6", {"en": "VIP", "el": "VIP"}),
|
||||||
|
("😊", "#22c55e", {"en": "Friendly guests", "el": "Ευγενικός πελάτης"}),
|
||||||
|
("😤", "#dc2626", {"en": "Difficult guests", "el": "Αγενής πελάτης"}),
|
||||||
|
("⚠️", "#f59e0b", {"en": "Allergies", "el": "Αλλεργίες"}),
|
||||||
|
("👶", "#06b6d4", {"en": "Children at the table", "el": "Παιδιά στο τραπέζι"}),
|
||||||
|
("🎂", "#ec4899", {"en": "Anniversary / birthday", "el": "Επέτειος / γενέθλια"}),
|
||||||
|
)
|
||||||
|
|
||||||
|
QUICK_MESSAGES = (
|
||||||
|
{"en": "I need you now", "el": "Σε χρειάζομαι τώρα"},
|
||||||
|
{"en": "Take a break", "el": "Πάρε διάλειμμα"},
|
||||||
|
{"en": "Get ready to close", "el": "Ετοιμάσου για κλείσιμο"},
|
||||||
|
{"en": "New guests have arrived", "el": "Ήρθε νέος πελάτης"},
|
||||||
|
{"en": "A guest is waiting to pay", "el": "Ο πελάτης περιμένει να πληρώσει"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def seed_starter_content(db, language: str | None) -> dict:
|
||||||
|
"""Add the default table flags and quick messages if none exist. Doesn't commit."""
|
||||||
|
from models.flag import TableFlagDef
|
||||||
|
from models.message import QuickMessageTemplate
|
||||||
|
lang = language if language in ("en", "el") else "en"
|
||||||
|
added = {"flags": 0, "quick_messages": 0}
|
||||||
|
if db.query(TableFlagDef).count() == 0:
|
||||||
|
for i, (emoji, color, names) in enumerate(TABLE_FLAGS, start=1):
|
||||||
|
db.add(TableFlagDef(name=names[lang], emoji=emoji, color=color, sort_order=i, is_active=True))
|
||||||
|
added["flags"] = len(TABLE_FLAGS)
|
||||||
|
if db.query(QuickMessageTemplate).count() == 0:
|
||||||
|
for i, bodies in enumerate(QUICK_MESSAGES, start=1):
|
||||||
|
db.add(QuickMessageTemplate(body=bodies[lang], sort_order=i, is_active=True))
|
||||||
|
added["quick_messages"] = len(QUICK_MESSAGES)
|
||||||
|
return added
|
||||||
@@ -1,14 +1,13 @@
|
|||||||
"""Permission guard (D-7, plan step 1.5): nothing reads v1 perm_* attributes any more.
|
"""Permission guard (D-7, plan step 1.5): nothing reads v1 perm_* attributes any more.
|
||||||
|
|
||||||
Permissions are keys checked with core.access (holds/can/require). The only file that
|
Permissions are keys checked with core.access (holds/can/require). The v1 projection
|
||||||
knows the 13 v1 booleans is core/access/legacy.py (temporary projection for the current
|
(core/access/legacy.py) is gone since step 2.99; only migrations still name the columns.
|
||||||
frontends). The UserOut schema declares them as output fields, which isn't a read.
|
|
||||||
"""
|
"""
|
||||||
import ast
|
import ast
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
BACKEND = Path(__file__).resolve().parents[2]
|
BACKEND = Path(__file__).resolve().parents[2]
|
||||||
ALLOWED = {"core/access/legacy.py"}
|
ALLOWED: set[str] = set()
|
||||||
|
|
||||||
|
|
||||||
def test_no_perm_attribute_reads():
|
def test_no_perm_attribute_reads():
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ from types import SimpleNamespace
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from core.access.check import AccessContext, can, check, holds
|
from core.access.check import AccessContext, can, check, holds
|
||||||
from core.access.legacy import LEGACY_MAP, project
|
|
||||||
from core.access.templates import role_template
|
from core.access.templates import role_template
|
||||||
from core.errors import XeniaError
|
from core.errors import XeniaError
|
||||||
from core.modules import entitlements as E
|
from core.modules import entitlements as E
|
||||||
@@ -54,7 +53,7 @@ def test_unknown_key_is_a_programming_error(db):
|
|||||||
check(AccessContext(user=_user(role="superadmin")), "no.such.key", db)
|
check(AccessContext(user=_user(role="superadmin")), "no.such.key", db)
|
||||||
|
|
||||||
|
|
||||||
# ── templates + legacy projection ────────────────────────────────────────────
|
# ── templates ────────────────────────────────────────────
|
||||||
|
|
||||||
def test_role_templates_match_v1_defaults():
|
def test_role_templates_match_v1_defaults():
|
||||||
assert "core.settings.manage" in role_template("owner")
|
assert "core.settings.manage" in role_template("owner")
|
||||||
@@ -65,14 +64,6 @@ def test_role_templates_match_v1_defaults():
|
|||||||
assert role_template("custom") == set()
|
assert role_template("custom") == set()
|
||||||
|
|
||||||
|
|
||||||
def test_legacy_projection_round_trip():
|
|
||||||
u = _user(keys=role_template("store_manager"))
|
|
||||||
p = project(u)
|
|
||||||
assert p["perm_access_dashboard"] and p["perm_view_reports"] and not p["perm_manage_settings"]
|
|
||||||
assert set(p) == set(LEGACY_MAP)
|
|
||||||
assert all(project(_user(role="superadmin")).values())
|
|
||||||
|
|
||||||
|
|
||||||
# ── API ──────────────────────────────────────────────────────────────────────
|
# ── API ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def test_waiter_is_denied_manager_endpoint_with_code(client, make_user, login):
|
def test_waiter_is_denied_manager_endpoint_with_code(client, make_user, login):
|
||||||
@@ -82,11 +73,11 @@ def test_waiter_is_denied_manager_endpoint_with_code(client, make_user, login):
|
|||||||
"message": "You don't have permission to do this (core.staff.manage)."}
|
"message": "You don't have permission to do this (core.staff.manage)."}
|
||||||
|
|
||||||
|
|
||||||
def test_userout_carries_keys_and_legacy_booleans(client, make_user, login):
|
def test_userout_carries_keys_only(client, make_user, login): # the v1 booleans are gone (2.99)
|
||||||
w = make_user(role="waiter")
|
w = make_user(role="waiter")
|
||||||
me = client.get("/api/auth/me", headers=login(w)).json()
|
me = client.get("/api/auth/me", headers=login(w)).json()
|
||||||
assert "waiter_app.access" in me["permissions"]
|
assert "waiter_app.access" in me["permissions"]
|
||||||
assert me["perm_access_waiter_app"] is True and me["perm_access_dashboard"] is False
|
assert not any(k.startswith("perm_") for k in me)
|
||||||
|
|
||||||
|
|
||||||
def test_staff_permission_api(client, make_user, login):
|
def test_staff_permission_api(client, make_user, login):
|
||||||
@@ -107,9 +98,6 @@ def test_staff_permission_api(client, make_user, login):
|
|||||||
bad = client.put(f"/api/waiters/{w.id}/permissions", headers=h, json={"keys": ["nope.key"]})
|
bad = client.put(f"/api/waiters/{w.id}/permissions", headers=h, json={"keys": ["nope.key"]})
|
||||||
assert bad.status_code == 422 and bad.json()["error"]["code"] == "access.unknown_key"
|
assert bad.status_code == 422 and bad.json()["error"]["code"] == "access.unknown_key"
|
||||||
|
|
||||||
reset = client.put(f"/api/waiters/{w.id}/reset-permissions", headers=h)
|
|
||||||
assert reset.status_code == 200 and set(reset.json()["permissions"]) == role_template("waiter")
|
|
||||||
|
|
||||||
|
|
||||||
def test_cannot_grant_keys_you_dont_hold(client, make_user, login):
|
def test_cannot_grant_keys_you_dont_hold(client, make_user, login):
|
||||||
sm = make_user(role="staff_manager") # can manage staff, can't change settings
|
sm = make_user(role="staff_manager") # can manage staff, can't change settings
|
||||||
@@ -119,16 +107,15 @@ def test_cannot_grant_keys_you_dont_hold(client, make_user, login):
|
|||||||
assert r.status_code == 403 and r.json()["error"]["code"] == "access.cannot_grant"
|
assert r.status_code == 403 and r.json()["error"]["code"] == "access.cannot_grant"
|
||||||
|
|
||||||
|
|
||||||
def test_legacy_toggle_still_works_for_current_manager_ui(client, make_user, login):
|
def test_v1_permission_writes_are_gone(client, make_user, login): # 2.99: keys only, via PUT /{id}/permissions
|
||||||
owner = make_user(role="owner")
|
owner = make_user(role="owner")
|
||||||
w = make_user(role="waiter")
|
w = make_user(role="waiter")
|
||||||
r = client.put(f"/api/waiters/{w.id}/permission", headers=login(owner),
|
h = login(owner)
|
||||||
json={"permission": "perm_view_reports", "value": True})
|
assert client.put(f"/api/waiters/{w.id}/permission", headers=h, json={"permission": "reports.view", "value": True}).status_code in (404, 405)
|
||||||
assert r.status_code == 200
|
assert client.put(f"/api/waiters/{w.id}/reset-permissions", headers=h).status_code in (404, 405)
|
||||||
keys = client.get(f"/api/waiters/{w.id}/permissions", headers=login(owner)).json()["keys"]
|
upd = client.put(f"/api/waiters/{w.id}", headers=h, json={"perm_view_reports": True, "nickname": "N"})
|
||||||
assert {"reports.view", "history.view"} <= set(keys)
|
assert upd.status_code == 200 and upd.json()["nickname"] == "N"
|
||||||
upd = client.put(f"/api/waiters/{w.id}", headers=login(owner), json={"perm_view_reports": False, "nickname": "N"})
|
assert "reports.view" not in client.get(f"/api/waiters/{w.id}/permissions", headers=h).json()["keys"]
|
||||||
assert upd.status_code == 200 and upd.json()["perm_view_reports"] is False and upd.json()["nickname"] == "N"
|
|
||||||
|
|
||||||
|
|
||||||
def test_created_staff_get_role_template(client, make_user, login):
|
def test_created_staff_get_role_template(client, make_user, login):
|
||||||
@@ -155,6 +142,11 @@ def test_0005_copies_flags_to_keys(tmp_path):
|
|||||||
from alembic import command
|
from alembic import command
|
||||||
from sqlalchemy import create_engine, text
|
from sqlalchemy import create_engine, text
|
||||||
from core.schema import alembic_config, upgrade_to_head
|
from core.schema import alembic_config, upgrade_to_head
|
||||||
|
import importlib.util
|
||||||
|
spec = importlib.util.spec_from_file_location("m0005", __import__("pathlib").Path(__file__).resolve().parents[1] / "migrations/versions/0005_permission_keys.py")
|
||||||
|
m0005 = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(m0005)
|
||||||
|
LEGACY_MAP = m0005.FROZEN_MAP # the v1 columns as they were (core/access/legacy.py is gone)
|
||||||
|
|
||||||
eng = create_engine(f"sqlite:///{(tmp_path / 'm.db').as_posix()}")
|
eng = create_engine(f"sqlite:///{(tmp_path / 'm.db').as_posix()}")
|
||||||
with eng.begin() as conn:
|
with eng.begin() as conn:
|
||||||
|
|||||||
@@ -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"})
|
client.put("/api/settings/auth.waiter_login_mode", headers=admin_h, json={"value": "tap"})
|
||||||
w = make_user(role="waiter")
|
w = make_user(role="waiter")
|
||||||
assert err(client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id})) == "auth.mode_needs_device"
|
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
|
||||||
|
|||||||
@@ -162,11 +162,10 @@ def test_expired_site_can_log_in_and_see_license_page_but_not_order(client, make
|
|||||||
from conftest import TEST_PASSWORD
|
from conftest import TEST_PASSWORD
|
||||||
E.set_current(E.compute(None, False, False, NOW, False, problem="expired"), notify=False)
|
E.set_current(E.compute(None, False, False, NOW, False, problem="expired"), notify=False)
|
||||||
m = make_user(role="store_manager")
|
m = make_user(role="store_manager")
|
||||||
r = client.post("/api/auth/login", json={"username": m.username, "password": TEST_PASSWORD})
|
r = client.post("/api/auth/login", json={"client": "manager", "username": m.username, "password": TEST_PASSWORD})
|
||||||
assert r.status_code == 200
|
assert r.status_code == 200
|
||||||
h = {"Authorization": f"Bearer {r.json()['access_token']}"}
|
h = {"Authorization": f"Bearer {r.json()['access_token']}"}
|
||||||
assert client.get("/api/system/status", headers=h).status_code == 200
|
assert client.get("/api/system/status", headers=h).status_code == 200
|
||||||
assert client.get("/api/setup/security-config").status_code == 200
|
|
||||||
boot = client.get("/api/platform/bootstrap", headers=h).json()
|
boot = client.get("/api/platform/bootstrap", headers=h).json()
|
||||||
assert boot["license"] == {"mode": "free", "reason": "expired"}
|
assert boot["license"] == {"mode": "free", "reason": "expired"}
|
||||||
assert "ordering" not in {x["key"] for x in boot["modules"]}
|
assert "ordering" not in {x["key"] for x in boot["modules"]}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from conftest import TEST_PASSWORD
|
|||||||
|
|
||||||
def test_manager_logs_in_and_reads_me(client, make_user):
|
def test_manager_logs_in_and_reads_me(client, make_user):
|
||||||
m = make_user(role="store_manager")
|
m = make_user(role="store_manager")
|
||||||
r = client.post("/api/auth/login", json={"username": m.username, "password": TEST_PASSWORD})
|
r = client.post("/api/auth/login", json={"client": "manager", "username": m.username, "password": TEST_PASSWORD})
|
||||||
assert r.status_code == 200, r.text
|
assert r.status_code == 200, r.text
|
||||||
token = r.json()["access_token"]
|
token = r.json()["access_token"]
|
||||||
me = client.get("/api/auth/me", headers={"Authorization": f"Bearer {token}"})
|
me = client.get("/api/auth/me", headers={"Authorization": f"Bearer {token}"})
|
||||||
@@ -14,7 +14,7 @@ def test_manager_logs_in_and_reads_me(client, make_user):
|
|||||||
|
|
||||||
def test_wrong_password_is_rejected(client, make_user):
|
def test_wrong_password_is_rejected(client, make_user):
|
||||||
m = make_user(role="store_manager")
|
m = make_user(role="store_manager")
|
||||||
r = client.post("/api/auth/login", json={"username": m.username, "password": "nope"})
|
r = client.post("/api/auth/login", json={"client": "manager", "username": m.username, "password": "nope"})
|
||||||
assert r.status_code == 401
|
assert r.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Log download for the manager (plan step 2.6f): list + one day's file, owner-level."""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from core import logging as xlog
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def logs(tmp_path, monkeypatch):
|
||||||
|
(tmp_path / "xenia-2026-11-13.log").write_text("2026-11-13T10:00:00.000Z INFO x [req=- user=- device=-] hello\n", encoding="utf-8")
|
||||||
|
(tmp_path / "xenia-2026-11-14.log").write_text("today\n", encoding="utf-8")
|
||||||
|
(tmp_path / "other.txt").write_text("not a log", encoding="utf-8")
|
||||||
|
monkeypatch.setattr(xlog, "log_dir", lambda: tmp_path)
|
||||||
|
return tmp_path
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_and_download(client, make_user, login, logs):
|
||||||
|
h = login(make_user(role="owner"))
|
||||||
|
rows = client.get("/api/system/logs", headers=h).json()
|
||||||
|
assert [r["date"] for r in rows] == ["2026-11-14", "2026-11-13"] and rows[1]["size"] > 10
|
||||||
|
r = client.get("/api/system/logs/2026-11-13", headers=h)
|
||||||
|
assert r.status_code == 200 and "hello" in r.text
|
||||||
|
assert 'filename="xenia-2026-11-13.log"' in r.headers["content-disposition"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_and_bad_dates(client, make_user, login, logs):
|
||||||
|
h = login(make_user(role="owner"))
|
||||||
|
for d in ("2026-01-01", "..%2Fpos", "x"):
|
||||||
|
r = client.get(f"/api/system/logs/{d}", headers=h)
|
||||||
|
assert r.status_code == 404, (d, r.text)
|
||||||
|
assert client.get("/api/system/logs/2026-01-01", headers=h).json()["error"]["code"] == "system.log_not_found"
|
||||||
|
|
||||||
|
|
||||||
|
def test_needs_settings_permission(client, make_user, login, logs):
|
||||||
|
h = login(make_user(role="staff_manager"))
|
||||||
|
assert client.get("/api/system/logs", headers=h).json()["error"]["code"] == "access.denied"
|
||||||
@@ -24,3 +24,25 @@ def test_every_module_has_texts(lang):
|
|||||||
missing.append(f"{m.key}.limits.{lim.key}")
|
missing.append(f"{m.key}.limits.{lim.key}")
|
||||||
assert missing == []
|
assert missing == []
|
||||||
assert set(texts) == set(registry()), "texts for modules that don't exist"
|
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"
|
||||||
|
|||||||
@@ -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"
|
assert err(client.get("/api/access/overrides", headers=v["waiter_h"])) == "access.denied"
|
||||||
listed = client.get("/api/access/overrides", headers=login(v["manager"])).json()
|
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]["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):
|
def test_token_is_bound_to_its_key(client, db, venue, make_user, login):
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Orders CSV export (KI-008, fixed in platform-v2 cleanup before phase 3)."""
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
|
||||||
|
|
||||||
|
def _rows(r):
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
assert r.headers["content-type"].startswith("text/csv")
|
||||||
|
return list(csv.DictReader(io.StringIO(r.text)))
|
||||||
|
|
||||||
|
|
||||||
|
def test_orders_export_returns_a_csv(client, db, make_user, login):
|
||||||
|
from models.order import Order, OrderItem
|
||||||
|
from models.product import Category, Product
|
||||||
|
waiter = make_user(role="waiter", full_name="Maria W")
|
||||||
|
cat = Category(name="Coffees")
|
||||||
|
db.add(cat)
|
||||||
|
db.flush()
|
||||||
|
prod = Product(name="Freddo", base_price=4.0, primary_category_id=cat.id)
|
||||||
|
db.add(prod)
|
||||||
|
db.flush()
|
||||||
|
order = Order(opened_by=waiter.id, order_type="takeaway")
|
||||||
|
db.add(order)
|
||||||
|
db.flush()
|
||||||
|
db.add_all([OrderItem(order_id=order.id, product_id=prod.id, added_by=waiter.id, quantity=2, unit_price=4.0),
|
||||||
|
OrderItem(order_id=order.id, product_id=prod.id, added_by=waiter.id, quantity=1, unit_price=4.0,
|
||||||
|
price_adjustment=-1.0),
|
||||||
|
OrderItem(order_id=order.id, product_id=prod.id, added_by=waiter.id, quantity=1, unit_price=4.0,
|
||||||
|
status="cancelled")])
|
||||||
|
db.commit()
|
||||||
|
h = login(make_user(role="owner"))
|
||||||
|
rows = _rows(client.get("/api/reports/orders/export", headers=h))
|
||||||
|
assert len(rows) == 1
|
||||||
|
row = rows[0]
|
||||||
|
assert row["id"] == str(order.id) and row["waiter"] == "Maria W" and row["status"] == order.status
|
||||||
|
assert float(row["total"]) == 11.0 # 2×4 + 1×(4−1); the cancelled item doesn't count
|
||||||
|
assert row["opened_at"].endswith(("Z", "+00:00")) # UTC, like the other exports
|
||||||
|
# business_day_id is honoured (the Today page sends it): no order in day 999
|
||||||
|
assert _rows(client.get("/api/reports/orders/export", headers=h, params={"business_day_id": 999})) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_orders_export_empty_still_has_a_header(client, make_user, login):
|
||||||
|
r = client.get("/api/reports/orders/export", headers=login(make_user(role="owner")))
|
||||||
|
assert r.status_code == 200 and r.text.splitlines()[0] == "id,table,waiter,opened_at,closed_at,status,total"
|
||||||
@@ -22,10 +22,11 @@ def admin_h(make_user, login):
|
|||||||
|
|
||||||
# ── manager logins ───────────────────────────────────────────────────────────
|
# ── manager logins ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def test_current_manager_ui_login_keeps_v1_rules(client, make_user):
|
def test_login_needs_client(client, make_user): # the v1 no-`client` path is gone (2.99)
|
||||||
m = make_user(role="store_manager")
|
m = make_user(role="store_manager")
|
||||||
assert client.post("/api/auth/login", json={"username": m.username, "password": TEST_PASSWORD}).status_code == 200
|
r = client.post("/api/auth/login", json={"username": m.username, "password": TEST_PASSWORD})
|
||||||
assert client.post("/api/auth/login", json={"username": m.username, "pin": TEST_PIN}).status_code == 200 # lock screen
|
assert r.status_code == 422 and r.json()["error"]["code"].startswith("validation.")
|
||||||
|
assert client.post("/api/auth/login", json={"client": "manager", "username": m.username, "password": TEST_PASSWORD}).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
def test_manager_password_mode_refuses_pin(client, make_user, admin_h):
|
def test_manager_password_mode_refuses_pin(client, make_user, admin_h):
|
||||||
@@ -46,10 +47,10 @@ def test_manager_none_mode_is_gone(client, admin_h): # D-8
|
|||||||
|
|
||||||
def test_wrong_password_and_wrong_app(client, make_user):
|
def test_wrong_password_and_wrong_app(client, make_user):
|
||||||
m = make_user(role="store_manager")
|
m = make_user(role="store_manager")
|
||||||
r = client.post("/api/auth/login", json={"username": m.username, "password": "nope"})
|
r = client.post("/api/auth/login", json={"client": "manager", "username": m.username, "password": "nope"})
|
||||||
assert r.status_code == 401 and r.json()["error"]["code"] == "auth.invalid_credentials"
|
assert r.status_code == 401 and r.json()["error"]["code"] == "auth.invalid_credentials"
|
||||||
w = make_user(role="waiter")
|
w = make_user(role="waiter")
|
||||||
r = client.post("/api/auth/login", json={"username": w.username, "password": TEST_PASSWORD})
|
r = client.post("/api/auth/login", json={"client": "manager", "username": w.username, "password": TEST_PASSWORD})
|
||||||
assert r.status_code == 403 and r.json()["error"] == {"code": "auth.client_not_allowed", "params": {"client": "manager"},
|
assert r.status_code == 403 and r.json()["error"] == {"code": "auth.client_not_allowed", "params": {"client": "manager"},
|
||||||
"message": "This account can't use the manager app."}
|
"message": "This account can't use the manager app."}
|
||||||
|
|
||||||
@@ -88,7 +89,7 @@ def test_waiter_modes(client, make_user, admin_h):
|
|||||||
|
|
||||||
def test_token_carries_sid_and_logout_ends_it(client, make_user):
|
def test_token_carries_sid_and_logout_ends_it(client, make_user):
|
||||||
m = make_user(role="store_manager")
|
m = make_user(role="store_manager")
|
||||||
h = _bearer(client.post("/api/auth/login", json={"username": m.username, "password": TEST_PASSWORD}))
|
h = _bearer(client.post("/api/auth/login", json={"client": "manager", "username": m.username, "password": TEST_PASSWORD}))
|
||||||
payload = jwt.decode(h["Authorization"][7:], options={"verify_signature": False})
|
payload = jwt.decode(h["Authorization"][7:], options={"verify_signature": False})
|
||||||
assert len(payload["sid"]) == 32
|
assert len(payload["sid"]) == 32
|
||||||
assert client.get("/api/auth/me", headers=h).status_code == 200
|
assert client.get("/api/auth/me", headers=h).status_code == 200
|
||||||
@@ -118,7 +119,7 @@ def test_refuse_new(client, make_user, admin_h):
|
|||||||
def test_single_session_is_per_client(client, make_user, admin_h):
|
def test_single_session_is_per_client(client, make_user, admin_h):
|
||||||
_set(client, admin_h, "auth.single_session_waiter", "end_old")
|
_set(client, admin_h, "auth.single_session_waiter", "end_old")
|
||||||
owner = make_user(role="owner") # owners can use both apps
|
owner = make_user(role="owner") # owners can use both apps
|
||||||
mgr = _bearer(client.post("/api/auth/login", json={"username": owner.username, "password": TEST_PASSWORD}))
|
mgr = _bearer(client.post("/api/auth/login", json={"client": "manager", "username": owner.username, "password": TEST_PASSWORD}))
|
||||||
client.post("/api/auth/login", json={"client": "waiter", "user_id": owner.id, "pin": TEST_PIN})
|
client.post("/api/auth/login", json={"client": "waiter", "user_id": owner.id, "pin": TEST_PIN})
|
||||||
assert client.get("/api/auth/me", headers=mgr).status_code == 200
|
assert client.get("/api/auth/me", headers=mgr).status_code == 200
|
||||||
|
|
||||||
@@ -146,7 +147,7 @@ def test_blocking_a_user_ends_their_sessions(client, make_user, login):
|
|||||||
|
|
||||||
def test_refresh_keeps_the_session(client, make_user):
|
def test_refresh_keeps_the_session(client, make_user):
|
||||||
m = make_user(role="store_manager")
|
m = make_user(role="store_manager")
|
||||||
h = _bearer(client.post("/api/auth/login", json={"username": m.username, "password": TEST_PASSWORD}))
|
h = _bearer(client.post("/api/auth/login", json={"client": "manager", "username": m.username, "password": TEST_PASSWORD}))
|
||||||
new = _bearer(client.post("/api/auth/refresh", headers=h))
|
new = _bearer(client.post("/api/auth/refresh", headers=h))
|
||||||
sid = lambda hh: jwt.decode(hh["Authorization"][7:], options={"verify_signature": False})["sid"] # noqa: E731
|
sid = lambda hh: jwt.decode(hh["Authorization"][7:], options={"verify_signature": False})["sid"] # noqa: E731
|
||||||
assert sid(new) == sid(h)
|
assert sid(new) == sid(h)
|
||||||
@@ -165,6 +166,54 @@ def test_session_survives_cache_loss_like_a_restart(client, make_user):
|
|||||||
keeps the token valid. The real restart is checked in the plan notes."""
|
keeps the token valid. The real restart is checked in the plan notes."""
|
||||||
from core import sessions
|
from core import sessions
|
||||||
m = make_user(role="store_manager")
|
m = make_user(role="store_manager")
|
||||||
h = _bearer(client.post("/api/auth/login", json={"username": m.username, "password": TEST_PASSWORD}))
|
h = _bearer(client.post("/api/auth/login", json={"client": "manager", "username": m.username, "password": TEST_PASSWORD}))
|
||||||
sessions.clear_cache()
|
sessions.clear_cache()
|
||||||
assert client.get("/api/auth/me", headers=h).status_code == 200
|
assert client.get("/api/auth/me", headers=h).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
# ── idle sessions (plan 2.99d, owner decision 2026-11-14) ────────────────────
|
||||||
|
|
||||||
|
def _age(db, days, **flt):
|
||||||
|
from datetime import timedelta
|
||||||
|
from core import sessions
|
||||||
|
from core.timeutil import utcnow
|
||||||
|
from models.session import LoginSession
|
||||||
|
for row in db.query(LoginSession).filter_by(**flt).all():
|
||||||
|
row.last_seen_at = utcnow() - timedelta(days=days)
|
||||||
|
db.commit()
|
||||||
|
sessions.clear_cache()
|
||||||
|
|
||||||
|
|
||||||
|
def test_idle_session_ends_after_14_days_by_default(client, db, make_user):
|
||||||
|
w = make_user(role="waiter")
|
||||||
|
wh = _bearer(client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id, "pin": TEST_PIN}))
|
||||||
|
_age(db, 13, user_id=w.id)
|
||||||
|
assert client.get("/api/auth/me", headers=wh).status_code == 200 # 13 days: still in
|
||||||
|
_age(db, 15, user_id=w.id)
|
||||||
|
r = client.get("/api/auth/me", headers=wh)
|
||||||
|
assert r.status_code == 401 and r.json()["error"]["code"] == "auth.session_ended"
|
||||||
|
from models.session import LoginSession
|
||||||
|
db.expire_all()
|
||||||
|
assert db.query(LoginSession).filter_by(user_id=w.id).one().end_reason == "idle"
|
||||||
|
|
||||||
|
|
||||||
|
def test_signed_in_now_drops_idle_sessions(client, db, make_user, login):
|
||||||
|
owner = make_user(role="owner")
|
||||||
|
w = make_user(role="waiter")
|
||||||
|
client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id, "pin": TEST_PIN})
|
||||||
|
oh = login(owner)
|
||||||
|
_age(db, 20, user_id=w.id)
|
||||||
|
assert all(s["user_id"] != w.id for s in client.get("/api/auth/sessions", headers=oh).json())
|
||||||
|
ended = client.get("/api/auth/sessions?include_ended=true", headers=oh).json()
|
||||||
|
assert next(s for s in ended if s["user_id"] == w.id)["end_reason"] == "idle"
|
||||||
|
|
||||||
|
|
||||||
|
def test_idle_days_setting_and_zero_means_never(client, db, make_user, admin_h):
|
||||||
|
w = make_user(role="waiter")
|
||||||
|
wh = _bearer(client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id, "pin": TEST_PIN}))
|
||||||
|
_set(client, admin_h, "auth.idle_days", "0")
|
||||||
|
_age(db, 400, user_id=w.id)
|
||||||
|
assert client.get("/api/auth/me", headers=wh).status_code == 200
|
||||||
|
_set(client, admin_h, "auth.idle_days", "3")
|
||||||
|
_age(db, 4, user_id=w.id)
|
||||||
|
assert client.get("/api/auth/me", headers=wh).status_code == 401
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""The setup wizard sets the venue language and time zone (plan step 2.6f)."""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from models.settings import PosSettings
|
||||||
|
|
||||||
|
|
||||||
|
def _setting(db, key):
|
||||||
|
row = db.query(PosSettings).filter_by(key=key).first()
|
||||||
|
return row.value if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def test_init_sets_language_and_timezone(client, db):
|
||||||
|
from models.user import User
|
||||||
|
if db.query(User).count():
|
||||||
|
pytest.skip("db has users")
|
||||||
|
bad = client.post("/api/setup/init", json={"username": "boss", "password": "secret1", "language": "xx"})
|
||||||
|
assert bad.json()["error"]["code"] == "validation.unknown_language"
|
||||||
|
bad = client.post("/api/setup/init", json={"username": "boss", "password": "secret1", "timezone": "Mars/Base"})
|
||||||
|
assert bad.json()["error"]["code"] == "validation.unknown_timezone"
|
||||||
|
r = client.post("/api/setup/init", json={"username": "boss", "password": "secret1", "language": "el",
|
||||||
|
"timezone": "Europe/Berlin"})
|
||||||
|
assert r.status_code in (200, 201), r.text
|
||||||
|
db.expire_all()
|
||||||
|
assert _setting(db, "venue.language") == "el" and _setting(db, "venue.timezone") == "Europe/Berlin"
|
||||||
|
# starter content in the chosen language (KI-007)
|
||||||
|
from models.flag import TableFlagDef
|
||||||
|
from models.message import QuickMessageTemplate
|
||||||
|
flags = db.query(TableFlagDef).order_by(TableFlagDef.sort_order).all()
|
||||||
|
assert len(flags) == 10 and flags[0].name == "Χρειάζεται καθάρισμα" and flags[0].emoji == "🧹" and flags[0].is_active
|
||||||
|
assert db.query(QuickMessageTemplate).count() == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_starter_content_in_english_and_only_once(db):
|
||||||
|
from models.flag import TableFlagDef
|
||||||
|
from models.message import QuickMessageTemplate
|
||||||
|
from services.defaults import seed_starter_content
|
||||||
|
assert seed_starter_content(db, "en") == {"flags": 10, "quick_messages": 5}
|
||||||
|
db.flush()
|
||||||
|
assert db.query(QuickMessageTemplate).order_by(QuickMessageTemplate.sort_order).first().body == "I need you now"
|
||||||
|
assert seed_starter_content(db, "el") == {"flags": 0, "quick_messages": 0} # existing rows: nothing added
|
||||||
|
assert db.query(TableFlagDef).count() == 10
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
// ESLint for the manager (plan step 2.99b): the waiter's rules (React Hooks 7, react-refresh).
|
||||||
|
// `npm run lint` checks the code written or converted in platform v2 (the list in V2 below).
|
||||||
|
// Older pages break these rules in places (e.g. setState in effects); phase 6 adds each page
|
||||||
|
// to V2 as it converts it. `npx eslint src` shows everything.
|
||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
|
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist', 'dev-dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{js,jsx}'],
|
||||||
|
extends: [
|
||||||
|
js.configs.recommended,
|
||||||
|
reactHooks.configs.flat.recommended,
|
||||||
|
reactRefresh.configs.vite,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
ecmaFeatures: { jsx: true },
|
||||||
|
sourceType: 'module',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
|
||||||
|
// The v2 pages load their data with `useEffect(() => { load() }, [load])` (setState after
|
||||||
|
// a fetch). A warning until phase 6 moves page loading to react-query (already a dependency).
|
||||||
|
'react-hooks/set-state-in-effect': 'warn',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['tests/**/*.mjs', '*.config.js'],
|
||||||
|
languageOptions: { globals: globals.node },
|
||||||
|
},
|
||||||
|
])
|
||||||
@@ -6,32 +6,39 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"test": "node --test \"tests/*.test.mjs\"",
|
||||||
|
"lint": "eslint eslint.config.js tests src/shell src/live src/pages/platform src/pages/staff src/pages/Settings/sections src/pages/LoginPage.jsx src/components/NotificationBell.jsx src/components/UserMenuButton.jsx src/pages/reports/operations/LogsPanel.jsx src/api/client.js src/store/authStore.js src/main.jsx"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tanstack/react-query": "^5.62.0",
|
"@tanstack/react-query": "^5.107.1",
|
||||||
"@xenia/access": "^0.0.0",
|
"@xenia/access": "^0.0.0",
|
||||||
"@xenia/api": "^0.0.0",
|
"@xenia/api": "^0.0.0",
|
||||||
"@xenia/i18n": "^0.0.0",
|
"@xenia/i18n": "^0.0.0",
|
||||||
"@xenia/ui": "^0.0.0",
|
"@xenia/ui": "^0.0.0",
|
||||||
"axios": "^1.7.9",
|
"axios": "^1.21.1",
|
||||||
"lucide-react": "^1.14.0",
|
"lucide-react": "^1.73.0",
|
||||||
"qrcode.react": "^4.2.0",
|
"qrcode.react": "^4.2.0",
|
||||||
"react": "^19.2.5",
|
"react": "^19.3.1",
|
||||||
"react-dom": "^19.2.5",
|
"react-dom": "^19.3.1",
|
||||||
"react-hot-toast": "^2.4.1",
|
"react-hot-toast": "^2.6.1",
|
||||||
"react-is": "^19.2.5",
|
"react-is": "^19.3.1",
|
||||||
"react-router-dom": "^7.14.1",
|
"react-router-dom": "^7.18.5",
|
||||||
"recharts": "^3.8.1",
|
"recharts": "^3.10.1",
|
||||||
"zustand": "^5.0.2"
|
"zustand": "^5.1.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/react": "^19.2.14",
|
"@eslint/js": "^9.39.5",
|
||||||
"@types/react-dom": "^19.2.3",
|
"@types/react": "^19.3.0",
|
||||||
"@vitejs/plugin-react": "^6.0.1",
|
"@types/react-dom": "^19.3.0",
|
||||||
"autoprefixer": "^10.4.20",
|
"@vitejs/plugin-react": "^6.3.0",
|
||||||
"postcss": "^8.4.49",
|
"autoprefixer": "^10.6.2",
|
||||||
|
"eslint": "^9.39.5",
|
||||||
|
"eslint-plugin-react-hooks": "^7.1.1",
|
||||||
|
"eslint-plugin-react-refresh": "^0.5.7",
|
||||||
|
"globals": "^17.14.0",
|
||||||
|
"postcss": "^8.5.33",
|
||||||
"tailwindcss": "^3.4.16",
|
"tailwindcss": "^3.4.16",
|
||||||
"vite": "^8.0.9"
|
"vite": "^8.3.8"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import RouteGuard from './shell/RouteGuard'
|
|||||||
import { createI18n } from '@xenia/i18n'
|
import { createI18n } from '@xenia/i18n'
|
||||||
import useAuthStore from './store/authStore'
|
import useAuthStore from './store/authStore'
|
||||||
import AppLayout from './layouts/AppLayout'
|
import AppLayout from './layouts/AppLayout'
|
||||||
|
import LiveProvider from './live/LiveProvider'
|
||||||
import client from './api/client'
|
import client from './api/client'
|
||||||
|
|
||||||
// Auth / setup
|
// Auth / setup
|
||||||
@@ -32,6 +33,8 @@ import TabsPage from './pages/financials/TabsPage'
|
|||||||
import ProductsPage from './pages/Management/ProductsPage'
|
import ProductsPage from './pages/Management/ProductsPage'
|
||||||
import TablesConfigPage from './pages/Management/TablesConfigPage'
|
import TablesConfigPage from './pages/Management/TablesConfigPage'
|
||||||
import StaffPage from './pages/Management/StaffPage'
|
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 ManagementSchedulePage from './pages/Management/SchedulePage'
|
||||||
import PrepZonesConfigPage from './pages/Management/PrepZonesConfigPage'
|
import PrepZonesConfigPage from './pages/Management/PrepZonesConfigPage'
|
||||||
import PricingPage from './pages/Management/PricingPage'
|
import PricingPage from './pages/Management/PricingPage'
|
||||||
@@ -53,6 +56,7 @@ import MiscPage from './pages/reports/MiscPage'
|
|||||||
// Other
|
// Other
|
||||||
import { AppsPage, IntegrationsPage } from './pages/platform/ModulesPage'
|
import { AppsPage, IntegrationsPage } from './pages/platform/ModulesPage'
|
||||||
import LicensePage from './pages/platform/LicensePage'
|
import LicensePage from './pages/platform/LicensePage'
|
||||||
|
import DevicesPage from './pages/platform/DevicesPage'
|
||||||
import PhonePage from './pages/PhonePage'
|
import PhonePage from './pages/PhonePage'
|
||||||
import SettingsPage from './pages/Settings/SettingsPage'
|
import SettingsPage from './pages/Settings/SettingsPage'
|
||||||
import NotesPage from './pages/NotesPage'
|
import NotesPage from './pages/NotesPage'
|
||||||
@@ -138,7 +142,7 @@ export default function App() {
|
|||||||
<Route path="/login" element={<SetupGuard><LoginPage /></SetupGuard>} />
|
<Route path="/login" element={<SetupGuard><LoginPage /></SetupGuard>} />
|
||||||
<Route path="/kds" element={<RequireAuth><RouteGuard><KdsPage /></RouteGuard></RequireAuth>} />
|
<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 />} />
|
<Route index element={<Navigate to="/dashboard" replace />} />
|
||||||
|
|
||||||
{/* ── Operation ── */}
|
{/* ── Operation ── */}
|
||||||
@@ -159,6 +163,8 @@ export default function App() {
|
|||||||
<Route path="management/products" element={<ProductsPage />} />
|
<Route path="management/products" element={<ProductsPage />} />
|
||||||
<Route path="management/tables" element={<TablesConfigPage />} />
|
<Route path="management/tables" element={<TablesConfigPage />} />
|
||||||
<Route path="management/staff" element={<StaffPage />} />
|
<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/schedule" element={<ManagementSchedulePage />} />
|
||||||
<Route path="management/prep-zones" element={<PrepZonesConfigPage />} />
|
<Route path="management/prep-zones" element={<PrepZonesConfigPage />} />
|
||||||
<Route path="management/pricing" element={<PricingPage />} />
|
<Route path="management/pricing" element={<PricingPage />} />
|
||||||
@@ -181,6 +187,7 @@ export default function App() {
|
|||||||
<Route path="apps" element={<AppsPage />} />
|
<Route path="apps" element={<AppsPage />} />
|
||||||
<Route path="integrations" element={<IntegrationsPage />} />
|
<Route path="integrations" element={<IntegrationsPage />} />
|
||||||
<Route path="license" element={<LicensePage />} />
|
<Route path="license" element={<LicensePage />} />
|
||||||
|
<Route path="devices" element={<DevicesPage />} />
|
||||||
<Route path="apps/phone" element={<PhonePage />} />
|
<Route path="apps/phone" element={<PhonePage />} />
|
||||||
<Route path="settings" element={<SettingsPage />} />
|
<Route path="settings" element={<SettingsPage />} />
|
||||||
<Route path="notes" element={<NotesPage />} />
|
<Route path="notes" element={<NotesPage />} />
|
||||||
|
|||||||
@@ -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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { Outlet, useNavigate, useLocation } from 'react-router-dom'
|
import { Outlet, useNavigate, useLocation } from 'react-router-dom'
|
||||||
import { useState, useEffect, useRef, createContext } from 'react'
|
import { useState, useEffect, useRef, createContext } from 'react'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
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 Sidebar from '../components/Sidebar'
|
||||||
import useAuthStore from '../store/authStore'
|
import useAuthStore from '../store/authStore'
|
||||||
import client from '../api/client'
|
import client from '../api/client'
|
||||||
@@ -271,13 +272,8 @@ export default function AppLayout() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Notifications (placeholder) */}
|
{/* Platform notifications (2.6f) */}
|
||||||
<button
|
<NotificationBell />
|
||||||
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>
|
|
||||||
|
|
||||||
{/* Divider */}
|
{/* Divider */}
|
||||||
<div className="h-5 w-px bg-slate-200" />
|
<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>
|
||||||
|
}
|
||||||
@@ -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,6 +5,11 @@ import { Toaster } from 'react-hot-toast'
|
|||||||
import App from './App.jsx'
|
import App from './App.jsx'
|
||||||
import '@xenia/ui/styles.css' // shared tokens + component styles (.x-*), no global rules
|
import '@xenia/ui/styles.css' // shared tokens + component styles (.x-*), no global rules
|
||||||
import './index.css'
|
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({
|
const queryClient = new QueryClient({
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||||
import useAuthStore from '../store/authStore'
|
import { useLiveEvent } from '../live/useLiveEvent'
|
||||||
import {
|
import {
|
||||||
getIncomingOrders,
|
getIncomingOrders,
|
||||||
getActiveOrders,
|
getActiveOrders,
|
||||||
@@ -236,7 +236,6 @@ export default function OnlineOrdersPage() {
|
|||||||
const [history, setHistory] = useState([])
|
const [history, setHistory] = useState([])
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const [error, setError] = useState(null)
|
const [error, setError] = useState(null)
|
||||||
const token = useAuthStore(s => s.token)
|
|
||||||
const pollRef = useRef(null)
|
const pollRef = useRef(null)
|
||||||
|
|
||||||
const fetchAll = useCallback(async () => {
|
const fetchAll = useCallback(async () => {
|
||||||
@@ -265,20 +264,11 @@ export default function OnlineOrdersPage() {
|
|||||||
return () => clearInterval(pollRef.current)
|
return () => clearInterval(pollRef.current)
|
||||||
}, [fetchAll])
|
}, [fetchAll])
|
||||||
|
|
||||||
// SSE listener — refetch on online_order_received or online_order_updated
|
// Live: refetch on the WebSocket events (KI-010: this listened on /api/stream, which never
|
||||||
useEffect(() => {
|
// existed). 'ready' = after a reconnect; the 20 s polling above stays as a fallback.
|
||||||
if (!token) return
|
useLiveEvent('online_order_received', fetchAll)
|
||||||
const es = new EventSource(`/api/stream?token=${encodeURIComponent(token)}`)
|
useLiveEvent('online_order_updated', fetchAll)
|
||||||
es.onmessage = (e) => {
|
useLiveEvent('ready', fetchAll)
|
||||||
try {
|
|
||||||
const { type } = JSON.parse(e.data)
|
|
||||||
if (type === 'online_order_received' || type === 'online_order_updated') {
|
|
||||||
fetchAll()
|
|
||||||
}
|
|
||||||
} catch { /* ignore malformed frames */ }
|
|
||||||
}
|
|
||||||
return () => es.close()
|
|
||||||
}, [token, fetchAll])
|
|
||||||
|
|
||||||
async function handleAction(action, orderId, extra) {
|
async function handleAction(action, orderId, extra) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
|
import { useTranslation } from '@xenia/i18n'
|
||||||
|
import VenueSettings from './sections/VenueSettings'
|
||||||
import AppInfoTab from './tabs/AppInfoTab'
|
import AppInfoTab from './tabs/AppInfoTab'
|
||||||
import ColoursTab from './tabs/ColoursTab'
|
import ColoursTab from './tabs/ColoursTab'
|
||||||
import OperationTab from './tabs/OperationTab'
|
import OperationTab from './tabs/OperationTab'
|
||||||
@@ -8,24 +10,19 @@ import DevelopmentTab from './tabs/DevelopmentTab'
|
|||||||
import FiscalTab from './tabs/FiscalTab'
|
import FiscalTab from './tabs/FiscalTab'
|
||||||
import { TabGroup } from '../../ui/Tabs'
|
import { TabGroup } from '../../ui/Tabs'
|
||||||
|
|
||||||
const TABS = [
|
const TABS = ['app-info', 'venue', 'security', 'operation', 'colours', 'print-fonts', 'fiscal', 'development']
|
||||||
{ id: 'app-info', label: 'Γενικά' },
|
|
||||||
{ id: 'security', label: 'Ασφάλεια' },
|
|
||||||
{ id: 'operation', label: 'Λειτουργία' },
|
|
||||||
{ id: 'colours', label: 'Εμφάνιση' },
|
|
||||||
{ id: 'print-fonts', label: 'Εκτύπωση' },
|
|
||||||
{ id: 'fiscal', label: 'Ταμειακή' },
|
|
||||||
{ id: 'development', label: 'Developer' },
|
|
||||||
]
|
|
||||||
|
|
||||||
export default function SettingsPage() {
|
export default function SettingsPage() {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
const [activeTab, setActiveTab] = useState('app-info')
|
const [activeTab, setActiveTab] = useState('app-info')
|
||||||
|
const tabs = TABS.map(id => ({ id, label: t(`settings.tabs.${id}`) }))
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-full min-h-0">
|
<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">
|
<div className="flex-1 overflow-y-auto p-6">
|
||||||
{activeTab === 'app-info' && <AppInfoTab />}
|
{activeTab === 'app-info' && <AppInfoTab />}
|
||||||
|
{activeTab === 'venue' && <div className="max-w-3xl"><VenueSettings /></div>}
|
||||||
{activeTab === 'security' && <SecurityTab />}
|
{activeTab === 'security' && <SecurityTab />}
|
||||||
{activeTab === 'operation' && <OperationTab />}
|
{activeTab === 'operation' && <OperationTab />}
|
||||||
{activeTab === 'colours' && <ColoursTab />}
|
{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,70 @@
|
|||||||
|
// 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, security.autofill_username (the sign-in page) and
|
||||||
|
// auth.idle_days (sign out after N days without use, 0 = never; owner decision 2026-11-14, 2.99d).
|
||||||
|
// 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']
|
||||||
|
const IDLE_DAYS = ['7', '14', '30', '60', '90', '0']
|
||||||
|
|
||||||
|
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()
|
||||||
|
const idIdle = 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')
|
||||||
|
const idle = s.get('auth.idle_days', '14')
|
||||||
|
const idleOptions = (IDLE_DAYS.includes(idle) ? IDLE_DAYS : [...IDLE_DAYS.slice(0, -1), idle, '0']) // keep a value set elsewhere
|
||||||
|
.map(d => ({ value: d, label: d === '0' ? t('settings.signIn.idleNever') : t('settings.signIn.idleDays', { count: Number(d) }) }))
|
||||||
|
|
||||||
|
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>
|
||||||
|
<SettingRow label={t('settings.signIn.idle')} htmlFor={idIdle} hint={t('settings.signIn.idleHint')}>
|
||||||
|
{select('auth.idle_days', '14', idleOptions, idIdle)}
|
||||||
|
</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 React, { useState, useEffect, useRef, useCallback } from 'react'
|
||||||
|
import PrintAlertSetting from '../sections/PrintAlertSetting'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import toast from 'react-hot-toast'
|
import toast from 'react-hot-toast'
|
||||||
import client from '../../../api/client'
|
import client from '../../../api/client'
|
||||||
@@ -1115,6 +1116,7 @@ export default function PrintFontsTab() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
|
||||||
|
<PrintAlertSetting />
|
||||||
|
|
||||||
{/* 1. Printers */}
|
{/* 1. Printers */}
|
||||||
<PrintersSection />
|
<PrintersSection />
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import toast from 'react-hot-toast'
|
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 client from '../../../api/client'
|
||||||
|
import SignInSettings from '../sections/SignInSettings'
|
||||||
import { PANEL_CLASS } from '../../../ui/tokens'
|
import { PANEL_CLASS } from '../../../ui/tokens'
|
||||||
import Button from '../../../ui/Button'
|
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 }) {
|
function TimeSelect({ value, onChange, disabled }) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<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 autoLock = get('security.auto_lock', 'false') === 'true'
|
||||||
const autoLockSecs = get('security.auto_lock_seconds', '300')
|
const autoLockSecs = get('security.auto_lock_seconds', '300')
|
||||||
const autoLogout = get('security.auto_logout', 'false') === 'true'
|
const autoLogout = get('security.auto_logout', 'false') === 'true'
|
||||||
@@ -300,46 +277,8 @@ export default function SecurityTab() {
|
|||||||
return (
|
return (
|
||||||
<div className="space-y-5">
|
<div className="space-y-5">
|
||||||
|
|
||||||
{/* ── Μέθοδος σύνδεσης ─────────────────────────────────────────────── */}
|
{/* Sign-in (2.6f): the v2 settings auth.* replace the v1 security.login_method card */}
|
||||||
<SectionCard
|
<SignInSettings />
|
||||||
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>
|
|
||||||
|
|
||||||
{/* ── Αυτόματο κλείδωμα ────────────────────────────────────────────── */}
|
{/* ── Αυτόματο κλείδωμα ────────────────────────────────────────────── */}
|
||||||
<SectionCard
|
<SectionCard
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { useState, useEffect, useRef } from 'react'
|
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 { useNavigate } from 'react-router-dom'
|
||||||
import {
|
import {
|
||||||
ArrowRight, User, Mail, Lock, Building2, Coffee,
|
ArrowRight, User, Mail, Lock, Building2, Coffee,
|
||||||
@@ -266,6 +268,7 @@ function StepAccount({ data, onChange, onNext, onBack }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function StepVenue({ data, onChange, onNext, onBack }) {
|
function StepVenue({ data, onChange, onNext, onBack }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
const [errors, setErrors] = useState({})
|
const [errors, setErrors] = useState({})
|
||||||
|
|
||||||
function toggleType(id) {
|
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>}
|
{errors.venueType && <p className="mt-1 text-[12px] text-rose-500">{errors.venueType}</p>}
|
||||||
</div>
|
</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>
|
<div>
|
||||||
<p className="text-[12px] font-medium text-slate-500 uppercase tracking-wider mb-2">Venue name</p>
|
<p className="text-[12px] font-medium text-slate-500 uppercase tracking-wider mb-2">Venue name</p>
|
||||||
<LabelledInput
|
<LabelledInput
|
||||||
@@ -424,7 +447,12 @@ export default function SetupWizard() {
|
|||||||
const [account, setAccount] = useState({
|
const [account, setAccount] = useState({
|
||||||
username: '', fullName: '', email: '', password: '', confirm: '',
|
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('')
|
const [pin, setPin] = useState('')
|
||||||
|
|
||||||
function updateAccount(key, value) {
|
function updateAccount(key, value) {
|
||||||
@@ -445,6 +473,8 @@ export default function SetupWizard() {
|
|||||||
full_name: account.fullName.trim(),
|
full_name: account.fullName.trim(),
|
||||||
venue_type: venue.venueTypes.join(','),
|
venue_type: venue.venueTypes.join(','),
|
||||||
venue_name: venue.venueName.trim(),
|
venue_name: venue.venueName.trim(),
|
||||||
|
language: venue.language,
|
||||||
|
timezone: venue.timezone,
|
||||||
pin: pin.length >= 4 ? pin : undefined,
|
pin: pin.length >= 4 ? pin : undefined,
|
||||||
})
|
})
|
||||||
navigate('/login', { replace: true })
|
navigate('/login', { replace: true })
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ import toast from 'react-hot-toast'
|
|||||||
import client from '../api/client'
|
import client from '../api/client'
|
||||||
import { ConfirmModal } from '../ui/Modal'
|
import { ConfirmModal } from '../ui/Modal'
|
||||||
import Button from '../ui/Button'
|
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) ───────────────────────────────
|
// ── Role definitions (mirrors backend roles.py) ───────────────────────────────
|
||||||
export const ALL_ROLES = [
|
export const ALL_ROLES = [
|
||||||
@@ -22,26 +25,6 @@ export const ALL_ROLES = [
|
|||||||
|
|
||||||
const ROLE_MAP = Object.fromEntries(ALL_ROLES.map(r => [r.value, r]))
|
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 ─────────────────────────────────────────────────────────────
|
// ── Avatar helpers ─────────────────────────────────────────────────────────────
|
||||||
function avatarColor(name) {
|
function avatarColor(name) {
|
||||||
const palette = ['#3758c9', '#7a44c9', '#2f9e5e', '#d94b26', '#8a6d2b', '#0d7a8a', '#c93775']
|
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 ───────────────────────────────────────────────────────────
|
// ── 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 [open, setOpen] = useState(false)
|
||||||
const ref = useRef(null)
|
const ref = useRef(null)
|
||||||
|
|
||||||
@@ -177,7 +109,7 @@ function ActionsMenu({ member, onEdit, onZones, onResetPin, onBlock, onDelete, o
|
|||||||
{ label: 'Επεξεργασία', icon: editIcon, onClick: onEdit },
|
{ label: 'Επεξεργασία', icon: editIcon, onClick: onEdit },
|
||||||
{ label: 'Πρόσβαση σε Ζώνες', icon: zonesIcon, onClick: onZones },
|
{ label: 'Πρόσβαση σε Ζώνες', icon: zonesIcon, onClick: onZones },
|
||||||
{ label: 'Επαναφορά PIN', icon: pinIcon, onClick: onResetPin },
|
{ 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: member.is_active ? 'Μπλοκάρισμα' : 'Ξεμπλοκάρισμα', icon: blockIcon, onClick: onBlock, color: member.is_active ? '#f97316' : '#22c55e' },
|
||||||
!isSuperadmin && { label: 'Διαγραφή', icon: trashIcon, onClick: onDelete, color: '#ef4444' },
|
!isSuperadmin && { label: 'Διαγραφή', icon: trashIcon, onClick: onDelete, color: '#ef4444' },
|
||||||
].filter(Boolean)
|
].filter(Boolean)
|
||||||
@@ -331,6 +263,8 @@ export default function StaffPage() {
|
|||||||
const [editModal, setEditModal] = useState(null)
|
const [editModal, setEditModal] = useState(null)
|
||||||
const [editForm, setEditForm] = useState({ username: '', full_name: '', nickname: '', mobile_phone: '', email: '', note: '', role: 'waiter', hourly_rate: '' })
|
const [editForm, setEditForm] = useState({ username: '', full_name: '', nickname: '', mobile_phone: '', email: '', note: '', role: 'waiter', hourly_rate: '' })
|
||||||
const [filterRole, setFilterRole] = useState('all')
|
const [filterRole, setFilterRole] = useState('all')
|
||||||
|
const [permEditor, setPermEditor] = useState(null)
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
const avatarInputRef = useRef(null)
|
const avatarInputRef = useRef(null)
|
||||||
const newAvatarInputRef = useRef(null)
|
const newAvatarInputRef = useRef(null)
|
||||||
|
|
||||||
@@ -338,6 +272,10 @@ export default function StaffPage() {
|
|||||||
queryKey: ['staff'],
|
queryKey: ['staff'],
|
||||||
queryFn: () => client.get('/api/waiters/').then(r => r.data),
|
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({
|
const { data: groups = [] } = useQuery({
|
||||||
queryKey: ['table-groups'],
|
queryKey: ['table-groups'],
|
||||||
queryFn: () => client.get('/api/tables/groups').then(r => r.data),
|
queryFn: () => client.get('/api/tables/groups').then(r => r.data),
|
||||||
@@ -402,17 +340,6 @@ export default function StaffPage() {
|
|||||||
onError: () => toast.error('Σφάλμα'),
|
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>
|
if (isLoading) return <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
|
||||||
|
|
||||||
function openEdit(m) {
|
function openEdit(m) {
|
||||||
@@ -436,13 +363,6 @@ export default function StaffPage() {
|
|||||||
|
|
||||||
const filtered = filterRole === 'all' ? staff : staff.filter(m => m.role === filterRole)
|
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 (
|
return (
|
||||||
<div className="flex flex-col h-full min-h-0">
|
<div className="flex flex-col h-full min-h-0">
|
||||||
{/* ── Header bar ── */}
|
{/* ── Header bar ── */}
|
||||||
@@ -487,47 +407,19 @@ export default function StaffPage() {
|
|||||||
<colgroup>
|
<colgroup>
|
||||||
<col style={{ width: 220, minWidth: 220 }} />
|
<col style={{ width: 220, minWidth: 220 }} />
|
||||||
<col style={{ width: 90, minWidth: 90 }} />
|
<col style={{ width: 90, minWidth: 90 }} />
|
||||||
{PERM_COLUMNS.map(c => (
|
<col style={{ width: 260, minWidth: 200 }} />
|
||||||
<col key={c.key} style={{ width: 58, minWidth: 54 }} />
|
|
||||||
))}
|
|
||||||
<col style={{ width: 120, minWidth: 110 }} />
|
<col style={{ width: 120, minWidth: 110 }} />
|
||||||
</colgroup>
|
</colgroup>
|
||||||
<thead>
|
<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 */}
|
{/* Column label row */}
|
||||||
<tr style={{ borderBottom: '2px solid #e5e7eb', background: '#f9fafb' }}>
|
<tr style={{ borderBottom: '2px solid #e5e7eb', background: '#f9fafb' }}>
|
||||||
<th style={{ ...thBase, textAlign: 'left', padding: '6px 16px', fontWeight: 600, color: '#374151' }}>
|
<th style={{ ...thBase, textAlign: 'left', padding: '6px 16px', fontWeight: 600, color: '#374151' }}>
|
||||||
Εργαζόμενος
|
Εργαζόμενος
|
||||||
</th>
|
</th>
|
||||||
<th style={{ ...thBase, textAlign: 'center', color: '#6b7280', fontWeight: 500 }}>Κατάσταση</th>
|
<th style={{ ...thBase, textAlign: 'center', color: '#6b7280', fontWeight: 500 }}>Κατάσταση</th>
|
||||||
{PERM_COLUMNS.map((c, i) => (
|
<th style={{ ...thBase, textAlign: 'left', padding: '6px 12px', color: '#6b7280', fontWeight: 500 }}>
|
||||||
<th key={c.key} style={{
|
{t('permissions.column')}
|
||||||
...thBase,
|
</th>
|
||||||
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>
|
|
||||||
))}
|
|
||||||
<th style={{ ...thBase, textAlign: 'right', padding: '6px 12px', color: '#6b7280', fontWeight: 500 }}>
|
<th style={{ ...thBase, textAlign: 'right', padding: '6px 12px', color: '#6b7280', fontWeight: 500 }}>
|
||||||
Ενέργειες
|
Ενέργειες
|
||||||
</th>
|
</th>
|
||||||
@@ -582,23 +474,18 @@ export default function StaffPage() {
|
|||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
{/* Permission toggle cells */}
|
{/* Permissions (2.6e): count + "custom" when they differ from the role */}
|
||||||
{PERM_COLUMNS.map((col, i) => (
|
<td style={{ padding: '0 12px', verticalAlign: 'middle' }} data-testid={`staff-perms-${member.id}`}>
|
||||||
<td key={col.key} style={{
|
<button type="button" onClick={() => setPermEditor(member)}
|
||||||
textAlign: 'center', verticalAlign: 'middle', padding: '0 4px',
|
className="text-left text-label text-ink-2 hover:text-accent-ink inline-flex items-center gap-2">
|
||||||
borderLeft: i === 0 || PERM_COLUMNS[i - 1]?.group !== col.group ? '1px solid #f3f4f6' : undefined,
|
{isSuperadmin
|
||||||
}}>
|
? t('permissions.all')
|
||||||
<div style={{ display: 'flex', justifyContent: 'center' }}>
|
: t('permissions.count', { count: member.permissions?.length || 0 })}
|
||||||
<PermToggle
|
{!isSuperadmin && catalog && differsFromRole(member.permissions || [], catalog.role_templates[member.role] || []) && (
|
||||||
staffId={member.id}
|
<span className="rounded-full px-2 py-0.5 text-caption font-medium bg-warning-soft text-warning-ink">{t('permissions.custom')}</span>
|
||||||
permKey={col.key}
|
)}
|
||||||
value={isSuperadmin ? true : !!member[col.key]}
|
</button>
|
||||||
disabled={isSuperadmin}
|
</td>
|
||||||
onToggle={togglePermission}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{/* Actions cell */}
|
{/* Actions cell */}
|
||||||
<td style={{ textAlign: 'right', padding: '0 12px', verticalAlign: 'middle' }}>
|
<td style={{ textAlign: 'right', padding: '0 12px', verticalAlign: 'middle' }}>
|
||||||
@@ -610,7 +497,8 @@ export default function StaffPage() {
|
|||||||
onResetPin={() => setPinModal(member.id)}
|
onResetPin={() => setPinModal(member.id)}
|
||||||
onBlock={() => toggleBlock.mutate(member.id)}
|
onBlock={() => toggleBlock.mutate(member.id)}
|
||||||
onDelete={() => setConfirmDelete(member.id)}
|
onDelete={() => setConfirmDelete(member.id)}
|
||||||
onResetPerms={() => resetPerms.mutate(member.id)}
|
onPermissions={() => setPermEditor(member)}
|
||||||
|
permissionsLabel={t('permissions.open')}
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -687,6 +575,8 @@ export default function StaffPage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{permEditor && <PermissionEditor member={permEditor} onClose={() => setPermEditor(null)} />}
|
||||||
|
|
||||||
{zoneModal && (
|
{zoneModal && (
|
||||||
<ZoneModal member={zoneModal} groups={groups} onClose={() => setZoneModal(null)} />
|
<ZoneModal member={zoneModal} groups={groups} onClose={() => setZoneModal(null)} />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,327 @@
|
|||||||
|
// Devices page (plan step 2.6d, APPS_PLATFORM D-8, §6.3): screens and terminals paired
|
||||||
|
// with the venue, each running one app. Backend: /api/devices (step 1.8, core.devices.manage).
|
||||||
|
// - Pair: the device shows a 6-character code (POST /api/devices/pair-request on its side);
|
||||||
|
// the manager enters it here with the app, a name, how staff sign in on it and an optional
|
||||||
|
// linked device → POST /api/devices. The license limit per app is shown and enforced
|
||||||
|
// (license.limit_reached).
|
||||||
|
// - Edit (name, sign-in mode, link) → PATCH; change app → POST /reassign (signs out whoever
|
||||||
|
// is on it); remove → POST /revoke (the device goes back to its pairing screen).
|
||||||
|
// Per-app settings (e.g. a KDS's prep zone) arrive with the apps themselves in phase 3.
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
|
import toast from 'react-hot-toast'
|
||||||
|
import { MonitorSmartphone, Plus } from 'lucide-react'
|
||||||
|
import { errorMessage, parseError } from '@xenia/api'
|
||||||
|
import { useTranslation, useFormat } from '@xenia/i18n'
|
||||||
|
import { Button, Dialog, EmptyState, Field, Input, Select, Spinner } from '@xenia/ui'
|
||||||
|
import client from '../../api/client'
|
||||||
|
import { deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode } from './devicesLogic'
|
||||||
|
|
||||||
|
const STATUS_TONE = {
|
||||||
|
online: 'bg-success-soft text-success-ink',
|
||||||
|
offline: 'bg-surface-2 text-ink-2',
|
||||||
|
waiting: 'bg-info-soft text-info-ink',
|
||||||
|
app_off: 'bg-warning-soft text-warning-ink',
|
||||||
|
removed: 'bg-surface-2 text-ink-3',
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DevicesPage() {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const f = useFormat()
|
||||||
|
const [devices, setDevices] = useState(null)
|
||||||
|
const [modules, setModules] = useState(null)
|
||||||
|
const [showRemoved, setShowRemoved] = useState(false)
|
||||||
|
const [error, setError] = useState(null)
|
||||||
|
const [dialog, setDialog] = useState(null) // { kind: 'pair' | 'edit' | 'app' | 'remove', device? }
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const [d, m] = await Promise.all([
|
||||||
|
client.get('/api/devices', { params: { include_revoked: showRemoved } }),
|
||||||
|
client.get('/api/platform/modules'),
|
||||||
|
])
|
||||||
|
setDevices(d.data)
|
||||||
|
setModules(m.data.modules)
|
||||||
|
setError(null)
|
||||||
|
} catch (err) {
|
||||||
|
setError(errorMessage(err, t))
|
||||||
|
}
|
||||||
|
}, [showRemoved, t])
|
||||||
|
|
||||||
|
useEffect(() => { load() }, [load])
|
||||||
|
|
||||||
|
const apps = useMemo(() => (modules || []).filter(m => m.device_app), [modules])
|
||||||
|
const appOn = key => !!apps.find(a => a.key === key)?.effective
|
||||||
|
const usage = useMemo(() => (devices && modules ? deviceUsage(devices, modules) : {}), [devices, modules])
|
||||||
|
const appName = key => t(`modules:${key}.name`, { defaultValue: key })
|
||||||
|
const limitLabel = key => t(`modules:${key}.limits.devices`, { defaultValue: appName(key) })
|
||||||
|
const byId = id => devices?.find(d => d.id === id)
|
||||||
|
|
||||||
|
/** A refusal for one more device of `app`: say it with the app's own words. */
|
||||||
|
const explain = useCallback(err => {
|
||||||
|
const x = parseError(err)
|
||||||
|
if (x.code === 'license.limit_reached') return t('devices.limitReached', { label: limitLabel(x.params.module), max: x.params.max })
|
||||||
|
return errorMessage(err, t)
|
||||||
|
}, [t]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
async function act(fn, okText) {
|
||||||
|
try {
|
||||||
|
await fn()
|
||||||
|
setDialog(null)
|
||||||
|
if (okText) toast.success(okText)
|
||||||
|
await load()
|
||||||
|
return null
|
||||||
|
} catch (err) {
|
||||||
|
return explain(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) return <div className="p-8"><EmptyState title={error} action={<Button variant="secondary" onClick={load}>{t('common:actions.retry')}</Button>} /></div>
|
||||||
|
if (!devices || !modules) return <div className="p-8 flex justify-center"><Spinner /></div>
|
||||||
|
|
||||||
|
const live = devices.filter(d => !d.revoked_at)
|
||||||
|
const signInLabel = d => {
|
||||||
|
const modes = apps.find(a => a.key === d.app_key)?.device_app?.login_modes || []
|
||||||
|
if (d.login_mode || modes.length < 2) return t(`devices.signIn.${d.effective_login_mode}`) // its own choice, or the only one the app has
|
||||||
|
return t('devices.signIn.default', { mode: t(`devices.signIn.${d.effective_login_mode}`) })
|
||||||
|
}
|
||||||
|
const statusText = d => {
|
||||||
|
const s = deviceStatus(d, { appOn: appOn(d.app_key) })
|
||||||
|
if (s === 'offline') return d.last_seen_at ? t('devices.status.offline', { when: f.formatRelative(d.last_seen_at) }) : t('devices.status.offlineNever')
|
||||||
|
if (s === 'removed') return t('devices.status.removed', { when: f.formatRelative(d.revoked_at) })
|
||||||
|
return t(`devices.status.${s}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 lg:p-8 max-w-6xl grid gap-6">
|
||||||
|
<div className="flex flex-wrap items-start gap-4 justify-between">
|
||||||
|
<p className="text-body text-ink-2 max-w-2xl">{t('devices.intro')}</p>
|
||||||
|
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'pair' })}>{t('devices.pair')}</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-2" data-testid="device-usage">
|
||||||
|
{apps.filter(a => a.effective).map(a => {
|
||||||
|
const u = usage[a.key] || { used: 0, max: null }
|
||||||
|
return (
|
||||||
|
<span key={a.key} className={`rounded-full px-3 py-1 text-label ${u.max != null && u.used >= u.max ? 'bg-warning-soft text-warning-ink' : 'bg-surface-2 text-ink-2'}`}>
|
||||||
|
{u.max == null
|
||||||
|
? t('devices.usageUnlimited', { label: limitLabel(a.key), used: u.used })
|
||||||
|
: t('devices.usage', { label: limitLabel(a.key), used: u.used, max: u.max })}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{devices.length === 0
|
||||||
|
? <EmptyState icon={<MonitorSmartphone />} title={t('devices.empty')} description={t('devices.emptyBody')} />
|
||||||
|
: (
|
||||||
|
<div className="bg-surface border border-line rounded-card shadow-raised overflow-x-auto">
|
||||||
|
<table className="w-full text-body" data-testid="devices-table">
|
||||||
|
<thead>
|
||||||
|
<tr className="text-left text-label text-ink-3 border-b border-line">
|
||||||
|
{['device', 'app', 'status', 'signIn', 'linked', 'actions'].map(c => <th key={c} className="px-4 py-2.5 font-medium">{t(`devices.columns.${c}`)}</th>)}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{devices.map(d => {
|
||||||
|
const s = deviceStatus(d, { appOn: appOn(d.app_key) })
|
||||||
|
return (
|
||||||
|
<tr key={d.id} className="border-b border-line last:border-0" data-testid={`device-${d.id}`} data-status={s}>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<div className="font-medium text-ink">{d.name}</div>
|
||||||
|
<div className="text-caption text-ink-3">{f.formatDate(d.paired_at, 'dateMedium')}</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-ink-2">{appName(d.app_key)}</td>
|
||||||
|
<td className="px-4 py-3"><span className={`rounded-full px-2.5 py-0.5 text-caption font-medium ${STATUS_TONE[s]}`}>{statusText(d)}</span></td>
|
||||||
|
<td className="px-4 py-3 text-ink-2">{d.revoked_at ? '—' : signInLabel(d)}</td>
|
||||||
|
<td className="px-4 py-3 text-ink-2">{byId(d.linked_device_id)?.name || '—'}</td>
|
||||||
|
<td className="px-4 py-3 whitespace-nowrap text-right">
|
||||||
|
{!d.revoked_at && (
|
||||||
|
<div className="inline-flex gap-1">
|
||||||
|
<Button size="sm" variant="ghost" onClick={() => setDialog({ kind: 'edit', device: d })}>{t('devices.actions.edit')}</Button>
|
||||||
|
<Button size="sm" variant="ghost" onClick={() => setDialog({ kind: 'app', device: d })}>{t('devices.actions.changeApp')}</Button>
|
||||||
|
<Button size="sm" variant="ghost" className="text-danger-ink" onClick={() => setDialog({ kind: 'remove', device: d })}>{t('devices.actions.remove')}</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</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={showRemoved} onChange={e => setShowRemoved(e.target.checked)} />
|
||||||
|
{t('devices.showRemoved')}
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{dialog?.kind === 'pair' && (
|
||||||
|
<PairDialog apps={apps} usage={usage} devices={live} appName={appName} limitLabel={limitLabel}
|
||||||
|
onClose={() => setDialog(null)}
|
||||||
|
onPair={body => act(() => client.post('/api/devices', body), t('devices.paired', { name: body.name }))} />
|
||||||
|
)}
|
||||||
|
{dialog?.kind === 'edit' && (
|
||||||
|
<EditDialog device={dialog.device} apps={apps} devices={live}
|
||||||
|
onClose={() => setDialog(null)}
|
||||||
|
onSave={body => act(() => client.patch(`/api/devices/${dialog.device.id}`, body), t('devices.saved'))} />
|
||||||
|
)}
|
||||||
|
{dialog?.kind === 'app' && (
|
||||||
|
<ChangeAppDialog device={dialog.device} apps={apps} usage={usage} appName={appName}
|
||||||
|
onClose={() => setDialog(null)}
|
||||||
|
onSave={appKey => act(() => client.post(`/api/devices/${dialog.device.id}/reassign`, { app_key: appKey }), t('devices.saved'))} />
|
||||||
|
)}
|
||||||
|
{dialog?.kind === 'remove' && (
|
||||||
|
<RemoveDialog device={dialog.device} onClose={() => setDialog(null)}
|
||||||
|
onRemove={() => act(() => client.post(`/api/devices/${dialog.device.id}/revoke`))} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function loginModeOptions(app, t) {
|
||||||
|
const modes = app?.device_app?.login_modes || []
|
||||||
|
if (modes.length < 2) return null
|
||||||
|
return [{ value: '', label: t('devices.signIn.defaultPlain') }, ...modes.map(m => ({ value: m, label: t(`devices.signIn.${m}`) }))]
|
||||||
|
}
|
||||||
|
|
||||||
|
function useSubmit(fn) {
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const run = async (...args) => {
|
||||||
|
setBusy(true)
|
||||||
|
setError('')
|
||||||
|
const err = await fn(...args)
|
||||||
|
setBusy(false)
|
||||||
|
if (err) setError(err)
|
||||||
|
}
|
||||||
|
return { busy, error, run }
|
||||||
|
}
|
||||||
|
|
||||||
|
function PairDialog({ apps, usage, devices, appName, limitLabel, onClose, onPair }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const usable = apps.filter(a => a.effective)
|
||||||
|
const [code, setCode] = useState('')
|
||||||
|
const [appKey, setAppKey] = useState(usable.find(a => hasRoom(usage, a.key))?.key || usable[0]?.key || '')
|
||||||
|
const [name, setName] = useState('')
|
||||||
|
const [mode, setMode] = useState('')
|
||||||
|
const [link, setLink] = useState('')
|
||||||
|
const { busy, error, run } = useSubmit(onPair)
|
||||||
|
const app = apps.find(a => a.key === appKey)
|
||||||
|
const full = appKey && !hasRoom(usage, appKey)
|
||||||
|
const modes = loginModeOptions(app, t)
|
||||||
|
const ready = code.length === 6 && appKey && name.trim() && !full
|
||||||
|
|
||||||
|
const submit = e => {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!ready || busy) return
|
||||||
|
run({ code, app_key: appKey, name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null })
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onClose={onClose} title={t('devices.pair')}
|
||||||
|
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button type="submit" form="pair-form" loading={busy} disabled={!ready}>{t('devices.pair')}</Button></>}>
|
||||||
|
{usable.length === 0
|
||||||
|
? <p>{t('devices.form.noApps')}</p>
|
||||||
|
: (
|
||||||
|
<form id="pair-form" onSubmit={submit} className="grid gap-4">
|
||||||
|
<Field label={t('devices.form.code')} hint={t('devices.form.codeHint')}>
|
||||||
|
<Input value={code} onChange={e => setCode(normalizeCode(e.target.value))} autoComplete="off" spellCheck={false}
|
||||||
|
className="font-mono tracking-[0.3em] text-center uppercase" autoFocus />
|
||||||
|
</Field>
|
||||||
|
<Field label={t('devices.form.app')} error={full ? t('devices.form.full', { label: limitLabel(appKey), max: usage[appKey].max }) : undefined}>
|
||||||
|
<Select value={appKey} onChange={e => { setAppKey(e.target.value); setMode('') }}
|
||||||
|
options={usable.map(a => ({ value: a.key, label: appName(a.key) }))} />
|
||||||
|
</Field>
|
||||||
|
<Field label={t('devices.form.name')}>
|
||||||
|
<Input value={name} onChange={e => setName(e.target.value)} placeholder={t('devices.form.namePlaceholder')} maxLength={60} />
|
||||||
|
</Field>
|
||||||
|
{modes && (
|
||||||
|
<Field label={t('devices.form.signIn')}>
|
||||||
|
<Select value={mode} onChange={e => setMode(e.target.value)} options={modes} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
{devices.length > 0 && (
|
||||||
|
<Field label={t('devices.form.link')} hint={t('devices.form.linkHint')}>
|
||||||
|
<Select value={link} onChange={e => setLink(e.target.value)}
|
||||||
|
options={[{ value: '', label: t('devices.form.noLink') }, ...linkTargets(devices).map(d => ({ value: String(d.id), label: d.name }))]} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
{error && <p className="text-label text-danger-ink" role="alert" data-testid="pair-error">{error}</p>}
|
||||||
|
<button type="submit" hidden aria-hidden="true" tabIndex={-1} />
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function EditDialog({ device, apps, devices, onClose, onSave }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const [name, setName] = useState(device.name)
|
||||||
|
const [mode, setMode] = useState(device.login_mode || '')
|
||||||
|
const [link, setLink] = useState(device.linked_device_id ? String(device.linked_device_id) : '')
|
||||||
|
const { busy, error, run } = useSubmit(onSave)
|
||||||
|
const modes = loginModeOptions(apps.find(a => a.key === device.app_key), t)
|
||||||
|
const targets = linkTargets(devices, device.id)
|
||||||
|
|
||||||
|
const submit = e => {
|
||||||
|
e.preventDefault()
|
||||||
|
if (!name.trim() || busy) return
|
||||||
|
run({ name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null })
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onClose={onClose} title={device.name}
|
||||||
|
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button type="submit" form="edit-form" loading={busy}>{t('devices.actions.save')}</Button></>}>
|
||||||
|
<form id="edit-form" onSubmit={submit} className="grid gap-4">
|
||||||
|
<Field label={t('devices.form.name')}>
|
||||||
|
<Input value={name} onChange={e => setName(e.target.value)} maxLength={60} />
|
||||||
|
</Field>
|
||||||
|
{modes && (
|
||||||
|
<Field label={t('devices.form.signIn')}>
|
||||||
|
<Select value={mode} onChange={e => setMode(e.target.value)} options={modes} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
{targets.length > 0 && (
|
||||||
|
<Field label={t('devices.form.link')} hint={t('devices.form.linkHint')}>
|
||||||
|
<Select value={link} onChange={e => setLink(e.target.value)}
|
||||||
|
options={[{ value: '', label: t('devices.form.noLink') }, ...targets.map(d => ({ value: String(d.id), label: d.name }))]} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
|
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
|
||||||
|
<button type="submit" hidden aria-hidden="true" tabIndex={-1} />
|
||||||
|
</form>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChangeAppDialog({ device, apps, usage, appName, onClose, onSave }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const usable = apps.filter(a => a.effective)
|
||||||
|
const [appKey, setAppKey] = useState(device.app_key)
|
||||||
|
const { busy, error, run } = useSubmit(onSave)
|
||||||
|
const full = appKey !== device.app_key && !hasRoom(usage, appKey)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onClose={onClose} title={`${t('devices.actions.changeApp')}: ${device.name}`} description={t('devices.changeAppBody')}
|
||||||
|
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button loading={busy} disabled={appKey === device.app_key || full} onClick={() => run(appKey)}>{t('devices.actions.save')}</Button></>}>
|
||||||
|
<div className="grid gap-4">
|
||||||
|
<Field label={t('devices.form.app')} error={full ? t('devices.form.full', { label: t(`modules:${appKey}.limits.devices`), max: usage[appKey].max }) : undefined}>
|
||||||
|
<Select value={appKey} onChange={e => setAppKey(e.target.value)} options={usable.map(a => ({ value: a.key, label: appName(a.key) }))} />
|
||||||
|
</Field>
|
||||||
|
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
|
||||||
|
</div>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function RemoveDialog({ device, onClose, onRemove }) {
|
||||||
|
const { t } = useTranslation('manager')
|
||||||
|
const { busy, error, run } = useSubmit(onRemove)
|
||||||
|
return (
|
||||||
|
<Dialog open size="sm" onClose={onClose} title={t('devices.removeTitle', { name: device.name })} description={t('devices.removeBody')}
|
||||||
|
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button variant="danger" loading={busy} onClick={() => run()}>{t('devices.actions.remove')}</Button></>}>
|
||||||
|
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// Pure helpers for the Devices page (plan step 2.6d). Unit-tested in manager_dashboard/tests.
|
||||||
|
|
||||||
|
/** Seen within this long = "Online" (the backend writes last_seen_at at most once a minute). */
|
||||||
|
export const ONLINE_WITHIN_MS = 3 * 60 * 1000
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A device's status for the list:
|
||||||
|
* removed revoked
|
||||||
|
* waiting paired here, but the device hasn't picked up its token yet
|
||||||
|
* app_off its app is turned off or not licensed (the device shows "app disabled")
|
||||||
|
* online seen in the last 3 minutes
|
||||||
|
* offline seen before that (or never since pairing)
|
||||||
|
*/
|
||||||
|
export function deviceStatus(d, { appOn = true, now = Date.now() } = {}) {
|
||||||
|
if (d.revoked_at) return 'removed'
|
||||||
|
if (!d.claimed) return 'waiting'
|
||||||
|
if (!appOn) return 'app_off'
|
||||||
|
const seen = d.last_seen_at ? Date.parse(d.last_seen_at) : NaN
|
||||||
|
return Number.isFinite(seen) && now - seen <= ONLINE_WITHIN_MS ? 'online' : 'offline'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pairing codes are typed by people: upper-case, no spaces or dashes, at most 6 characters. */
|
||||||
|
export function normalizeCode(input) {
|
||||||
|
return String(input || '').toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 6)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How many devices of each app are paired (not removed), and the license limit:
|
||||||
|
* { kds: { used: 1, max: 2 }, signage: { used: 0, max: null } } (max null = unlimited)
|
||||||
|
* `modules` = GET /api/platform/modules → modules.
|
||||||
|
*/
|
||||||
|
export function deviceUsage(devices, modules) {
|
||||||
|
const out = {}
|
||||||
|
for (const m of modules) {
|
||||||
|
if (!m.device_app) continue
|
||||||
|
const limit = m.limits.find(l => l.key === 'devices')
|
||||||
|
out[m.key] = { used: 0, max: limit ? limit.value ?? null : null }
|
||||||
|
}
|
||||||
|
for (const d of devices) {
|
||||||
|
if (!d.revoked_at && out[d.app_key]) out[d.app_key].used++
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Is there room for one more device of this app? (when moving a device, it doesn't count against itself) */
|
||||||
|
export function hasRoom(usage, appKey, { moving = false } = {}) {
|
||||||
|
const u = usage[appKey]
|
||||||
|
if (!u || u.max == null) return true
|
||||||
|
return u.used - (moving ? 1 : 0) < u.max
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Devices another device may link to: not itself, not removed. */
|
||||||
|
export function linkTargets(devices, selfId = null) {
|
||||||
|
return devices.filter(d => !d.revoked_at && d.id !== selfId)
|
||||||
|
}
|
||||||
@@ -2,6 +2,9 @@ import { useState } from 'react'
|
|||||||
import { TabBar } from '../../ui/Tabs'
|
import { TabBar } from '../../ui/Tabs'
|
||||||
import PrinterHistory from './operations/PrinterHistory'
|
import PrinterHistory from './operations/PrinterHistory'
|
||||||
import PrinterHealthLog from './operations/PrinterHealthLog'
|
import PrinterHealthLog from './operations/PrinterHealthLog'
|
||||||
|
import LogsPanel from './operations/LogsPanel'
|
||||||
|
import { useCan } from '@xenia/access'
|
||||||
|
import { useTranslation } from '@xenia/i18n'
|
||||||
|
|
||||||
const TABS = [
|
const TABS = [
|
||||||
{ id: 'printer-history', label: 'Ιστορικό Εκτυπωτή', Component: PrinterHistory },
|
{ id: 'printer-history', label: 'Ιστορικό Εκτυπωτή', Component: PrinterHistory },
|
||||||
@@ -9,13 +12,16 @@ const TABS = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
export default function TechnicalPage() {
|
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 [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
|
const { Component } = tab
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-full min-h-0">
|
<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">
|
<div className="flex-1 min-h-0 flex flex-col">
|
||||||
<Component key={active} />
|
<Component key={active} />
|
||||||
</div>
|
</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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -16,7 +16,7 @@ import {
|
|||||||
BookUser, Users, Receipt, CreditCard,
|
BookUser, Users, Receipt, CreditCard,
|
||||||
Package, TableProperties, UserCog, CalendarDays, Trash2, Boxes,
|
Package, TableProperties, UserCog, CalendarDays, Trash2, Boxes,
|
||||||
BarChart2, TrendingUp, Users2, ShoppingCart, Tag, Activity, Printer, ConciergeBell, FileText,
|
BarChart2, TrendingUp, Users2, ShoppingCart, Tag, Activity, Printer, ConciergeBell, FileText,
|
||||||
AppWindow, Settings, CookingPot, StickyNote, Percent, Plug, BadgeCheck,
|
AppWindow, Settings, CookingPot, StickyNote, Percent, Plug, BadgeCheck, MonitorSmartphone, LogIn, ShieldCheck,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
|
|
||||||
const DASH = 'core.dashboard.access'
|
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/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/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/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/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/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' },
|
{ to: '/management/pricing', icon: Percent, label: 'nav.pricing', module: 'pricing', perm: 'catalog.menu.manage' },
|
||||||
@@ -96,6 +98,7 @@ export const NAV = [
|
|||||||
export const NAV_BOTTOM = [
|
export const NAV_BOTTOM = [
|
||||||
{ to: '/apps', icon: AppWindow, label: 'nav.apps', module: 'core', perm: DASH },
|
{ to: '/apps', icon: AppWindow, label: 'nav.apps', module: 'core', perm: DASH },
|
||||||
{ to: '/integrations', icon: Plug, label: 'nav.integrations', module: 'core', perm: DASH },
|
{ to: '/integrations', icon: Plug, label: 'nav.integrations', module: 'core', perm: DASH },
|
||||||
|
{ to: '/devices', icon: MonitorSmartphone, label: 'nav.devices', module: 'core', perm: 'core.devices.manage' },
|
||||||
{ to: '/license', icon: BadgeCheck, label: 'nav.license', module: 'core', perm: DASH },
|
{ to: '/license', icon: BadgeCheck, label: 'nav.license', module: 'core', perm: DASH },
|
||||||
{ to: '/settings', icon: Settings, label: 'nav.settings', module: 'core', perm: 'core.settings.manage' },
|
{ to: '/settings', icon: Settings, label: 'nav.settings', module: 'core', perm: 'core.settings.manage' },
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
// 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 })
|
||||||
|
|
||||||
|
test('module state', () => {
|
||||||
|
assert.equal(moduleState(mod('core', { can_disable: false })), 'always')
|
||||||
|
assert.equal(moduleState(mod('kds', { entitled: false, effective: false })), 'not_licensed')
|
||||||
|
assert.equal(moduleState(mod('kds')), 'on')
|
||||||
|
assert.equal(moduleState(mod('kds', { effective: false })), 'waiting')
|
||||||
|
assert.equal(moduleState(mod('kds', { enabled: false, effective: false })), 'off')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('turning a module off stops what depends on it, directly or not (only those that are on)', () => {
|
||||||
|
const modules = [
|
||||||
|
mod('catalog'), mod('ordering', { depends: ['catalog'] }), mod('kds', { depends: ['ordering'] }),
|
||||||
|
mod('pos_counter', { depends: ['ordering'] }), mod('customer_display', { depends: ['pos_counter'] }),
|
||||||
|
mod('pricing', { depends: ['ordering'], effective: false }), mod('notes'),
|
||||||
|
]
|
||||||
|
assert.deepEqual(stoppedBy('ordering', modules).map(m => m.key).sort(), ['customer_display', 'kds', 'pos_counter'])
|
||||||
|
assert.deepEqual(stoppedBy('notes', modules), [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('device status', () => {
|
||||||
|
const now = Date.parse('2026-11-13T12:00:00Z')
|
||||||
|
const d = { claimed: true, revoked_at: null, last_seen_at: '2026-11-13T11:58:30Z' }
|
||||||
|
assert.equal(deviceStatus(d, { now }), 'online')
|
||||||
|
assert.equal(deviceStatus({ ...d, last_seen_at: '2026-11-13T11:50:00Z' }, { now }), 'offline')
|
||||||
|
assert.equal(deviceStatus({ ...d, last_seen_at: null }, { now }), 'offline')
|
||||||
|
assert.equal(deviceStatus({ ...d, claimed: false }, { now }), 'waiting')
|
||||||
|
assert.equal(deviceStatus(d, { now, appOn: false }), 'app_off')
|
||||||
|
assert.equal(deviceStatus({ ...d, revoked_at: '2026-11-13T11:00:00Z' }, { now }), 'removed')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('pairing codes as typed', () => {
|
||||||
|
assert.equal(normalizeCode(' ab-c d2e '), 'ABCD2E')
|
||||||
|
assert.equal(normalizeCode('k7m9pq2x'), 'K7M9PQ')
|
||||||
|
assert.equal(normalizeCode(null), '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('device usage against the license limit', () => {
|
||||||
|
const modules = [
|
||||||
|
mod('kds', { device_app: {}, limits: [{ key: 'devices', value: 2 }] }),
|
||||||
|
mod('signage', { device_app: {}, limits: [{ key: 'devices', value: null }] }),
|
||||||
|
mod('notes'),
|
||||||
|
]
|
||||||
|
const devices = [
|
||||||
|
{ app_key: 'kds', revoked_at: null }, { app_key: 'kds', revoked_at: '2026-01-01T00:00:00Z' },
|
||||||
|
{ app_key: 'kds', revoked_at: null }, { app_key: 'signage', revoked_at: null },
|
||||||
|
]
|
||||||
|
const usage = deviceUsage(devices, modules)
|
||||||
|
assert.deepEqual(usage, { kds: { used: 2, max: 2 }, signage: { used: 1, max: null } })
|
||||||
|
assert.equal(hasRoom(usage, 'kds'), false)
|
||||||
|
assert.equal(hasRoom(usage, 'kds', { moving: true }), true)
|
||||||
|
assert.equal(hasRoom(usage, 'signage'), true)
|
||||||
|
})
|
||||||
|
|
||||||
|
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)
|
||||||
|
})
|
||||||
Generated
+3894
-4002
File diff suppressed because it is too large
Load Diff
@@ -68,5 +68,8 @@
|
|||||||
"catalog": {
|
"catalog": {
|
||||||
"unknown_category": "Δεν υπάρχει η κατηγορία {{category_id}}.",
|
"unknown_category": "Δεν υπάρχει η κατηγορία {{category_id}}.",
|
||||||
"primary_not_listed": "Η κύρια κατηγορία ({{category_id}}) πρέπει να είναι μία από τις κατηγορίες του προϊόντος."
|
"primary_not_listed": "Η κύρια κατηγορία ({{category_id}}) πρέπει να είναι μία από τις κατηγορίες του προϊόντος."
|
||||||
|
},
|
||||||
|
"system": {
|
||||||
|
"log_not_found": "Δεν υπάρχει αρχείο καταγραφής για {{date}}."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,10 @@
|
|||||||
"kds": "Οθόνη κουζίνας",
|
"kds": "Οθόνη κουζίνας",
|
||||||
"soon": "σύντομα",
|
"soon": "σύντομα",
|
||||||
"integrations": "Συνδέσεις",
|
"integrations": "Συνδέσεις",
|
||||||
"license": "Άδεια"
|
"license": "Άδεια",
|
||||||
|
"devices": "Συσκευές",
|
||||||
|
"sessions": "Συνδεδεμένοι τώρα",
|
||||||
|
"approvals": "Εγκρίσεις υπευθύνου"
|
||||||
},
|
},
|
||||||
"profile": {
|
"profile": {
|
||||||
"edit": "Επεξεργασία προφίλ",
|
"edit": "Επεξεργασία προφίλ",
|
||||||
@@ -127,5 +130,243 @@
|
|||||||
"dev": "Ανάπτυξη",
|
"dev": "Ανάπτυξη",
|
||||||
"notIncluded": "Δεν περιλαμβάνεται",
|
"notIncluded": "Δεν περιλαμβάνεται",
|
||||||
"limits": "Όρια"
|
"limits": "Όρια"
|
||||||
|
},
|
||||||
|
"devices": {
|
||||||
|
"intro": "Οθόνες και τερματικά που τρέχουν από μία εφαρμογή: οθόνες κουζίνας, ταμεία πάγκου, οθόνες πελάτη, σήμανση, tablet μενού. Τα κινητά του προσωπικού δεν είναι συσκευές· συνδέονται με τον λογαριασμό τους.",
|
||||||
|
"pair": "Σύζευξη συσκευής",
|
||||||
|
"empty": "Δεν υπάρχουν συσκευές ακόμα",
|
||||||
|
"emptyBody": "Ανοίξτε την εφαρμογή στην οθόνη που θέλετε: δείχνει έναν κωδικό 6 χαρακτήρων. Μετά πατήστε εδώ «Σύζευξη συσκευής».",
|
||||||
|
"showRemoved": "Εμφάνιση συσκευών που αφαιρέθηκαν",
|
||||||
|
"usage": "{{label}}: {{used}} από {{max}}",
|
||||||
|
"usageUnlimited": "{{label}}: {{used}}",
|
||||||
|
"columns": {
|
||||||
|
"device": "Συσκευή",
|
||||||
|
"app": "Εφαρμογή",
|
||||||
|
"status": "Κατάσταση",
|
||||||
|
"signIn": "Σύνδεση",
|
||||||
|
"linked": "Συνδεδεμένη με",
|
||||||
|
"actions": ""
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"online": "Σε σύνδεση",
|
||||||
|
"offline": "Τελευταία φορά {{when}}",
|
||||||
|
"offlineNever": "Δεν έχει εμφανιστεί ακόμα",
|
||||||
|
"waiting": "Περιμένει να συνδεθεί η συσκευή",
|
||||||
|
"app_off": "Η εφαρμογή είναι κλειστή",
|
||||||
|
"removed": "Αφαιρέθηκε {{when}}"
|
||||||
|
},
|
||||||
|
"signIn": {
|
||||||
|
"default": "Προεπιλογή καταστήματος ({{mode}})",
|
||||||
|
"pin": "PIN",
|
||||||
|
"password": "Κωδικός",
|
||||||
|
"tap": "Επιλογή ονόματος",
|
||||||
|
"none": "Χωρίς σύνδεση",
|
||||||
|
"defaultPlain": "Προεπιλογή καταστήματος"
|
||||||
|
},
|
||||||
|
"form": {
|
||||||
|
"code": "Κωδικός που δείχνει η συσκευή",
|
||||||
|
"codeHint": "6 χαρακτήρες, γράμματα και αριθμοί",
|
||||||
|
"app": "Εφαρμογή",
|
||||||
|
"name": "Όνομα",
|
||||||
|
"namePlaceholder": "π.χ. Κουζίνα, Μπαρ, Ταμείο 1",
|
||||||
|
"signIn": "Πώς συνδέεται το προσωπικό",
|
||||||
|
"link": "Συνδεδεμένη συσκευή",
|
||||||
|
"noLink": "Καμία",
|
||||||
|
"linkHint": "Για παράδειγμα μια οθόνη πελάτη που δείχνει την παραγγελία ενός ταμείου πάγκου.",
|
||||||
|
"full": "{{label}}: η άδεια επιτρέπει {{max}} και χρησιμοποιούνται όλα. Αφαιρέστε μία ή ζητήστε μεγαλύτερη άδεια.",
|
||||||
|
"noApps": "Καμία εφαρμογή συσκευών δεν είναι ενεργή. Ενεργοποιήστε μία πρώτα από τις Εφαρμογές."
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"rename": "Μετονομασία",
|
||||||
|
"changeApp": "Αλλαγή εφαρμογής",
|
||||||
|
"remove": "Αφαίρεση",
|
||||||
|
"save": "Αποθήκευση",
|
||||||
|
"edit": "Επεξεργασία"
|
||||||
|
},
|
||||||
|
"paired": "Η συσκευή {{name}} συνδέθηκε. Ξεκινά σε λίγα δευτερόλεπτα.",
|
||||||
|
"saved": "Αποθηκεύτηκε",
|
||||||
|
"removeTitle": "Αφαίρεση: {{name}};",
|
||||||
|
"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 στην οθόνη κλειδώματος",
|
||||||
|
"idle": "αχρησιμοποίητη για πολύ καιρό"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"approvals": {
|
||||||
|
"intro": "Κάθε φορά που ένας υπεύθυνος έβαλε το PIN του για να επιτρέψει μία ενέργεια σε κάποιον που δεν έχει το δικαίωμα. Μια έγκριση ισχύει μία φορά, μέσα σε ένα λεπτό.",
|
||||||
|
"empty": "Δεν υπάρχουν εγκρίσεις ακόμα",
|
||||||
|
"emptyBody": "Όταν ένας σερβιτόρος χρειάζεται υπεύθυνο για μια ενέργεια, π.χ. ακύρωση είδους που έχει σταλεί, η έγκριση εμφανίζεται εδώ.",
|
||||||
|
"columns": {
|
||||||
|
"when": "Πότε",
|
||||||
|
"action": "Ενέργεια",
|
||||||
|
"askedBy": "Ζήτησε",
|
||||||
|
"approvedBy": "Ενέκρινε",
|
||||||
|
"where": "Συσκευή",
|
||||||
|
"result": "Αποτέλεσμα"
|
||||||
|
},
|
||||||
|
"state": {
|
||||||
|
"used": "Χρησιμοποιήθηκε",
|
||||||
|
"expired": "Δεν χρησιμοποιήθηκε",
|
||||||
|
"waiting": "Σε αναμονή"
|
||||||
|
},
|
||||||
|
"order": "Παραγγελία #{{id}}"
|
||||||
|
},
|
||||||
|
"notifications": {
|
||||||
|
"bell": "Ειδοποιήσεις",
|
||||||
|
"bellUnread_one": "Ειδοποιήσεις: {{count}} αδιάβαστη",
|
||||||
|
"bellUnread_other": "Ειδοποιήσεις: {{count}} αδιάβαστες",
|
||||||
|
"title": "Ειδοποιήσεις",
|
||||||
|
"empty": "Τίποτα καινούργιο. Εδώ εμφανίζονται ειδοποιήσεις για την άδεια, την εκτύπωση και την υποστήριξη.",
|
||||||
|
"markAll": "Όλες διαβασμένες",
|
||||||
|
"times_one": "{{count}} φορά",
|
||||||
|
"times_other": "{{count}} φορές"
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"saved": "Αποθηκεύτηκε",
|
||||||
|
"tabs": {
|
||||||
|
"app-info": "Γενικά",
|
||||||
|
"venue": "Κατάστημα & γλώσσα",
|
||||||
|
"security": "Σύνδεση & ασφάλεια",
|
||||||
|
"operation": "Λειτουργία",
|
||||||
|
"colours": "Εμφάνιση",
|
||||||
|
"print-fonts": "Εκτύπωση",
|
||||||
|
"fiscal": "Ταμειακή",
|
||||||
|
"development": "Developer"
|
||||||
|
},
|
||||||
|
"mode": {
|
||||||
|
"password": "Κωδικός",
|
||||||
|
"pin": "PIN",
|
||||||
|
"tap": "Επιλογή ονόματος",
|
||||||
|
"none": "Χωρίς σύνδεση"
|
||||||
|
},
|
||||||
|
"session": {
|
||||||
|
"off": "Επιτρέπεται σε πολλές συσκευές",
|
||||||
|
"refuse_new": "Άρνηση δεύτερης σύνδεσης",
|
||||||
|
"end_old": "Αποσύνδεση της παλιότερης"
|
||||||
|
},
|
||||||
|
"signIn": {
|
||||||
|
"title": "Σύνδεση",
|
||||||
|
"intro": "Πώς κάθε εφαρμογή ρωτά ποιος είναι ο χρήστης. Οι αλλαγές ισχύουν από την επόμενη σύνδεση.",
|
||||||
|
"manager": "Οι υπεύθυνοι συνδέονται στη διαχείριση με",
|
||||||
|
"managerTip": "Με PIN, οι υπεύθυνοι βάζουν το ίδιο PIN που χρησιμοποιούν για ξεκλείδωμα και εγκρίσεις. Κάθε υπεύθυνος χρειάζεται PIN.",
|
||||||
|
"autofill": "Συμπλήρωση ονόματος χρήστη όταν υπάρχει ένας μόνο υπεύθυνος",
|
||||||
|
"autofillHint": "Η σελίδα σύνδεσης ζητά τότε μόνο τον κωδικό ή το PIN.",
|
||||||
|
"waiter": "Οι σερβιτόροι συνδέονται στην εφαρμογή τους με",
|
||||||
|
"waiterTapWarning": "Η «Επιλογή ονόματος» λειτουργεί μόνο σε συζευγμένες συσκευές. Από τα δικά τους κινητά οι σερβιτόροι δεν μπορούν να συνδεθούν έτσι.",
|
||||||
|
"requireUsername": "Οι σερβιτόροι γράφουν το όνομα χρήστη τους",
|
||||||
|
"requireUsernameHint": "Αντί να επιλέγουν το όνομά τους από τη λίστα.",
|
||||||
|
"device": "Στις συζευγμένες συσκευές (οθόνη κουζίνας, ταμείο πάγκου) το προσωπικό συνδέεται με",
|
||||||
|
"deviceHint": "Κάθε συσκευή μπορεί να έχει δική της επιλογή στη σελίδα Συσκευές.",
|
||||||
|
"singleManager": "Μία σύνδεση ανά υπεύθυνο",
|
||||||
|
"singleWaiter": "Μία σύνδεση ανά σερβιτόρο",
|
||||||
|
"singleTip": "Όταν κάποιος είναι ήδη συνδεδεμένος σε άλλη συσκευή: επιτρέπονται και οι δύο, απορρίπτεται η νέα σύνδεση ή αποσυνδέεται η παλιότερη.",
|
||||||
|
"idle": "Αποσύνδεση μετά από",
|
||||||
|
"idleHint": "Ημέρες χωρίς χρήση της εφαρμογής (διαχείριση, εφαρμογή σερβιτόρων και συζευγμένες συσκευές). Την επόμενη φορά συνδέονται ξανά.",
|
||||||
|
"idleDays_one": "{{count}} ημέρα χωρίς χρήση",
|
||||||
|
"idleDays_other": "{{count}} ημέρες χωρίς χρήση",
|
||||||
|
"idleNever": "Ποτέ"
|
||||||
|
},
|
||||||
|
"venue": {
|
||||||
|
"title": "Κατάστημα",
|
||||||
|
"language": "Γλώσσα",
|
||||||
|
"languageHint": "Για όσους δεν έχουν διαλέξει δική τους, και για τα εκτυπωμένα δελτία και τις αναφορές.",
|
||||||
|
"timezone": "Ζώνη ώρας",
|
||||||
|
"timezoneHint": "Όλες οι ώρες εμφανίζονται σε αυτή. Η ώρα εκεί τώρα: {{time}}."
|
||||||
|
},
|
||||||
|
"print": {
|
||||||
|
"title": "Ειδοποιήσεις εκτύπωσης",
|
||||||
|
"alert": "Ειδοποίηση των υπευθύνων όταν ένα δελτίο δεν τυπώνεται",
|
||||||
|
"alertHint": "Όσο συνεχίζει να ξαναδοκιμάζει. Ένα δελτίο που εγκαταλείπεται οριστικά αναφέρεται πάντα.",
|
||||||
|
"never": "Μόνο όταν εγκαταλειφθεί",
|
||||||
|
"after_one": "Μετά από {{count}} αποτυχία",
|
||||||
|
"after_other": "Μετά από {{count}} αποτυχίες"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"logs": {
|
||||||
|
"tab": "Αρχεία καταγραφής",
|
||||||
|
"intro": "Τα ημερήσια αρχεία καταγραφής του συστήματος, που κρατιούνται 30 ημέρες. Η υποστήριξη μπορεί να ζητήσει το αρχείο της ημέρας που κάτι πήγε στραβά. Οι ημέρες είναι σε ώρα UTC.",
|
||||||
|
"empty": "Δεν υπάρχουν αρχεία ακόμα",
|
||||||
|
"current": "(γράφεται ακόμα)",
|
||||||
|
"size": "{{size}} KB",
|
||||||
|
"download": "Λήψη"
|
||||||
|
},
|
||||||
|
"setup": {
|
||||||
|
"language": "Γλώσσα προσωπικού",
|
||||||
|
"timezone": "Ζώνη ώρας",
|
||||||
|
"languageHint": "Η γλώσσα των οθονών του προσωπικού (ο καθένας μπορεί να διαλέξει τη δική του) και των εκτυπωμένων δελτίων και αναφορών."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,35 +1,82 @@
|
|||||||
{
|
{
|
||||||
"caller_id": {
|
"caller_id": {
|
||||||
"name": "Αναγνώριση κλήσης",
|
"name": "Αναγνώριση κλήσης",
|
||||||
"description": "Εισερχόμενες κλήσεις από το τηλεφωνικό κέντρο του καταστήματος (Grandstream UCM)."
|
"description": "Εισερχόμενες κλήσεις από το τηλεφωνικό κέντρο του καταστήματος (Grandstream UCM).",
|
||||||
|
"permissions": {
|
||||||
|
"use": "Προβολή εισερχόμενων κλήσεων"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"catalog": {
|
"catalog": {
|
||||||
"name": "Κατάλογος",
|
"name": "Κατάλογος",
|
||||||
"description": "Προϊόντα, κατηγορίες, επιλογές, τραπέζια και ζώνες ετοιμασίας."
|
"description": "Προϊόντα, κατηγορίες, επιλογές, τραπέζια και ζώνες ετοιμασίας.",
|
||||||
|
"permissions": {
|
||||||
|
"menu": {
|
||||||
|
"manage": "Επεξεργασία προϊόντων, κατηγοριών και σημείων παρασκευής"
|
||||||
|
},
|
||||||
|
"tables": {
|
||||||
|
"manage": "Επεξεργασία τραπεζιών και ομάδων τραπεζιών"
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"chat": {
|
"chat": {
|
||||||
"name": "Συνομιλία προσωπικού",
|
"name": "Συνομιλία προσωπικού",
|
||||||
"description": "Συνομιλία του προσωπικού και μηνύματα του υπευθύνου προς το προσωπικό."
|
"description": "Συνομιλία του προσωπικού και μηνύματα του υπευθύνου προς το προσωπικό.",
|
||||||
|
"permissions": {
|
||||||
|
"use": "Χρήση της συνομιλίας προσωπικού",
|
||||||
|
"broadcast": "Αποστολή μηνυμάτων σε όλο το προσωπικό"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"connect_menu": {
|
"connect_menu": {
|
||||||
"name": "QR μενού",
|
"name": "QR μενού",
|
||||||
"description": "Το online μενού με QR, συγχρονισμένο με τον κατάλογο."
|
"description": "Το online μενού με QR, συγχρονισμένο με τον κατάλογο.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Διαχείριση του QR μενού"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"connect_orders": {
|
"connect_orders": {
|
||||||
"name": "Online παραγγελίες",
|
"name": "Online παραγγελίες",
|
||||||
"description": "Παραγγελίες από το QR μενού, που έρχονται από το cloud."
|
"description": "Παραγγελίες από το QR μενού, που έρχονται από το cloud.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Αποδοχή και διαχείριση online παραγγελιών"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"connect_remote": {
|
"connect_remote": {
|
||||||
"name": "Απομακρυσμένη διαχείριση",
|
"name": "Απομακρυσμένη διαχείριση",
|
||||||
"description": "Ζωντανά στοιχεία για την εφαρμογή απομακρυσμένης διαχείρισης του ιδιοκτήτη."
|
"description": "Ζωντανά στοιχεία για την εφαρμογή απομακρυσμένης διαχείρισης του ιδιοκτήτη.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Ρύθμιση της εφαρμογής απομακρυσμένης διαχείρισης"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"core": {
|
"core": {
|
||||||
"name": "Βασικό σύστημα",
|
"name": "Βασικό σύστημα",
|
||||||
"description": "Σύνδεση, προσωπικό, ρυθμίσεις, άδεια, σύστημα και ζωντανές ενημερώσεις. Πάντα ενεργό."
|
"description": "Σύνδεση, προσωπικό, ρυθμίσεις, άδεια, σύστημα και ζωντανές ενημερώσεις. Πάντα ενεργό.",
|
||||||
|
"permissions": {
|
||||||
|
"dashboard": {
|
||||||
|
"access": "Είσοδος στη διαχείριση"
|
||||||
|
},
|
||||||
|
"staff": {
|
||||||
|
"manage": "Προσθήκη και επεξεργασία προσωπικού, προβολή συνδεδεμένων"
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"manage": "Αλλαγή ρυθμίσεων καταστήματος"
|
||||||
|
},
|
||||||
|
"modules": {
|
||||||
|
"manage": "Ενεργοποίηση και απενεργοποίηση εφαρμογών, λειτουργιών και συνδέσεων"
|
||||||
|
},
|
||||||
|
"devices": {
|
||||||
|
"manage": "Σύζευξη, μετονομασία, αλλαγή εφαρμογής και αφαίρεση συσκευών"
|
||||||
|
},
|
||||||
|
"system": {
|
||||||
|
"admin": "Συντήρηση μόνο από την υποστήριξη"
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"crm": {
|
"crm": {
|
||||||
"name": "Πελάτες",
|
"name": "Πελάτες",
|
||||||
"description": "Αρχείο πελατών."
|
"description": "Αρχείο πελατών.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Προσθήκη και επεξεργασία πελατών"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"customer_display": {
|
"customer_display": {
|
||||||
"name": "Οθόνη πελάτη",
|
"name": "Οθόνη πελάτη",
|
||||||
@@ -40,28 +87,44 @@
|
|||||||
},
|
},
|
||||||
"expenses": {
|
"expenses": {
|
||||||
"name": "Έξοδα",
|
"name": "Έξοδα",
|
||||||
"description": "Έξοδα, πληρωμές και βιβλίο προμηθευτών."
|
"description": "Έξοδα, πληρωμές και βιβλίο προμηθευτών.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Καταχώριση εξόδων και προμηθευτών"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"fiscal": {
|
"fiscal": {
|
||||||
"name": "Φορολογικός μηχανισμός",
|
"name": "Φορολογικός μηχανισμός",
|
||||||
"description": "Αποστολή αποδείξεων στον φορολογικό μηχανισμό (ΦΗΜ) μέσω του φακέλου γέφυρας."
|
"description": "Αποστολή αποδείξεων στον φορολογικό μηχανισμό (ΦΗΜ) μέσω του φακέλου γέφυρας.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Ρύθμιση του φορολογικού μηχανισμού"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"history": {
|
"history": {
|
||||||
"name": "Ιστορικό παραγγελιών",
|
"name": "Ιστορικό παραγγελιών",
|
||||||
"description": "Παλιές παραγγελίες και σύνοψη εργάσιμων ημερών (μόνο προβολή). Δωρεάν, με σύντομο ιστορικό.",
|
"description": "Παλιές παραγγελίες και σύνοψη εργάσιμων ημερών (μόνο προβολή). Δωρεάν, με σύντομο ιστορικό.",
|
||||||
"limits": {
|
"limits": {
|
||||||
"history_days": "Ημέρες ιστορικού για προβολή"
|
"history_days": "Ημέρες ιστορικού για προβολή"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"view": "Προβολή παλιών παραγγελιών και συνόψεων ημέρας"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"inventory": {
|
"inventory": {
|
||||||
"name": "Αποθήκη",
|
"name": "Αποθήκη",
|
||||||
"description": "Καταγραφή απορριμμάτων και κόστος προϊόντων."
|
"description": "Καταγραφή απορριμμάτων και κόστος προϊόντων.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Καταγραφή φθορών και κόστους"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"kds": {
|
"kds": {
|
||||||
"name": "Οθόνη κουζίνας",
|
"name": "Οθόνη κουζίνας",
|
||||||
"description": "Οθόνες στην κουζίνα ή στο μπαρ με τις παραγγελίες προς ετοιμασία.",
|
"description": "Οθόνες στην κουζίνα ή στο μπαρ με τις παραγγελίες προς ετοιμασία.",
|
||||||
"limits": {
|
"limits": {
|
||||||
"devices": "Οθόνες κουζίνας"
|
"devices": "Οθόνες κουζίνας"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"access": "Χρήση της οθόνης κουζίνας",
|
||||||
|
"bump": "Σήμανση πιάτων ως έτοιμων"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"menu_tablet": {
|
"menu_tablet": {
|
||||||
@@ -69,55 +132,102 @@
|
|||||||
"description": "Κατάλογος αυτοεξυπηρέτησης σε tablet (έρχεται σύντομα).",
|
"description": "Κατάλογος αυτοεξυπηρέτησης σε tablet (έρχεται σύντομα).",
|
||||||
"limits": {
|
"limits": {
|
||||||
"devices": "Tablet μενού"
|
"devices": "Tablet μενού"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Ρύθμιση των tablet μενού"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"notes": {
|
"notes": {
|
||||||
"name": "Σημειώσεις",
|
"name": "Σημειώσεις",
|
||||||
"description": "Σημειώσεις και εργασίες του καταστήματος."
|
"description": "Σημειώσεις και εργασίες του καταστήματος.",
|
||||||
|
"permissions": {
|
||||||
|
"use": "Ανάγνωση και γραφή σημειώσεων και εκκρεμοτήτων"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"ordering": {
|
"ordering": {
|
||||||
"name": "Παραγγελίες",
|
"name": "Παραγγελίες",
|
||||||
"description": "Παραγγελίες, πληρωμές, εργάσιμη ημέρα, βάρδιες, ταμείο και εκτύπωση κουζίνας."
|
"description": "Παραγγελίες, πληρωμές, εργάσιμη ημέρα, βάρδιες, ταμείο και εκτύπωση κουζίνας.",
|
||||||
|
"permissions": {
|
||||||
|
"orders": {
|
||||||
|
"open": "Άνοιγμα παραγγελιών και προσθήκη ειδών",
|
||||||
|
"close": "Είσπραξη και κλείσιμο παραγγελιών",
|
||||||
|
"cancel": "Ακύρωση ειδών που έχουν σταλεί"
|
||||||
|
},
|
||||||
|
"prices": {
|
||||||
|
"modify": "Αλλαγή τιμής είδους"
|
||||||
|
},
|
||||||
|
"business_day": {
|
||||||
|
"manage": "Άνοιγμα και κλείσιμο της εργάσιμης ημέρας"
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"pos_counter": {
|
"pos_counter": {
|
||||||
"name": "Ταμείο πάγκου",
|
"name": "Ταμείο πάγκου",
|
||||||
"description": "Τερματικό στον πάγκο για γρήγορες παραγγελίες (έρχεται σύντομα).",
|
"description": "Τερματικό στον πάγκο για γρήγορες παραγγελίες (έρχεται σύντομα).",
|
||||||
"limits": {
|
"limits": {
|
||||||
"devices": "Τερματικά πάγκου"
|
"devices": "Τερματικά πάγκου"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"access": "Χρήση του ταμείου πάγκου"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"pricing": {
|
"pricing": {
|
||||||
"name": "Τιμολόγηση",
|
"name": "Τιμολόγηση",
|
||||||
"description": "Ομάδες τιμών, happy hour, τροποποιητές, προσφορές και εκπτώσεις σερβιτόρων."
|
"description": "Ομάδες τιμών, happy hour, τροποποιητές, προσφορές και εκπτώσεις σερβιτόρων.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Ρύθμιση ομάδων τιμών, τροποποιητών και προσφορών",
|
||||||
|
"discounts": {
|
||||||
|
"apply": "Εκπτώσεις",
|
||||||
|
"over_limit": "Εκπτώσεις πάνω από τα όρια ανά σερβιτόρο"
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"reports": {
|
"reports": {
|
||||||
"name": "Αναφορές",
|
"name": "Αναφορές",
|
||||||
"description": "Πλήρεις αναφορές πωλήσεων, προϊόντων, προσωπικού και εκτυπωτών, εξαγωγή CSV και εκτυπωμένες αναφορές.",
|
"description": "Πλήρεις αναφορές πωλήσεων, προϊόντων, προσωπικού και εκτυπωτών, εξαγωγή CSV και εκτυπωμένες αναφορές.",
|
||||||
"limits": {
|
"limits": {
|
||||||
"history_days": "Ημέρες που καλύπτουν οι αναφορές"
|
"history_days": "Ημέρες που καλύπτουν οι αναφορές"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"view": "Προβολή αναφορών"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"reservations": {
|
"reservations": {
|
||||||
"name": "Κρατήσεις",
|
"name": "Κρατήσεις",
|
||||||
"description": "Κρατήσεις τραπεζιών."
|
"description": "Κρατήσεις τραπεζιών.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Προσθήκη και επεξεργασία κρατήσεων"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"signage": {
|
"signage": {
|
||||||
"name": "Ψηφιακή σήμανση",
|
"name": "Ψηφιακή σήμανση",
|
||||||
"description": "Μενού και προσφορές σε τηλεοράσεις (έρχεται σύντομα).",
|
"description": "Μενού και προσφορές σε τηλεοράσεις (έρχεται σύντομα).",
|
||||||
"limits": {
|
"limits": {
|
||||||
"devices": "Οθόνες σήμανσης"
|
"devices": "Οθόνες σήμανσης"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Επεξεργασία περιεχομένου σήμανσης"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"staff_planning": {
|
"staff_planning": {
|
||||||
"name": "Προγραμματισμός προσωπικού",
|
"name": "Προγραμματισμός προσωπικού",
|
||||||
"description": "Πρόγραμμα βαρδιών και μισθοδοσία."
|
"description": "Πρόγραμμα βαρδιών και μισθοδοσία.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Προγραμματισμός βαρδιών και προβολή μισθοδοσίας"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"tabs": {
|
"tabs": {
|
||||||
"name": "Καρτέλες",
|
"name": "Καρτέλες",
|
||||||
"description": "Καρτέλες πληρωμής αργότερα για τακτικούς πελάτες."
|
"description": "Καρτέλες πληρωμής αργότερα για τακτικούς πελάτες.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Άνοιγμα, χρέωση και εξόφληση λογαριασμών"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"waiter_app": {
|
"waiter_app": {
|
||||||
"name": "Εφαρμογή σερβιτόρων",
|
"name": "Εφαρμογή σερβιτόρων",
|
||||||
"description": "Λήψη παραγγελιών από τα κινητά των σερβιτόρων (web και εφαρμογή Android)."
|
"description": "Λήψη παραγγελιών από τα κινητά των σερβιτόρων (web και εφαρμογή Android).",
|
||||||
|
"permissions": {
|
||||||
|
"access": "Σύνδεση στην εφαρμογή σερβιτόρων"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,5 +68,8 @@
|
|||||||
"catalog": {
|
"catalog": {
|
||||||
"unknown_category": "There is no category {{category_id}}.",
|
"unknown_category": "There is no category {{category_id}}.",
|
||||||
"primary_not_listed": "The main category ({{category_id}}) must be one of the product's categories."
|
"primary_not_listed": "The main category ({{category_id}}) must be one of the product's categories."
|
||||||
|
},
|
||||||
|
"system": {
|
||||||
|
"log_not_found": "There is no log file for {{date}}."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,10 @@
|
|||||||
"kds": "Kitchen display",
|
"kds": "Kitchen display",
|
||||||
"soon": "soon",
|
"soon": "soon",
|
||||||
"integrations": "Integrations",
|
"integrations": "Integrations",
|
||||||
"license": "License"
|
"license": "License",
|
||||||
|
"devices": "Devices",
|
||||||
|
"sessions": "Signed in now",
|
||||||
|
"approvals": "Manager approvals"
|
||||||
},
|
},
|
||||||
"profile": {
|
"profile": {
|
||||||
"edit": "Edit profile",
|
"edit": "Edit profile",
|
||||||
@@ -127,5 +130,243 @@
|
|||||||
"dev": "Development",
|
"dev": "Development",
|
||||||
"notIncluded": "Not included",
|
"notIncluded": "Not included",
|
||||||
"limits": "Limits"
|
"limits": "Limits"
|
||||||
|
},
|
||||||
|
"devices": {
|
||||||
|
"intro": "Screens and terminals that run one app each: kitchen displays, counter POS, customer displays, signage, menu tablets. Phones of staff are not devices; they sign in as themselves.",
|
||||||
|
"pair": "Pair a device",
|
||||||
|
"empty": "No devices yet",
|
||||||
|
"emptyBody": "Open the app on the screen you want to use: it shows a 6-character code. Then choose \"Pair a device\" here.",
|
||||||
|
"showRemoved": "Show removed devices",
|
||||||
|
"usage": "{{label}}: {{used}} of {{max}}",
|
||||||
|
"usageUnlimited": "{{label}}: {{used}}",
|
||||||
|
"columns": {
|
||||||
|
"device": "Device",
|
||||||
|
"app": "App",
|
||||||
|
"status": "Status",
|
||||||
|
"signIn": "Sign-in",
|
||||||
|
"linked": "Linked to",
|
||||||
|
"actions": ""
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"online": "Online",
|
||||||
|
"offline": "Last seen {{when}}",
|
||||||
|
"offlineNever": "Not seen yet",
|
||||||
|
"waiting": "Waiting for the device to connect",
|
||||||
|
"app_off": "App turned off",
|
||||||
|
"removed": "Removed {{when}}"
|
||||||
|
},
|
||||||
|
"signIn": {
|
||||||
|
"default": "Venue default ({{mode}})",
|
||||||
|
"pin": "PIN",
|
||||||
|
"password": "Password",
|
||||||
|
"tap": "Tap your name",
|
||||||
|
"none": "No sign-in",
|
||||||
|
"defaultPlain": "Venue default"
|
||||||
|
},
|
||||||
|
"form": {
|
||||||
|
"code": "Code shown on the device",
|
||||||
|
"codeHint": "6 characters, letters and digits",
|
||||||
|
"app": "App to run",
|
||||||
|
"name": "Name",
|
||||||
|
"namePlaceholder": "e.g. Kitchen, Bar, Counter 1",
|
||||||
|
"signIn": "How staff sign in",
|
||||||
|
"link": "Linked device",
|
||||||
|
"noLink": "None",
|
||||||
|
"linkHint": "For example a customer display that shows a counter POS's order.",
|
||||||
|
"full": "{{label}}: the license allows {{max}}, all in use. Remove one or ask for a bigger license.",
|
||||||
|
"noApps": "No device app is turned on. Turn one on in Apps first."
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"rename": "Rename",
|
||||||
|
"changeApp": "Change app",
|
||||||
|
"remove": "Remove",
|
||||||
|
"save": "Save",
|
||||||
|
"edit": "Edit"
|
||||||
|
},
|
||||||
|
"paired": "{{name}} is paired. It starts in a few seconds.",
|
||||||
|
"saved": "Saved",
|
||||||
|
"removeTitle": "Remove {{name}}?",
|
||||||
|
"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",
|
||||||
|
"idle": "not used for too long"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"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}}"
|
||||||
|
},
|
||||||
|
"notifications": {
|
||||||
|
"bell": "Notifications",
|
||||||
|
"bellUnread_one": "Notifications: {{count}} unread",
|
||||||
|
"bellUnread_other": "Notifications: {{count}} unread",
|
||||||
|
"title": "Notifications",
|
||||||
|
"empty": "Nothing new. Licence, printing and support alerts show up here.",
|
||||||
|
"markAll": "Mark all as read",
|
||||||
|
"times_one": "{{count}} time",
|
||||||
|
"times_other": "{{count}} times"
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"saved": "Saved",
|
||||||
|
"tabs": {
|
||||||
|
"app-info": "General",
|
||||||
|
"venue": "Venue & language",
|
||||||
|
"security": "Sign-in & security",
|
||||||
|
"operation": "Operation",
|
||||||
|
"colours": "Appearance",
|
||||||
|
"print-fonts": "Printing",
|
||||||
|
"fiscal": "Fiscal device",
|
||||||
|
"development": "Developer"
|
||||||
|
},
|
||||||
|
"mode": {
|
||||||
|
"password": "Password",
|
||||||
|
"pin": "PIN",
|
||||||
|
"tap": "Tap your name",
|
||||||
|
"none": "No sign-in"
|
||||||
|
},
|
||||||
|
"session": {
|
||||||
|
"off": "Allowed on several devices",
|
||||||
|
"refuse_new": "Refuse a second sign-in",
|
||||||
|
"end_old": "Sign out the older one"
|
||||||
|
},
|
||||||
|
"signIn": {
|
||||||
|
"title": "Sign-in",
|
||||||
|
"intro": "How each app asks people who they are. Changes apply to the next sign-in.",
|
||||||
|
"manager": "Managers sign in to this dashboard with",
|
||||||
|
"managerTip": "With PIN, managers type the same PIN they use to unlock the screen and to approve actions. Every manager needs a PIN.",
|
||||||
|
"autofill": "Fill in the username when there is only one manager",
|
||||||
|
"autofillHint": "The sign-in page then only asks for the password or PIN.",
|
||||||
|
"waiter": "Waiters sign in to the waiter app with",
|
||||||
|
"waiterTapWarning": "\"Tap your name\" works only on paired devices. On their own phones, waiters can't sign in this way.",
|
||||||
|
"requireUsername": "Waiters type their username",
|
||||||
|
"requireUsernameHint": "Instead of picking their name from the list.",
|
||||||
|
"device": "On paired devices (kitchen display, counter POS), staff sign in with",
|
||||||
|
"deviceHint": "Each device can choose its own on the Devices page.",
|
||||||
|
"singleManager": "One session per manager",
|
||||||
|
"singleWaiter": "One session per waiter",
|
||||||
|
"singleTip": "When someone is already signed in on another device: allow both, refuse the new sign-in, or sign out the older one.",
|
||||||
|
"idle": "Sign people out after",
|
||||||
|
"idleHint": "Days without using the app (manager, waiter app and paired devices). They sign in again next time.",
|
||||||
|
"idleDays_one": "{{count}} day without use",
|
||||||
|
"idleDays_other": "{{count}} days without use",
|
||||||
|
"idleNever": "Never"
|
||||||
|
},
|
||||||
|
"venue": {
|
||||||
|
"title": "Venue",
|
||||||
|
"language": "Language",
|
||||||
|
"languageHint": "For staff who haven't chosen their own, and for printed tickets and reports.",
|
||||||
|
"timezone": "Time zone",
|
||||||
|
"timezoneHint": "Every time is shown in it. The time there now: {{time}}."
|
||||||
|
},
|
||||||
|
"print": {
|
||||||
|
"title": "Print alerts",
|
||||||
|
"alert": "Tell managers when a ticket fails to print",
|
||||||
|
"alertHint": "While it keeps retrying. A ticket that is finally given up is always reported.",
|
||||||
|
"never": "Only when it is given up",
|
||||||
|
"after_one": "After {{count}} failed attempt",
|
||||||
|
"after_other": "After {{count}} failed attempts"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"logs": {
|
||||||
|
"tab": "Log files",
|
||||||
|
"intro": "The system's daily log files, kept for 30 days. Support may ask for the file of the day something went wrong. Days are in UTC.",
|
||||||
|
"empty": "No log files yet",
|
||||||
|
"current": "(still being written)",
|
||||||
|
"size": "{{size}} KB",
|
||||||
|
"download": "Download"
|
||||||
|
},
|
||||||
|
"setup": {
|
||||||
|
"language": "Staff language",
|
||||||
|
"timezone": "Time zone",
|
||||||
|
"languageHint": "The language of staff screens (each person can choose their own) and of printed tickets and reports."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,35 +1,82 @@
|
|||||||
{
|
{
|
||||||
"caller_id": {
|
"caller_id": {
|
||||||
"name": "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": {
|
"catalog": {
|
||||||
"name": "Catalogue",
|
"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": {
|
"chat": {
|
||||||
"name": "Staff 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": {
|
"connect_menu": {
|
||||||
"name": "QR 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": {
|
"connect_orders": {
|
||||||
"name": "Online 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": {
|
"connect_remote": {
|
||||||
"name": "Remote manager",
|
"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": {
|
"core": {
|
||||||
"name": "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": {
|
"crm": {
|
||||||
"name": "Customers",
|
"name": "Customers",
|
||||||
"description": "Customer records."
|
"description": "Customer records.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Add and edit customers"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"customer_display": {
|
"customer_display": {
|
||||||
"name": "Customer display",
|
"name": "Customer display",
|
||||||
@@ -40,28 +87,44 @@
|
|||||||
},
|
},
|
||||||
"expenses": {
|
"expenses": {
|
||||||
"name": "Expenses",
|
"name": "Expenses",
|
||||||
"description": "Expenses, payments and the supplier book."
|
"description": "Expenses, payments and the supplier book.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Record expenses and suppliers"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"fiscal": {
|
"fiscal": {
|
||||||
"name": "Fiscal device",
|
"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": {
|
"history": {
|
||||||
"name": "Order history",
|
"name": "Order history",
|
||||||
"description": "Past orders and business-day summaries (read only). Free, with a short history.",
|
"description": "Past orders and business-day summaries (read only). Free, with a short history.",
|
||||||
"limits": {
|
"limits": {
|
||||||
"history_days": "Days of history you can view"
|
"history_days": "Days of history you can view"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"view": "See past orders and day summaries"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"inventory": {
|
"inventory": {
|
||||||
"name": "Inventory",
|
"name": "Inventory",
|
||||||
"description": "Waste log and product costs."
|
"description": "Waste log and product costs.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Log waste and costs"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"kds": {
|
"kds": {
|
||||||
"name": "Kitchen display",
|
"name": "Kitchen display",
|
||||||
"description": "Screens in the kitchen or bar showing the orders to prepare.",
|
"description": "Screens in the kitchen or bar showing the orders to prepare.",
|
||||||
"limits": {
|
"limits": {
|
||||||
"devices": "Kitchen screens"
|
"devices": "Kitchen screens"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"access": "Use the kitchen display",
|
||||||
|
"bump": "Mark items ready"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"menu_tablet": {
|
"menu_tablet": {
|
||||||
@@ -69,55 +132,102 @@
|
|||||||
"description": "A self-service catalogue on a tablet (coming soon).",
|
"description": "A self-service catalogue on a tablet (coming soon).",
|
||||||
"limits": {
|
"limits": {
|
||||||
"devices": "Menu tablets"
|
"devices": "Menu tablets"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Set up menu tablets"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"notes": {
|
"notes": {
|
||||||
"name": "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": {
|
"ordering": {
|
||||||
"name": "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": {
|
"pos_counter": {
|
||||||
"name": "Counter POS",
|
"name": "Counter POS",
|
||||||
"description": "A counter terminal for quick orders (coming soon).",
|
"description": "A counter terminal for quick orders (coming soon).",
|
||||||
"limits": {
|
"limits": {
|
||||||
"devices": "Counter terminals"
|
"devices": "Counter terminals"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"access": "Use the counter POS"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"pricing": {
|
"pricing": {
|
||||||
"name": "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": {
|
"reports": {
|
||||||
"name": "Reports",
|
"name": "Reports",
|
||||||
"description": "Full sales, product, staff and printer reports, CSV export and printed reports.",
|
"description": "Full sales, product, staff and printer reports, CSV export and printed reports.",
|
||||||
"limits": {
|
"limits": {
|
||||||
"history_days": "Days of history reports can cover"
|
"history_days": "Days of history reports can cover"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"view": "See reports"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"reservations": {
|
"reservations": {
|
||||||
"name": "Reservations",
|
"name": "Reservations",
|
||||||
"description": "Table reservations."
|
"description": "Table reservations.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Add and edit reservations"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"signage": {
|
"signage": {
|
||||||
"name": "Digital signage",
|
"name": "Digital signage",
|
||||||
"description": "Menus and promotions on TVs (coming soon).",
|
"description": "Menus and promotions on TVs (coming soon).",
|
||||||
"limits": {
|
"limits": {
|
||||||
"devices": "Signage screens"
|
"devices": "Signage screens"
|
||||||
|
},
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Edit signage content"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"staff_planning": {
|
"staff_planning": {
|
||||||
"name": "Staff planning",
|
"name": "Staff planning",
|
||||||
"description": "Shift schedule and payroll."
|
"description": "Shift schedule and payroll.",
|
||||||
|
"permissions": {
|
||||||
|
"manage": "Plan shifts and see payroll"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"tabs": {
|
"tabs": {
|
||||||
"name": "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": {
|
"waiter_app": {
|
||||||
"name": "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"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,8 +14,8 @@
|
|||||||
"check": "node scripts/check-i18n.mjs"
|
"check": "node scripts/check-i18n.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"i18next": "26.7.2",
|
"i18next": "27.1.1",
|
||||||
"react-i18next": "17.1.13"
|
"react-i18next": "18.0.1"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react": "^19.0.0"
|
"react": "^19.0.0"
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import i18next from 'i18next'
|
|||||||
import { initReactI18next } from 'react-i18next'
|
import { initReactI18next } from 'react-i18next'
|
||||||
import { FALLBACK_LANGUAGE, SUPPORTED_LANGUAGES, normalizeLanguage } from './locale.js'
|
import { FALLBACK_LANGUAGE, SUPPORTED_LANGUAGES, normalizeLanguage } from './locale.js'
|
||||||
import { NAMESPACES, resources } from './resources.js'
|
import { NAMESPACES, resources } from './resources.js'
|
||||||
|
import { BASE_OPTIONS } from './options.js'
|
||||||
|
|
||||||
const DEV = typeof import.meta !== 'undefined' && !!import.meta.env?.DEV
|
const DEV = typeof import.meta !== 'undefined' && !!import.meta.env?.DEV
|
||||||
|
|
||||||
@@ -21,14 +22,9 @@ export function createI18n({ language = FALLBACK_LANGUAGE, defaultNS = 'common',
|
|||||||
i18n.use(initReactI18next).init({
|
i18n.use(initReactI18next).init({
|
||||||
resources: mergeResources(resources, extra),
|
resources: mergeResources(resources, extra),
|
||||||
lng: normalizeLanguage(language) || FALLBACK_LANGUAGE,
|
lng: normalizeLanguage(language) || FALLBACK_LANGUAGE,
|
||||||
fallbackLng: FALLBACK_LANGUAGE,
|
...BASE_OPTIONS,
|
||||||
supportedLngs: SUPPORTED_LANGUAGES,
|
|
||||||
ns: NAMESPACES,
|
ns: NAMESPACES,
|
||||||
defaultNS,
|
defaultNS,
|
||||||
fallbackNS: 'common',
|
|
||||||
interpolation: { escapeValue: false }, // React escapes already
|
|
||||||
returnNull: false,
|
|
||||||
initAsync: false,
|
|
||||||
saveMissing: DEV,
|
saveMissing: DEV,
|
||||||
missingKeyHandler: DEV ? (lngs, ns, key) => console.warn(`[i18n] missing key "${ns}:${key}" (${lngs.join(', ')})`) : undefined,
|
missingKeyHandler: DEV ? (lngs, ns, key) => console.warn(`[i18n] missing key "${ns}:${key}" (${lngs.join(', ')})`) : undefined,
|
||||||
react: { useSuspense: false },
|
react: { useSuspense: false },
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
// The i18next options every app shares (createI18n in i18n.js adds resources, language and
|
||||||
|
// namespaces). Kept apart from the locale files so node tests can import it (tests/instance.test.mjs).
|
||||||
|
import { FALLBACK_LANGUAGE, SUPPORTED_LANGUAGES } from './locale.js'
|
||||||
|
|
||||||
|
export const BASE_OPTIONS = {
|
||||||
|
fallbackLng: FALLBACK_LANGUAGE,
|
||||||
|
supportedLngs: SUPPORTED_LANGUAGES,
|
||||||
|
fallbackNS: 'common',
|
||||||
|
interpolation: { escapeValue: false }, // React escapes already
|
||||||
|
returnNull: false,
|
||||||
|
returnEmptyString: true, // i18next 27 made '' fall back like a missing key; a few texts are '' on purpose (e.g. an untitled column)
|
||||||
|
initAsync: false,
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
// The shared i18next options (src/options.js) on i18next itself. Guards what i18next 27
|
||||||
|
// changed (plan step 2.99c): empty texts, fallback language, language code casing, plurals.
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import i18next from 'i18next'
|
||||||
|
import { BASE_OPTIONS } from '../src/options.js'
|
||||||
|
|
||||||
|
const make = (lng, resources) => {
|
||||||
|
const i18n = i18next.createInstance()
|
||||||
|
i18n.init({ ...BASE_OPTIONS, lng, resources, ns: ['common'], defaultNS: 'common' })
|
||||||
|
return i18n
|
||||||
|
}
|
||||||
|
const RES = {
|
||||||
|
en: { common: { empty: '', onlyEn: 'Only English', times_one: '{{count}} time', times_other: '{{count}} times' } },
|
||||||
|
el: { common: { empty: '', times_one: '{{count}} φορά', times_other: '{{count}} φορές' } },
|
||||||
|
}
|
||||||
|
|
||||||
|
test('an empty text stays empty (i18next 27 alone would show the key)', () => {
|
||||||
|
assert.equal(make('en', RES).t('empty'), '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('a key Greek lacks falls back to English', () => {
|
||||||
|
assert.equal(make('el', RES).t('onlyEn'), 'Only English')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('language code casing and plurals', () => {
|
||||||
|
assert.equal(make('EN', RES).language, 'en')
|
||||||
|
assert.equal(make('en', RES).t('times', { count: 1 }), '1 time')
|
||||||
|
assert.equal(make('el', RES).t('times', { count: 3 }), '3 φορές')
|
||||||
|
})
|
||||||
@@ -22,3 +22,4 @@ export { Field, Input, Textarea, Select } from './components/Field.jsx'
|
|||||||
export { Switch } from './components/Switch.jsx'
|
export { Switch } from './components/Switch.jsx'
|
||||||
export { UiLabelsProvider, DEFAULT_LABELS } from './components/labels.js'
|
export { UiLabelsProvider, DEFAULT_LABELS } from './components/labels.js'
|
||||||
export { cx } from './internal/cx.js'
|
export { cx } from './internal/cx.js'
|
||||||
|
export { THEMES, THEME_STORAGE_KEY, applyTheme, getStoredTheme } from './theme.js'
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// The colour theme of an app (plan step 2.6f): light | dark | system (follows the OS).
|
||||||
|
// tokens.css reads it from data-theme on <html>. The choice is per device (localStorage),
|
||||||
|
// like a screen setting, not per user. No React here.
|
||||||
|
//
|
||||||
|
// applyTheme(getStoredTheme()) at startup
|
||||||
|
// applyTheme('dark', { save: true }) when the user picks one
|
||||||
|
//
|
||||||
|
// The manager offers the choice only once its older pages use the tokens (phase 6): until
|
||||||
|
// then it always applies 'light' (decided 2026-11-14), so a saved choice waits unused.
|
||||||
|
|
||||||
|
export const THEMES = ['light', 'dark', 'system']
|
||||||
|
export const THEME_STORAGE_KEY = 'xenia_theme'
|
||||||
|
|
||||||
|
const browserStorage = () => { try { return globalThis.localStorage ?? null } catch { return null } }
|
||||||
|
|
||||||
|
/** The saved theme, or 'light'. */
|
||||||
|
export function getStoredTheme(storage = browserStorage()) {
|
||||||
|
try {
|
||||||
|
const v = storage?.getItem(THEME_STORAGE_KEY)
|
||||||
|
return THEMES.includes(v) ? v : 'light'
|
||||||
|
} catch {
|
||||||
|
return 'light'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Set data-theme on the root element (and save it when asked). Unknown values become 'light'. */
|
||||||
|
export function applyTheme(theme, { root = globalThis.document?.documentElement, storage = browserStorage(), save = false } = {}) {
|
||||||
|
const t = THEMES.includes(theme) ? theme : 'light'
|
||||||
|
root?.setAttribute('data-theme', t)
|
||||||
|
if (save) {
|
||||||
|
try { storage?.setItem(THEME_STORAGE_KEY, t) } catch { /* private mode: not remembered */ }
|
||||||
|
}
|
||||||
|
return t
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { test } from 'node:test'
|
||||||
|
import { applyTheme, getStoredTheme, THEME_STORAGE_KEY } from '../src/theme.js'
|
||||||
|
|
||||||
|
const memory = () => { const m = new Map(); return { getItem: k => m.get(k) ?? null, setItem: (k, v) => m.set(k, v) } }
|
||||||
|
const element = () => { const a = {}; return { setAttribute: (k, v) => { a[k] = v }, attrs: a } }
|
||||||
|
|
||||||
|
test('stored theme: light unless a known one is saved', () => {
|
||||||
|
const s = memory()
|
||||||
|
assert.equal(getStoredTheme(s), 'light')
|
||||||
|
s.setItem(THEME_STORAGE_KEY, 'neon')
|
||||||
|
assert.equal(getStoredTheme(s), 'light')
|
||||||
|
s.setItem(THEME_STORAGE_KEY, 'system')
|
||||||
|
assert.equal(getStoredTheme(s), 'system')
|
||||||
|
assert.equal(getStoredTheme({ getItem: () => { throw new Error('blocked') } }), 'light')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('applyTheme sets data-theme and saves only when asked', () => {
|
||||||
|
const s = memory()
|
||||||
|
const root = element()
|
||||||
|
assert.equal(applyTheme('dark', { root, storage: s }), 'dark')
|
||||||
|
assert.equal(root.attrs['data-theme'], 'dark')
|
||||||
|
assert.equal(getStoredTheme(s), 'light')
|
||||||
|
applyTheme('dark', { root, storage: s, save: true })
|
||||||
|
assert.equal(getStoredTheme(s), 'dark')
|
||||||
|
assert.equal(applyTheme('bogus', { root, storage: s }), 'light')
|
||||||
|
})
|
||||||
+3
-1
@@ -20,6 +20,8 @@ npm test -w @xenia/ui # PIN rules + WCAG contrast of every to
|
|||||||
npm test -w @xenia/i18n # venue-time formatting (DST), money/numbers, comma-or-dot parsing, language order, check-i18n guard, error texts vs core/errors.py
|
npm test -w @xenia/i18n # venue-time formatting (DST), money/numbers, comma-or-dot parsing, language order, check-i18n guard, error texts vs core/errors.py
|
||||||
npm test -w @xenia/api # live client = the waiter's old WebSocket behaviour (backoff, cursor, online); HTTP client vs a fake backend (headers, codes, 401, offline, approval retry)
|
npm test -w @xenia/api # live client = the waiter's old WebSocket behaviour (backoff, cursor, online); HTTP client vs a fake backend (headers, codes, 401, offline, approval retry)
|
||||||
npm test -w @xenia/access # can(): one key, any/all
|
npm test -w @xenia/access # can(): one key, any/all
|
||||||
|
npm test -w manager-dashboard # platform pages' logic: module states, what stops with a module, device status/usage/limits
|
||||||
|
npm run lint -w manager-dashboard # ESLint (waiter rules) on the manager's v2 code; the file list is the `lint` script
|
||||||
```
|
```
|
||||||
|
|
||||||
**DB tests** (`local_backend/tests/conftest.py`) run the real FastAPI app against a throwaway SQLite database in a temp folder (never your dev or venue DB). Fixtures: `db` (session, rolled back after each test even if the code commits), `client` (TestClient with `get_db` overridden, license check open, no lifespan), `make_user(role=..., perms=...)` (password `password`, PIN `1234`), `login(user)` (auth headers). A test that uses any of them is marked `db` automatically.
|
**DB tests** (`local_backend/tests/conftest.py`) run the real FastAPI app against a throwaway SQLite database in a temp folder (never your dev or venue DB). Fixtures: `db` (session, rolled back after each test even if the code commits), `client` (TestClient with `get_db` overridden, license check open, no lifespan), `make_user(role=..., perms=...)` (password `password`, PIN `1234`), `login(user)` (auth headers). A test that uses any of them is marked `db` automatically.
|
||||||
@@ -40,7 +42,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 |
|
| `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 |
|
| `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 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); the notification bell (live, read, read all), sign-in/venue/print settings, log download; the **owner flow** (sign in → turn on KDS → pair a screen → give a chef the kitchen permissions → the chef signs in on that screen) | 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 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 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 |
|
| `node android.mjs rediscovery` | Server IP change (logged in / out), server down + manual search, cold start while offline | Android emulator | ~4 min |
|
||||||
|
|||||||
+329
-4
@@ -6,12 +6,12 @@
|
|||||||
// ended session logs out), a module turned off, and the manager-approval dialog.
|
// ended session logs out), a module turned off, and the manager-approval dialog.
|
||||||
// node manager.mjs
|
// node manager.mjs
|
||||||
import { spawn } from 'node:child_process'
|
import { spawn } from 'node:child_process'
|
||||||
import { openSync } from 'node:fs'
|
import { openSync, readFileSync } from 'node:fs'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
import { chromium } from 'playwright'
|
import { chromium } from 'playwright'
|
||||||
import { BROWSER_CHANNEL, CS, OUT, reporter, sleep } from './lib/env.mjs'
|
import { BROWSER_CHANNEL, CS, OUT, reporter, sleep } from './lib/env.mjs'
|
||||||
import { killTree, startBackend, waitHttp } from './lib/proc.mjs'
|
import { killTree, startBackend, waitHttp } from './lib/proc.mjs'
|
||||||
import { SUPPORT_MASTER, codeFor, siteSecret } from './lib/support.mjs'
|
import { SUPPORT_MASTER, codeFor, siteSecret, supportLogin } from './lib/support.mjs'
|
||||||
|
|
||||||
const PORT = 5186
|
const PORT = 5186
|
||||||
const APP = `http://localhost:${PORT}`
|
const APP = `http://localhost:${PORT}`
|
||||||
@@ -35,7 +35,16 @@ async function api(method, url, { token, body } = {}) {
|
|||||||
if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 200)}`)
|
if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 200)}`)
|
||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
const loginApi = (username, secret) => api('POST', '/api/auth/login', { body: { username, ...secret } }).then(d => d.access_token)
|
// A device's side of pairing (what the terminal app will do in phase 3)
|
||||||
|
async function deviceRequestsPairing() {
|
||||||
|
return api('POST', '/api/devices/pair-request')
|
||||||
|
}
|
||||||
|
async function devicePicksUpToken(req) {
|
||||||
|
const res = await fetch(`${backend.url}/api/devices/pair-request/${req.code}`, { headers: { 'X-Xenia-Pair-Secret': req.secret } })
|
||||||
|
return (await res.json()).device_token
|
||||||
|
}
|
||||||
|
const asDevice = (token, url) => fetch(`${backend.url}${url}`, { headers: { 'X-Xenia-Device': token } })
|
||||||
|
const loginApi = (username, secret) => api('POST', '/api/auth/login', { body: { client: 'manager', username, ...secret } }).then(d => d.access_token)
|
||||||
|
|
||||||
async function uiLogin(page, password) {
|
async function uiLogin(page, password) {
|
||||||
await page.goto(`${APP}/login`)
|
await page.goto(`${APP}/login`)
|
||||||
@@ -145,6 +154,58 @@ try {
|
|||||||
await card('notes').waitFor()
|
await card('notes').waitFor()
|
||||||
await page.screenshot({ path: path.join(OUT, 'manager-apps.png'), fullPage: true })
|
await page.screenshot({ path: path.join(OUT, 'manager-apps.png'), fullPage: true })
|
||||||
|
|
||||||
|
// ── 2.6d: Devices: pair by code, edit, change app, remove ──────────────────
|
||||||
|
await page.goto(`${APP}/devices`)
|
||||||
|
await page.getByTestId('device-usage').waitFor({ timeout: 15_000 })
|
||||||
|
r.check('devices: empty state before any pairing', await page.getByText('No devices yet').count() === 1)
|
||||||
|
const dlg = page.getByRole('dialog')
|
||||||
|
await page.getByRole('button', { name: 'Pair a device' }).first().click()
|
||||||
|
await dlg.getByLabel('Code shown on the device').fill('zz-zz-zz')
|
||||||
|
await dlg.getByLabel('App to run').selectOption('kds')
|
||||||
|
await dlg.getByLabel('Name').fill('Kitchen')
|
||||||
|
await dlg.getByRole('button', { name: 'Pair a device' }).click()
|
||||||
|
await page.getByTestId('pair-error').waitFor({ timeout: 5000 }).catch(() => {})
|
||||||
|
r.check('devices: a wrong code is refused with a message', (await page.getByTestId('pair-error').textContent().catch(() => '')).includes('pairing code is wrong'))
|
||||||
|
const req = await deviceRequestsPairing()
|
||||||
|
const typed = `${req.code.slice(0, 3).toLowerCase()}-${req.code.slice(3).toLowerCase()}`
|
||||||
|
await dlg.getByLabel('Code shown on the device').fill(typed)
|
||||||
|
r.check('devices: the code is normalized as typed (lower case, dash)', await dlg.getByLabel('Code shown on the device').inputValue() === req.code)
|
||||||
|
await dlg.getByLabel('How staff sign in').selectOption('pin')
|
||||||
|
await dlg.getByRole('button', { name: 'Pair a device' }).click()
|
||||||
|
await page.waitForFunction(() => document.querySelectorAll('[data-testid^="device-"][data-status]').length === 1, null, { timeout: 8000 }).catch(() => {})
|
||||||
|
const row = page.locator('[data-testid^="device-"][data-status]').first()
|
||||||
|
r.check('devices: paired → listed as "waiting for the device"', await row.getAttribute('data-status') === 'waiting' && (await row.textContent()).includes('Kitchen'))
|
||||||
|
const deviceToken = await devicePicksUpToken(req)
|
||||||
|
const me = await asDevice(deviceToken, '/api/devices/me').then(x => x.json())
|
||||||
|
r.check('devices: the device got its token and runs the kitchen display', me.app_key === 'kds' && me.name === 'Kitchen' && me.login_mode === 'pin', JSON.stringify(me))
|
||||||
|
await page.reload()
|
||||||
|
await row.waitFor({ timeout: 10_000 })
|
||||||
|
r.check('devices: after it connected → "Online", sign-in PIN', await row.getAttribute('data-status') === 'online' && (await row.textContent()).includes('PIN'))
|
||||||
|
r.check('devices: usage shows kitchen screens in use', (await page.getByTestId('device-usage').textContent()).includes('Kitchen screens: 1'))
|
||||||
|
|
||||||
|
await row.getByRole('button', { name: 'Edit' }).click()
|
||||||
|
await dlg.getByLabel('Name').fill('Kitchen 1')
|
||||||
|
await dlg.getByRole('button', { name: 'Save' }).click()
|
||||||
|
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Kitchen 1'), null, { timeout: 8000 }).catch(() => {})
|
||||||
|
r.check('devices: renamed', (await row.textContent()).includes('Kitchen 1') && (await asDevice(deviceToken, '/api/devices/me').then(x => x.json())).name === 'Kitchen 1')
|
||||||
|
|
||||||
|
await row.getByRole('button', { name: 'Change app' }).click()
|
||||||
|
await dlg.getByLabel('App to run').selectOption('pos_counter')
|
||||||
|
await dlg.getByRole('button', { name: 'Save' }).click()
|
||||||
|
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Counter POS'), null, { timeout: 8000 }).catch(() => {})
|
||||||
|
r.check('devices: app changed to Counter POS (the device follows)', (await row.textContent()).includes('Counter POS') && (await asDevice(deviceToken, '/api/devices/me').then(x => x.json())).app_key === 'pos_counter')
|
||||||
|
await page.screenshot({ path: path.join(OUT, 'manager-devices.png'), fullPage: true })
|
||||||
|
|
||||||
|
await row.getByRole('button', { name: 'Remove' }).click()
|
||||||
|
await dlg.getByRole('button', { name: 'Remove' }).click()
|
||||||
|
await page.getByText('No devices yet').waitFor({ timeout: 8000 }).catch(() => {})
|
||||||
|
const after = await asDevice(deviceToken, '/api/devices/me')
|
||||||
|
r.check('devices: removed → gone from the list, the device is refused (device.revoked)',
|
||||||
|
await page.getByText('No devices yet').count() === 1 && after.status === 401 && (await after.json()).error.code === 'device.revoked')
|
||||||
|
await page.getByLabel('Show removed devices').check()
|
||||||
|
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status="removed"]'), null, { timeout: 8000 }).catch(() => {})
|
||||||
|
r.check('devices: "show removed" lists it as removed', await page.locator('[data-status="removed"]').count() === 1)
|
||||||
|
|
||||||
// ── Lock screen: a wrong PIN stays locked (no logout), the right one unlocks ─
|
// ── Lock screen: a wrong PIN stays locked (no logout), the right one unlocks ─
|
||||||
await page.goto(`${APP}/dashboard`)
|
await page.goto(`${APP}/dashboard`)
|
||||||
await sleep(1500)
|
await sleep(1500)
|
||||||
@@ -216,7 +277,10 @@ try {
|
|||||||
await page.getByLabel("Support's code").fill(codeFor(siteSecret(SUPPORT_MASTER, 'test-site-1'), 'test-site-1', challenge))
|
await page.getByLabel("Support's code").fill(codeFor(siteSecret(SUPPORT_MASTER, 'test-site-1'), 'test-site-1', challenge))
|
||||||
await page.getByRole('button', { name: 'Open support session' }).click()
|
await page.getByRole('button', { name: 'Open support session' }).click()
|
||||||
await page.waitForURL(u => u.pathname === '/dashboard', { timeout: 10_000 }).catch(() => {})
|
await page.waitForURL(u => u.pathname === '/dashboard', { timeout: 10_000 }).catch(() => {})
|
||||||
r.check('support: the right code opens a session', new URL(page.url()).pathname === '/dashboard', page.url())
|
const supportOk = new URL(page.url()).pathname === '/dashboard'
|
||||||
|
if (!supportOk) await page.screenshot({ path: path.join(OUT, 'manager-support-access-FAILED.png') }) // seen failing once in ~8 runs (2.99a, 2.99d)
|
||||||
|
r.check('support: the right code opens a session', supportOk,
|
||||||
|
supportOk ? page.url() : `${page.url()} alert=${JSON.stringify(await page.getByRole('alert').allTextContents().catch(() => []))}`)
|
||||||
await page.evaluate(() => { localStorage.removeItem('manager_token') })
|
await page.evaluate(() => { localStorage.removeItem('manager_token') })
|
||||||
await uiLogin(page, 'password')
|
await uiLogin(page, 'password')
|
||||||
await page.waitForURL(u => u.pathname === '/dashboard', { timeout: 10_000 }).catch(() => {})
|
await page.waitForURL(u => u.pathname === '/dashboard', { timeout: 10_000 }).catch(() => {})
|
||||||
@@ -278,6 +342,267 @@ 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]))
|
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') })
|
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 } })
|
||||||
|
// new staff have only a PIN: sign them in while managers use PINs, then back to passwords
|
||||||
|
await api('PUT', '/api/settings/auth.manager_login_mode', { token: boss, body: { value: 'pin' } })
|
||||||
|
const smToken = await loginApi('e2e_staffmgr', { pin: '5151' })
|
||||||
|
await api('PUT', '/api/settings/auth.manager_login_mode', { token: boss, body: { value: 'password' } })
|
||||||
|
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'))
|
||||||
|
|
||||||
|
// ── 2.6f: notification bell (live), settings pages, log download ───────────
|
||||||
|
await page.goto(`${APP}/dashboard`)
|
||||||
|
const bell = page.getByTestId('notif-bell')
|
||||||
|
await bell.waitFor({ timeout: 10_000 })
|
||||||
|
await page.getByTestId('notif-count').waitFor({ timeout: 8000 }).catch(() => {})
|
||||||
|
r.check('bell: unread count from the earlier support sign-ins', Number((await page.getByTestId('notif-count').textContent().catch(() => '0')).replace('+', '')) >= 1)
|
||||||
|
await bell.click()
|
||||||
|
const panel = page.getByTestId('notif-panel')
|
||||||
|
r.check('bell: the list says support signed in, in plain words', (await panel.textContent()).includes('Xenia support logged in'))
|
||||||
|
await page.getByTestId('notif-read-all').click()
|
||||||
|
await page.getByTestId('notif-count').waitFor({ state: 'detached', timeout: 5000 }).catch(() => {})
|
||||||
|
r.check('bell: "mark all as read" clears the count', await page.getByTestId('notif-count').count() === 0)
|
||||||
|
await bell.click() // close
|
||||||
|
await sleep(1500) // the live socket is up (opened with the shell)
|
||||||
|
await supportLogin(backend.url)
|
||||||
|
await page.getByTestId('notif-count').waitFor({ timeout: 8000 }).catch(() => {})
|
||||||
|
r.check('bell: a new one arrives live (no reload): count 1 and a toast',
|
||||||
|
await page.getByTestId('notif-count').textContent().catch(() => '') === '1' && await page.getByText('Xenia support logged in').count() >= 1)
|
||||||
|
await bell.click()
|
||||||
|
const unreadItem = panel.locator('[data-read="false"]').first()
|
||||||
|
await unreadItem.click()
|
||||||
|
await page.waitForFunction(() => !document.querySelector('[data-testid="notif-count"]'), null, { timeout: 5000 }).catch(() => {})
|
||||||
|
r.check('bell: opening it marks it read', await page.getByTestId('notif-count').count() === 0 &&
|
||||||
|
(await api('GET', '/api/platform/notifications', { token: boss })).unread === 0)
|
||||||
|
await page.screenshot({ path: path.join(OUT, 'manager-notifications.png') })
|
||||||
|
await page.keyboard.press('Escape')
|
||||||
|
|
||||||
|
const settingValue = async key => (await api('GET', '/api/settings/', { token: boss }))[key].value
|
||||||
|
// KI-010: Online Orders refreshes from the shared live connection, never /api/stream
|
||||||
|
const ooUrls = []
|
||||||
|
const ooListen = req => ooUrls.push(new URL(req.url()).pathname)
|
||||||
|
page.on('request', ooListen)
|
||||||
|
await page.goto(`${APP}/online-orders`)
|
||||||
|
await sleep(5000)
|
||||||
|
page.off('request', ooListen)
|
||||||
|
r.check('online orders: loads its lists and never asks for the old /api/stream',
|
||||||
|
ooUrls.some(u => u.startsWith('/api/connect/orders')) && !ooUrls.some(u => u.startsWith('/api/stream')), [...new Set(ooUrls)].filter(u => u.startsWith('/api/')).join(' '))
|
||||||
|
|
||||||
|
await page.goto(`${APP}/settings`)
|
||||||
|
await page.getByText('Sign-in & security', { exact: true }).click()
|
||||||
|
const waiterMode = page.getByTestId('setting-auth.waiter_login_mode')
|
||||||
|
await waiterMode.waitFor({ timeout: 10_000 })
|
||||||
|
await waiterMode.selectOption('tap')
|
||||||
|
await page.getByRole('note').waitFor({ timeout: 5000 }).catch(() => {})
|
||||||
|
r.check('settings: waiter sign-in → "Tap your name" is saved and warns it needs paired devices',
|
||||||
|
await settingValue('auth.waiter_login_mode') === 'tap' && (await page.getByRole('note').textContent()).includes('only on paired devices'))
|
||||||
|
await waiterMode.selectOption('pin')
|
||||||
|
await page.getByTestId('setting-auth.manager_login_mode').selectOption('pin')
|
||||||
|
await sleep(800)
|
||||||
|
r.check('settings: manager sign-in → PIN reaches the sign-in page (bootstrap)',
|
||||||
|
(await api('GET', '/api/platform/bootstrap')).login.manager_mode === 'pin')
|
||||||
|
await page.screenshot({ path: path.join(OUT, 'manager-settings-sign-in.png'), fullPage: true })
|
||||||
|
await page.getByTestId('setting-auth.manager_login_mode').selectOption('password')
|
||||||
|
await page.getByTestId('setting-auth.single_session_waiter').selectOption('end_old')
|
||||||
|
await sleep(800)
|
||||||
|
r.check('settings: one session per waiter → "sign out the older one"', await settingValue('auth.single_session_waiter') === 'end_old' &&
|
||||||
|
await settingValue('auth.manager_login_mode') === 'password' && await settingValue('auth.waiter_login_mode') === 'pin')
|
||||||
|
await page.getByTestId('setting-auth.single_session_waiter').selectOption('off')
|
||||||
|
const idleSel = page.getByTestId('setting-auth.idle_days')
|
||||||
|
const idleDefault = await idleSel.inputValue()
|
||||||
|
await idleSel.selectOption('30')
|
||||||
|
await sleep(800)
|
||||||
|
r.check('settings: sign out after 14 days by default; 30 days is saved', idleDefault === '14' && await settingValue('auth.idle_days') === '30', idleDefault)
|
||||||
|
await idleSel.selectOption('14')
|
||||||
|
|
||||||
|
await page.getByText('Venue & language', { exact: true }).click()
|
||||||
|
const tzSelect = page.getByTestId('setting-venue.timezone')
|
||||||
|
await tzSelect.waitFor({ timeout: 10_000 })
|
||||||
|
await tzSelect.selectOption('Europe/London')
|
||||||
|
await sleep(800)
|
||||||
|
await page.getByTestId('setting-venue.language').selectOption('el')
|
||||||
|
await sleep(800)
|
||||||
|
const venue = (await api('GET', '/api/platform/bootstrap')).venue
|
||||||
|
r.check('settings: time zone and venue language saved (bootstrap says Europe/London, el)', venue.timezone === 'Europe/London' && venue.language === 'el', JSON.stringify(venue))
|
||||||
|
await page.screenshot({ path: path.join(OUT, 'manager-settings-venue.png'), fullPage: true })
|
||||||
|
await page.getByTestId('setting-venue.language').selectOption('en')
|
||||||
|
await sleep(800)
|
||||||
|
await tzSelect.selectOption('Europe/Athens')
|
||||||
|
await sleep(800)
|
||||||
|
|
||||||
|
await page.getByText('Printing', { exact: true }).click()
|
||||||
|
const alertSel = page.getByTestId('setting-print.alert_after_failures')
|
||||||
|
await alertSel.waitFor({ timeout: 10_000 })
|
||||||
|
await alertSel.selectOption('5')
|
||||||
|
await sleep(800)
|
||||||
|
r.check('settings: print alert after 5 failed attempts', await settingValue('print.alert_after_failures') === '5')
|
||||||
|
await alertSel.selectOption('2')
|
||||||
|
await sleep(500)
|
||||||
|
|
||||||
|
await page.goto(`${APP}/reports/technical`)
|
||||||
|
await page.getByText('Log files', { exact: true }).click()
|
||||||
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
|
const logRow = page.getByTestId(`log-${today}`)
|
||||||
|
await logRow.waitFor({ timeout: 10_000 }).catch(() => {})
|
||||||
|
r.check("logs: today's file is listed (still being written)", (await logRow.textContent().catch(() => '')).includes('still being written'))
|
||||||
|
const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 10_000 }), logRow.getByRole('button', { name: 'Download' }).click()])
|
||||||
|
const dlText = readFileSync(await dl.path(), 'utf-8')
|
||||||
|
r.check('logs: Download saves xenia-<day>.log with the backend\'s lines', dl.suggestedFilename() === `xenia-${today}.log` && dlText.includes('session.started'), dl.suggestedFilename())
|
||||||
|
await s2.goto(`${APP}/reports/technical`)
|
||||||
|
await s2.getByText('Printer history').or(s2.getByText('Ιστορικό Εκτυπωτή')).first().waitFor({ timeout: 10_000 }).catch(() => {})
|
||||||
|
r.check('logs: a staff manager has no "Log files" tab (owner-level)', await s2.getByText('Log files', { exact: true }).count() === 0)
|
||||||
|
|
||||||
|
// ── 2.6g: the owner flow (plan step 2.6 "done when") ───────────────────────
|
||||||
|
// log in → enable KDS → pair a device → give a chef kds.access → the chef logs in on it.
|
||||||
|
// The device's side is played through the API until the terminal app exists (phase 3).
|
||||||
|
const ownerFlow = 'owner flow:'
|
||||||
|
await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: false } }) // start with KDS off
|
||||||
|
const chef = await api('POST', '/api/waiters/', { token: boss, body: { username: 'e2e_chef', full_name: 'Kostas Chef', pin: '4747', role: 'custom', is_active: true } })
|
||||||
|
const o = await (await browser.newContext({ viewport: { width: 1400, height: 900 } })).newPage()
|
||||||
|
o.on('pageerror', e => errors.push(e.message))
|
||||||
|
// 1. log in
|
||||||
|
await uiLogin(o, 'password')
|
||||||
|
await o.waitForURL(u => u.pathname === '/dashboard', { timeout: 15_000 }).catch(() => {})
|
||||||
|
r.check(`${ownerFlow} 1. the owner signs in`, new URL(o.url()).pathname === '/dashboard', o.url())
|
||||||
|
// 2. enable KDS on the Apps page
|
||||||
|
await o.goto(`${APP}/apps`)
|
||||||
|
const kdsCard = o.getByTestId('module-kds')
|
||||||
|
await kdsCard.waitFor({ timeout: 10_000 })
|
||||||
|
const offBefore = await kdsCard.getAttribute('data-state')
|
||||||
|
await kdsCard.getByRole('switch').click()
|
||||||
|
await o.waitForFunction(() => document.querySelector('[data-testid="module-kds"]')?.getAttribute('data-state') === 'on', null, { timeout: 8000 }).catch(() => {})
|
||||||
|
r.check(`${ownerFlow} 2. KDS turned on from its card`, offBefore === 'off' && await kdsCard.getAttribute('data-state') === 'on')
|
||||||
|
// 3. the screen shows a code; the owner pairs it on the Devices page
|
||||||
|
const kitchenReq = await deviceRequestsPairing()
|
||||||
|
await o.goto(`${APP}/devices`)
|
||||||
|
await o.getByTestId('device-usage').waitFor({ timeout: 10_000 })
|
||||||
|
await o.getByRole('button', { name: 'Pair a device' }).first().click()
|
||||||
|
const odlg = o.getByRole('dialog')
|
||||||
|
await odlg.getByLabel('Code shown on the device').fill(kitchenReq.code)
|
||||||
|
await odlg.getByLabel('App to run').selectOption('kds')
|
||||||
|
await odlg.getByLabel('Name').fill('Kitchen pass')
|
||||||
|
await odlg.getByLabel('How staff sign in').selectOption('pin')
|
||||||
|
await odlg.getByRole('button', { name: 'Pair a device' }).click()
|
||||||
|
await odlg.waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
|
||||||
|
const kitchenToken = await devicePicksUpToken(kitchenReq)
|
||||||
|
const kitchenMe = await asDevice(kitchenToken, '/api/devices/me').then(x => x.json())
|
||||||
|
r.check(`${ownerFlow} 3. the screen is paired as "Kitchen pass", a kitchen display with PIN sign-in`,
|
||||||
|
kitchenMe.app_key === 'kds' && kitchenMe.name === 'Kitchen pass' && kitchenMe.login_mode === 'pin', JSON.stringify(kitchenMe))
|
||||||
|
const chefOnDevice = () => fetch(`${backend.url}/api/auth/login`, {
|
||||||
|
method: 'POST', headers: { 'content-type': 'application/json', 'X-Xenia-Device': kitchenToken },
|
||||||
|
body: JSON.stringify({ client: 'terminal', user_id: chef.id, pin: '4747' }),
|
||||||
|
})
|
||||||
|
const refused = await chefOnDevice()
|
||||||
|
r.check(`${ownerFlow} …before the permission, the chef is refused on that screen`,
|
||||||
|
refused.status === 403 && (await refused.json()).error.code === 'auth.client_not_allowed')
|
||||||
|
// 4. give the chef the kitchen permissions in the editor
|
||||||
|
await o.goto(`${APP}/management/staff`)
|
||||||
|
await o.getByTestId(`staff-perms-${chef.id}`).getByRole('button').click()
|
||||||
|
await o.getByTestId('perm-editor').waitFor({ timeout: 10_000 })
|
||||||
|
await o.getByTestId('perm-kds.access').getByRole('switch').click()
|
||||||
|
await o.getByTestId('perm-kds.bump').getByRole('switch').click()
|
||||||
|
await o.getByRole('button', { name: 'Save 2 changes' }).click()
|
||||||
|
await o.getByTestId('perm-editor').waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
|
||||||
|
const chefKeys = (await api('GET', `/api/waiters/${chef.id}/permissions`, { token: boss })).keys
|
||||||
|
r.check(`${ownerFlow} 4. the chef now has kds.access and kds.bump`, chefKeys.includes('kds.access') && chefKeys.includes('kds.bump'), JSON.stringify(chefKeys))
|
||||||
|
// 5. the chef signs in on the kitchen screen with their PIN
|
||||||
|
const chefLogin = await chefOnDevice()
|
||||||
|
const chefSession = chefLogin.status === 200 ? (await chefLogin.json()).access_token : null
|
||||||
|
const kdsOrders = chefSession && await fetch(`${backend.url}/api/kds/orders`, { headers: { authorization: `Bearer ${chefSession}`, 'X-Xenia-Device': kitchenToken } })
|
||||||
|
r.check(`${ownerFlow} 5. the chef signs in on that screen and sees the kitchen orders`, !!chefSession && kdsOrders.status === 200, String(chefLogin.status))
|
||||||
|
await o.goto(`${APP}/management/sessions`)
|
||||||
|
const chefRow = o.locator(`[data-user="${chef.id}"][data-client="terminal"]`)
|
||||||
|
await chefRow.waitFor({ timeout: 10_000 }).catch(() => {})
|
||||||
|
r.check(`${ownerFlow} …and the owner sees them under "Signed in now" on "Kitchen pass · Kitchen display"`,
|
||||||
|
(await chefRow.textContent().catch(() => '')).includes('Kitchen pass · Kitchen display'))
|
||||||
|
await o.screenshot({ path: path.join(OUT, 'manager-owner-flow.png'), fullPage: true })
|
||||||
|
|
||||||
r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | '))
|
r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | '))
|
||||||
} finally {
|
} finally {
|
||||||
await browser.close()
|
await browser.close()
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ const suites = [
|
|||||||
['unit: packages/i18n (node --test + guard)', 'npm', ['test', '--silent', '-w', '@xenia/i18n'], CS],
|
['unit: packages/i18n (node --test + guard)', 'npm', ['test', '--silent', '-w', '@xenia/i18n'], CS],
|
||||||
['unit: packages/api (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/api'], CS],
|
['unit: packages/api (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/api'], CS],
|
||||||
['unit: packages/access (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/access'], CS],
|
['unit: packages/access (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/access'], CS],
|
||||||
|
['unit: manager_dashboard (node --test)', 'npm', ['test', '--silent', '-w', 'manager-dashboard'], CS],
|
||||||
|
['lint: manager_dashboard (v2 code)', 'npm', ['run', 'lint', '--silent', '-w', 'manager-dashboard'], CS],
|
||||||
['install.sh', 'node', ['install.mjs'], E2E],
|
['install.sh', 'node', ['install.mjs'], E2E],
|
||||||
['license (cloud + site)', PYTHON, ['license_e2e.py'], E2E],
|
['license (cloud + site)', PYTHON, ['license_e2e.py'], E2E],
|
||||||
['browser', 'node', ['browser.mjs'], E2E],
|
['browser', 'node', ['browser.mjs'], E2E],
|
||||||
|
|||||||
+2
-1
@@ -123,7 +123,8 @@ try {
|
|||||||
await p.screenshot({ path: path.join(OUT, 'ui-gallery-dark-amber.png'), fullPage: true })
|
await p.screenshot({ path: path.join(OUT, 'ui-gallery-dark-amber.png'), fullPage: true })
|
||||||
await p.evaluate(() => { history.pushState({}, '', '/login'); dispatchEvent(new PopStateEvent('popstate')) })
|
await p.evaluate(() => { history.pushState({}, '', '/login'); dispatchEvent(new PopStateEvent('popstate')) })
|
||||||
await sleep(500)
|
await sleep(500)
|
||||||
r.check('theme: leaving the gallery restores <html>', await p.evaluate(() => !document.documentElement.hasAttribute('data-theme') && !document.documentElement.hasAttribute('data-venue-theme')))
|
// the manager sets data-theme="light" at startup (2.6f); the gallery puts that back
|
||||||
|
r.check('theme: leaving the gallery restores <html>', await p.evaluate(() => document.documentElement.getAttribute('data-theme') === 'light' && !document.documentElement.hasAttribute('data-venue-theme')))
|
||||||
|
|
||||||
r.check('no page or console errors', errs.length === 0, errs.slice(0, 3).join(' | '))
|
r.check('no page or console errors', errs.length === 0, errs.slice(0, 3).join(' | '))
|
||||||
failures += r.done()
|
failures += r.done()
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ load_license_at_startup()
|
|||||||
c = TestClient(main.app, raise_server_exceptions=False)
|
c = TestClient(main.app, raise_server_exceptions=False)
|
||||||
|
|
||||||
callers = {}
|
callers = {}
|
||||||
r = c.post("/api/auth/login", json={"username": "manager", "password": "password"})
|
r = c.post("/api/auth/login", json={"client": "manager", "username": "manager", "password": "password"})
|
||||||
if r.status_code == 200:
|
if r.status_code == 200:
|
||||||
callers["manager"] = r.json()["access_token"]
|
callers["manager"] = r.json()["access_token"]
|
||||||
row = sqlite3.connect(f"{data}/pos.db").execute("select id from users where username='demo_nikos'").fetchone()
|
row = sqlite3.connect(f"{data}/pos.db").execute("select id from users where username='demo_nikos'").fetchone()
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ android {
|
|||||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||||
// Bump BOTH for every APK handed out: Android only installs an update over
|
// Bump BOTH for every APK handed out: Android only installs an update over
|
||||||
// an existing install when versionCode is higher.
|
// an existing install when versionCode is higher.
|
||||||
versionCode 1
|
versionCode 2
|
||||||
versionName "1.0.0"
|
versionName "1.1.0"
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||||
aaptOptions {
|
aaptOptions {
|
||||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
|
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
|
||||||
include ':capacitor-android'
|
include ':capacitor-android'
|
||||||
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
|
project(':capacitor-android').projectDir = new File('../../node_modules/@capacitor/android/capacitor')
|
||||||
|
|
||||||
include ':capacitor-app'
|
include ':capacitor-app'
|
||||||
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
|
project(':capacitor-app').projectDir = new File('../../node_modules/@capacitor/app/android')
|
||||||
|
|
||||||
include ':capgo-capacitor-updater'
|
include ':capgo-capacitor-updater'
|
||||||
project(':capgo-capacitor-updater').projectDir = new File('../node_modules/@capgo/capacitor-updater/android')
|
project(':capgo-capacitor-updater').projectDir = new File('../../node_modules/@capgo/capacitor-updater/android')
|
||||||
|
|||||||
@@ -14,7 +14,8 @@
|
|||||||
"appReadyTimeout": 15000,
|
"appReadyTimeout": 15000,
|
||||||
"resetWhenUpdate": true,
|
"resetWhenUpdate": true,
|
||||||
"autoDeletePrevious": false,
|
"autoDeletePrevious": false,
|
||||||
"autoDeleteFailed": true
|
"autoDeleteFailed": true,
|
||||||
|
"httpsOnly": false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+22
-22
@@ -14,34 +14,34 @@
|
|||||||
"test": "node --test \"tests/*.test.mjs\""
|
"test": "node --test \"tests/*.test.mjs\""
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@capacitor/android": "8.5.2",
|
"@capacitor/android": "8.6.2",
|
||||||
"@capacitor/app": "8.1.1",
|
"@capacitor/app": "8.1.2",
|
||||||
"@capacitor/core": "8.5.2",
|
"@capacitor/core": "8.6.2",
|
||||||
"@capgo/capacitor-updater": "8.51.25",
|
"@capgo/capacitor-updater": "8.54.2",
|
||||||
"@tanstack/react-query": "^5.100.11",
|
"@tanstack/react-query": "^5.107.1",
|
||||||
"@xenia/api": "^0.0.0",
|
"@xenia/api": "^0.0.0",
|
||||||
"@xenia/ui": "^0.0.0",
|
"@xenia/ui": "^0.0.0",
|
||||||
"axios": "^1.15.1",
|
"axios": "^1.21.1",
|
||||||
"dexie": "^4.4.2",
|
"dexie": "^4.4.7",
|
||||||
"qr-scanner": "^1.4.2",
|
"qr-scanner": "^1.4.2",
|
||||||
"react": "^19.2.5",
|
"react": "^19.3.1",
|
||||||
"react-dom": "^19.2.5",
|
"react-dom": "^19.3.1",
|
||||||
"react-router-dom": "^7.14.1",
|
"react-router-dom": "^7.18.5",
|
||||||
"vite-plugin-pwa": "^1.2.0",
|
"vite-plugin-pwa": "^2.0.0",
|
||||||
"workbox-window": "^7.4.0",
|
"workbox-window": "^7.4.1",
|
||||||
"zustand": "^5.0.12"
|
"zustand": "^5.1.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@capacitor/cli": "8.5.2",
|
"@capacitor/cli": "8.6.2",
|
||||||
"@eslint/js": "^9.39.4",
|
"@eslint/js": "^9.39.5",
|
||||||
"@types/react": "^19.2.14",
|
"@types/react": "^19.3.0",
|
||||||
"@types/react-dom": "^19.2.3",
|
"@types/react-dom": "^19.3.0",
|
||||||
"@vitejs/plugin-react": "^6.0.1",
|
"@vitejs/plugin-react": "^6.3.0",
|
||||||
"eslint": "^9.39.4",
|
"eslint": "^9.39.5",
|
||||||
"eslint-plugin-react-hooks": "^7.1.1",
|
"eslint-plugin-react-hooks": "^7.1.1",
|
||||||
"eslint-plugin-react-refresh": "^0.5.2",
|
"eslint-plugin-react-refresh": "^0.5.7",
|
||||||
"fflate": "^0.8.3",
|
"fflate": "^0.8.3",
|
||||||
"globals": "^17.5.0",
|
"globals": "^17.14.0",
|
||||||
"vite": "^8.0.9"
|
"vite": "^8.3.8"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,4 +10,4 @@
|
|||||||
* Bump it ONLY when this web code starts depending on something new in the
|
* Bump it ONLY when this web code starts depending on something new in the
|
||||||
* native project (android/…), in the same commit that bumps versionCode.
|
* native project (android/…), in the same commit that bumps versionCode.
|
||||||
*/
|
*/
|
||||||
export const MIN_SHELL_BUILD = 1
|
export const MIN_SHELL_BUILD = 2 // 2: Capacitor 8.6.2, capacitor-updater 8.54.2 (platform-v2 2.99c)
|
||||||
|
|||||||
Reference in New Issue
Block a user