Reviews (name, stars, text, date, where) under Signage -> Message & settings, shown one at a time by the reviews widget (a minimum of stars, seconds each); not pulled from Google (owner's choice). The widgets section: one "Add a widget" menu at its top instead of a button per kind; the cards are layers, the top one drawn over the others, so a new widget goes on top; the arrows bring forward / send backward. Plan 6R.19, F-113. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
client-services — On-site Pack
Everything that runs inside the restaurant, on the local server box.
This folder is its own git repo, nested inside the xenia-pos parent repo.
Read the global rules first: ../../docs/README.md. This file adds only the rules specific to this pack. The feature catalog, the cloud contract, known issues and site records all live in the parent's
docs/.
Services
| Service | Stack | Dev port | Prod exposure | Image |
|---|---|---|---|---|
local_backend |
FastAPI + SQLAlchemy + SQLite (/app/data/pos.db) |
8000 | only through proxy / inner nginx | pos-backend |
waiter_pwa |
React + Vite + vite-plugin-pwa, axios, zustand, react-query, Dexie (IndexedDB) | 5173 | http://<LAN IP> (80, LAN only) · https://waiter.<domain> / https://<IP> (443) |
pos-waiter |
manager_dashboard |
React + Vite | 5174 | http://<LAN IP>:8081 (LAN only; http://<IP>/manager redirects there) · https://manager.<domain> (443) · https://<IP>:4443 |
pos-manager |
terminal |
React + Vite (platform v2, phase 3): one app for every paired screen (KDS, counter POS, customer display), apps as lazy chunks by the device's app_key |
5175 | http://<LAN IP>:8082 (LAN only) |
pos-terminal |
proxy |
nginx:alpine | — | 80, 443, 4443, 8081, 8082, 8443. See the header of nginx-proxy/nginx.conf for the full routing map. Waits for the backend to be healthy; terminal is resolved per request, so the proxy also starts without it |
stock |
Request path in production
Phones normally use plain HTTP by LAN IP (http://<HOST_IP> → proxy:80 default_server). Only private source IPs are allowed; everything else gets 403.
Legacy domain sites use https://waiter.<domain> (proxy:443), and waiter.*/manager.* on port 80 still redirect to https.
phone ──http(s)──▶ proxy:80/443 ──http──▶ waiter_pwa nginx:80 ──┬─ / → static SPA
├─ /api/ → backend:8000
├─ /api/ws/ → backend:8000 (WebSocket upgrade)
└─ /static/ → backend:8000/static/
Every hop must forward WebSocket upgrades: proxy_http_version 1.1, plus Upgrade and Connection headers, plus a long proxy_read_timeout.
The manager calls the API same-origin, with relative paths. The waiter app resolves every backend URL through waiter_pwa/src/config/server.js: same-origin when served by the venue's server, absolute when running in the native app (see CS-8). Don't hardcode hosts.
Key files
| File | Why it matters |
|---|---|
local_backend/main.py |
App setup, router registration, CORS, _run_migrations() |
local_backend/services/lan_ip.py, services/netinfo_helper.py |
Which LAN IP phones get (override → live detection → HOST_IP); the netinfo host-network helper |
local_backend/services/tls_identity.py, waiter_pwa/android/.../TrustStore.java, src/native/tls.js |
Encrypted LAN link: the server's self-managed key and cert, and the app's key pinning |
local_backend/services/cloud_sync.py |
Every call to the cloud (see the parent's docs/reference/cloud-contract.md) |
local_backend/roles.py, routers/deps.py |
Roles, permission checks, auth dependencies |
local_backend/services/fiscal/ |
Fiscal devices behind one driver interface (D-27, step 3.3e): base.py (prepare_receipt / prepare_credit_note → send, credit_notes flag, status), txt_file.py (the dTEC100extra folder bridge, the only driver today; no credit notes yet), __init__.py (the venue's driver from fiscal.type, item building, background issue). A new machine = a new driver module listed in DRIVERS; never write to a device from a router |
local_backend/services/fees.py |
Delivery fee engine (phase 3S). Byte-identical copy in cloud-service/cloud_backend/services/fees.py: change both, and tests/fixtures/fee_cases.json in both; tests/test_fees.py fails if they differ |
local_backend/services/sales.py, services/csv_export.py |
How every report counts sales (6.12a, 6.13c): sold = active, paid and tabbed lines (a tab line is sold, not paid), each net of what was refunded of it, system lines (the delivery fee) apart as fees; Totals.on_tab. Every analytics endpoint, printed report and export uses it. Exports: UTF-8 mark, venue time with the zone in the header, ; and decimal commas for a Greek venue |
local_backend/services/tab_books.py |
Tabs in the books (6.13c, owner rule "every movement recorded"): a line put on a tab and a tab payment record the business day and the shift of whoever did it; for_shift / for_day. A shift's drawer adds the tab cash it received; money taken by someone with no shift is theirs, in the day, in no drawer |
local_backend/services/refunds.py |
Refunds: their own records (models/refund.py), never edits of the paid items; shift / day totals subtract them |
local_backend/services/system_products.py, services/online_check.py |
Lines the system adds itself (phase 3S): the delivery fee is an order line whose product has system_key and lifecycle_status = "system" (never on a menu or in the catalogue, never added by hand, added printed + served so the kitchen never sees it; paid, counted, receipted and refunded like any line). The site's own price check of a pulled online order (orders.online_price_diff): shown, never applied — the customer pays the cloud's prices |
local_backend/services/online_reservations.py |
Table bookings from the online ordering app (phase 3S): stored as Reservation rows (requested → pending confirmed / declined; arrived, cancelled, no_show), food ordered ahead kept on the booking (items_json) and turned into an order only at the fire time (fire_worker, a connect_orders module worker; needs an open business day) or on early arrival. Every step mirrors the cloud status. The counter's Online → Bookings and /api/connect/bookings/* use it; the reservations router delegates online bookings to it |
local_backend/services/table_qr.py, services/qr_orders.py |
The QR menu at the table (phase 3S): every active table has a random qr_token; the menu snapshot carries only its sha256 (qr), so the cloud can check a code but never make one. A new code (rotate) kills the printed one at the next push (/api/tables and /api/connect/qr are in MENU_PATHS). A QR order with a valid table goes straight onto the table's open order (or a new one), to the kitchen, with a qr_order message to the table's waiters; the audit row QR_ORDER (note = the cloud ref) keeps repeats out. Manager page /online/qr |
local_backend/routers/fees.py |
The venue's online ordering settings (connect_orders.ordering: services, hours, slots, ASAP; reservations: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (links.order, links.menu from the cloud's apps_url). Everything here travels to the cloud in the menu snapshot (contract C-2) |
local_backend/routers/customer_display.py, models/display_look.py, terminal/src/apps/customer-display/ |
The customer display (3.4, 5.3): the counter POS pushes POST /api/display/state (useDisplay() in apps/pos/usePos.js: the sale cart, the payment dialog's bill, then "paid"); only displays whose linked_device_id is that POS get display.state. The idle screen is a look (display_looks: name, is_default, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config look (a ref to display_looks, also set from Settings → Customer display through PUT /api/display/displays/{id}/look) or the default. A look's change sends display.settings only to the displays showing it. Pictures are served from the library (full for image / slides, card for the logo). The POS's last state lives in memory |
local_backend/routers/media.py, services/media.py, models/media.py; manager src/pages/media/ |
The media library (5.1, 5.2): every picture and video once, by sha256, under /app/data/media/<sha[:2]>/<sha>/ (the untouched original + thumb 200 / card 600 / full 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). data/media belongs in every site backup together with pos.db (the database only holds ids and hashes; DEPLOYMENT_GUIDE → Backups). Served public by hash at /api/media/file/<sha>/<variant> with year-long immutable caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. What points at media has a media_id column and registers register_usage(kind, fn) (products and categories in routers/products.py) so delete is refused (media.in_use) while it's used. APIs give image = {id, name, thumb, card, full} (services.media.image_of); a product's image_url is its card size. Manager: the Media page (batch upload, details) and MediaField (upload on the spot / pick from the library / "Name it after" with latin() from @xenia/i18n) for any form that takes a picture. The waiter fetches the menu's photos ahead (services/photoCache.js; PWA: workbox xenia-media cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets client_max_body_size 250m. Videos (5.4e, services/video.py): MP4 / MOV / WebM kept as uploaded; a background thread (start_worker in main.py's lifespan, one video at a time, low priority, 2 threads) makes the still frame (the same thumb / card / full WebP) and, when needs_version() says so (not H.264 MP4, over 1920 px, 10-bit / HDR, other audio, > 12 Mbps), play.mp4 (H.264 + AAC, ≤ 1920 px, HDR tone-mapped, faststart). Media.processing waiting → working (progress) → done |
local_backend/routers/signage.py, models/signage.py, assets/builtin_media/ |
Digital signage (5.4a): playlists (name, orientation, default transition) of slides (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, content typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by media_ids() for the library's usage check). A screen's device config: playlist (ref signage_playlists), orientation, rotation, and its picture (6R.13): fit (keep a slide's shape with bands / stretch) and area_* (px cut off each edge, set by Screens → Calibrate the picture; signage.calibrate to that screen while calibrating; the TV reports its window with POST /api/signage/screen/viewport); playlists and library slides have a shape (orientation + aspect "21:9", shapeOf() in @xenia/signage); GET /api/signage/screen gives it the playlist resolved (enabled slides, media addresses, a version hash); changes send signage.changed only to the screens playing that playlist. Built-in pictures: files in assets/builtin_media/ are imported at start (services.media.import_builtin, media.builtin), listed as their own collection, never deleted or renamed. Menu boards (5.4b): services/signage_menu.py resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own category_order / product_order; prices from pos_cart.unit_prices of its sales point; customer-facing names); every request that changes the menu (cloud_sync.menu_changed paths) also sends signage.changed to the screens with a menu board (main._signage_menu_changed). The editor (5.6a): manager src/pages/signage/ (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (SlidePreview), templates (signageLogic.TEMPLATES), the orientation warning; GET /api/signage/venue and POST /api/signage/preview/menu feed the previews. The menu board editor (5.6b, MenuEditor.jsx) orders what the server resolved: boardOrder() writes the whole shown order into category_order / product_order; widgets: WidgetsEditor.jsx. Tabs (5.6c): Screens (ScreensTab: playlist, schedule, shape, rotation through PUT /api/signage/screens/{id}), Schedules (SchedulesTab), Message and weather (SignageSettingsTab: PUT /api/signage/message, the town search and PUT /api/signage/weather/place). Widgets (5.4c): Widget on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); 6R.15 adds shape (rectangle / circle as a box, triangle / polygon / star / own corners as SVG, shapePoints; fill or gradient, border), ticker (scrolling text, Web Animations), countdown (countdownState / countdownText in venue time: every day at HH:MM or a date; from now, a span before or a time), opening hours (venue.opening_hours, GET/PUT /api/identity/hours, edited on the Schedule page's Opening hours; hoursRows), Wi-Fi and contact details (from the identity; editor MoreWidgetFields.jsx warns with a link when the venue hasn't set them); 6R.19 reviews (typed in by hand: setting signage.reviews, GET/PUT /api/signage/reviews, Message & settings → Reviews; venue.reviews on the screens; one at a time, a minimum of stars). The editor's widgets list is in layers (owner 2026-11-22): the top card is the last widget of the slide's list (drawn over the others), "Add a widget" (AddWidgetMenu) adds on top; the screen also gets venue = name, the message of the day (signage.message, PUT /api/signage/message tells every screen) and the weather (services/weather.py: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; null when there is no place, no internet or it is older than 3 h, so the player hides the widget). Schedules (5.4d): signage_schedules (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's schedule (ref) wins over its playlist; services/signage_schedule.pick chooses in venue time (highest priority, then dates > days > hours, then the later entry); /screen then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; schedule_worker (30 s) tells a screen when its pick changes. The player (5.5a): terminal/src/apps/signage/ (the logic and slides moved to packages/signage in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; SignageApp.jsx: the last /screen answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on signage.changed, device.updated, a reconnect and every 5 min). Signage is in QUIET_OFFLINE (apps/registry.js): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (boardPages: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; page_size overrides) and go round while the slide lasts (at least its pages × page_seconds); widgets in Slides.jsx (Widgets), a widget with nothing to show (no weather, no message) is left out |
local_backend/routers/menu_tablet.py, terminal/src/apps/menu-tablet/ |
The menu tablet (5.7a): GET /api/menu-tablet/menu (a paired tablet) gives categories in the catalogue's order with their products (a product in several categories shows in each), the products once with the tablet's sales point price, photos, tags, and its device config (view compact / expanded / full, photos, descriptions, group, theme, prices of, sold out, one category, search, languages, idle reset). Menu changes send menu_tablet.changed (the same hook as signage). The app: search folds accents and also matches names typed in Latin letters (latin, @xenia/i18n/latin); the last menu in localStorage. Call a waiter (5.7b): device config table (ref tables) + call_waiter; POST /api/menu-tablet/call sends a table_call staff message (the open order's waiters, else the zone's; qr_orders.waiters_for) at most once a minute per tablet (in memory); the waiter's phone shows it with "Open the table" Ordering at the table (6.6, D-30): services/tablet_orders.py + models/tablet_order.py (tablet_orders, 0034). Device config ordering (off), bill, and per-tablet overrides order_confirm / order_no_order / order_max_items / order_max_of_one / order_min_seconds (-1 / venue = the venue's); the venue's rules are the JSON setting menu_tablet.ordering (GET/PUT /api/menu-tablet/ordering, Settings → Menu tablets). /menu adds table.can_order, table.can_see_bill and ordering (rules + choices: the POS product shape at in-store prices, so the tablet reuses pos/ProductDialog). POST /quote / /order take POS lines by id (pos_cart.resolve_line, never prices or discounts); every order is a TabletOrder row (it also times the limit); kitchen mode places it with orders_api.add_priced_items(source="tablet"), waiter mode leaves it waiting until `POST /requests/{id}/accept |
local_backend/routers/pricing.py, services/pricing.py, manager_dashboard/src/pages/pricing/ |
Pricing (6.7): price groups, modifiers (price rules), deals, discount limits. Every set-up endpoint needs pricing.manage and broadcasts pricing.changed (the page's useLiveQuery); the phones keep reading rules / deals with any signed-in user. Conditions are checked on save (_condition_ok → pricing.bad_condition): an incomplete one used to raise in services/pricing.py::_eval_condition at quote time. Venue limits live in settings discounts.* (empty = no limit; pricing.bad_limit). The page's rules as data: pricingLogic.js (tests/pricing.test.mjs) |
local_backend/routers/floor_plans.py, services/floor_live.py, packages/floorplan, manager src/pages/floor/ |
The table map (6.8, D-31): floor_plans / floor_items (0035) and the tables' plan_id, floor_x/y (centre), width, height, rotation, shape. Set-up /api/floor-plans (catalog.tables.manage; PUT /{id}/layout saves tables + items whole) sends floor_plans.changed; GET /api/floor-plans/live (any signed-in person, the waiter app's zone rule) gives each table's state, guests (customer_count), waiters and time. @xenia/floorplan: FloorView (inline styles on tokens, so the waiter app can use it), Floor / Item / TableShape, geometry.js (grid snap = positions and sizes in whole cells; @xenia/floorplan/geometry for node tests). Dockerfiles copy its package.json |
local_backend/routers/phone.py, services/caller_id.py |
Caller ID (3.5): the UCM's GET /api/phone/call-event is public but LAN-only in the proxy (the same `location ~ ^/api/(devices/pair-request |
local_backend/routers/ws.py |
Real-time event stream (seq + cursor replay) |
waiter_pwa/src/config/server.js |
Where the backend is: active venue, apiBase(), wsUrl(), assetUrl(), storageKey(), dbName(), deliveryMode() |
waiter_pwa/android/, capacitor.config.json |
Native Android app (Capacitor 8). See "Native Android app" below |
waiter_pwa/src/native/pairing.js, src/pages/VenuesPage.jsx |
Pairing with a venue (QR / typed address) and the venue switcher |
waiter_pwa/src/api/client.js, src/api/bootstrapCache.js, src/api/venueSettings.js, src/api/errors.js |
The waiter's client on @xenia/api (since 4.1): token, 401 → logout, no answer → backend-offline, the manager-approval retry; <AccessProvider cache> keeps the last bootstrap per venue so an offline restart stays signed in (CS-3); one shared, offline-cached read of the venue settings; apiError(err, fallback) shows backend error codes in the user's language |
waiter_pwa/src/context/LiveContext.jsx, src/hooks/useWebSocket.js |
Real-time lifecycle, event → store/cache updates, visibility refresh; the socket itself is createLiveClient from @xenia/api |
waiter_pwa/src/db/posdb, src/services/offlineOrders |
Offline cache and queued orders (lines by id, priced on sync; refused lines kept in kv.refused_lines, components/RefusedLines.jsx; 4.4) |
waiter_pwa/src/i18n.js, src/logic/colour.js, tests/no-greek.test.mjs, tests/no-colours.test.mjs |
The waiter's texts (waiter namespace, tw(), money(); 4.5) and colours (tokens only, fade(); 4.6), and the guards that keep them so |
waiter_pwa/src/pages/TableDetailPage.jsx, AddItemsPage.jsx, BookingsPage.jsx, components/TableHistory.jsx |
The table (actions by permission key 4.3, combine lines and close-with-unpaid 4.8, history 4.7), ordering (server-priced cart 4.4), bookings (4.8) |
nginx-proxy/nginx.conf |
Proxy config used in dev / by hand |
install.sh |
Site installer. Writes its own copy of the proxy config. |
docker-compose.yml / docker-compose.dev.yml |
Prod (pull images) / dev override (build + expose ports) |
manager_dashboard/src/shell/, src/pages/<area>/, v2.json |
The manager (phase 6, all of it on v2 since 6.14b): the frame (shell/AppLayout, Sidebar on the nav tokens, ProfileDialog, nav.js = the one list of pages with their module and key, RouteGuard), one folder per area (overview, orders, products, pricing, floor, tables, printing, staff, schedule, reports/<report> on reports/kit, finance, customers, inventory, notes, Settings/sections, setup, platform, online, media, signage), each with a *Logic.js unit-tested in tests/. v2.json: paths = src (the guards refuse Greek and colour literals anywhere; venue colour data files are listed in the guard's DATA), strict = folders that may not set state in an effect |
package.json, package-lock.json, packages/ |
npm workspace for the frontends (D-15): waiter_pwa, manager_dashboard, terminal and the shared packages/{ui,i18n,api,access} (imported from source, no build step). One lockfile at this root; the apps have none of their own. |
terminal/ |
The terminal app (phase 3): src/device/DeviceProvider.jsx (the device's /me, who is signed in, the live connection with credentials in the first frame, offline; apps listen with useLiveEvent), src/device/flow.js (which screen shows when: pairing → sign-in → app / blocked; pure, unit-tested), src/screens/ (pairing, sign-in per mode, blocked, app + bar), src/apps/registry.js (which apps a screen runs, lazy chunks), src/device/storage.js (device + session tokens), src/api/client.js (X-Xenia-Device on every request; 401 / unreachable listeners). The screen follows the device, not the URL. Lint covers all of src |
packages/ui/ |
Shared design tokens, Tailwind preset and base components (CS-16). Visual check: npm run dev:manager → /ui-gallery |
docs/DESIGN.md |
The design language (2026-11-20): the page rule (<Page>: own scroll, fills 1080p, 16:9 and centred on ultrawides), toolbars, the one Dropdown (multi-select), tabs, type/spacing tokens, tables. Read before any UI work (CS-20) |
packages/api/ |
Shared HTTP client (createApiClient: session/device headers, err.xenia codes, the manager-approval retry) and the live WebSocket client with cursor replay (createLiveClient, used by the waiter's useWebSocket) (CS-18) |
routers/identity.py; manager pages/Settings/sections/IdentitySettings.jsx, shell/useIdentity.js, shell/VenueIdentity.jsx |
The venue's identity (6R.14): GET/PUT /api/identity = venue.name + the JSON setting venue.identity (slogan, up to 12 named colours, logos main / light / dark / icon as media ids — registered usage identity —, guest Wi-Fi, contact details). Signage gets it in _venue() (identity, plus the venue's timezone) and every screen is told on a change. The manager reads it once (useIdentity) and VenueIdentity feeds VenueColoursProvider (@xenia/ui): every ColourField offers the venue's colours first. wifiQr() (@xenia/signage/logic) writes the join-the-network QR text |
packages/signage/ |
@xenia/signage (5.6a): signage slides as the TVs draw them (SlideView, TextSlide, MenuSlide, Widgets) and the player's pure logic (schedule pick, slide windows, menu pages; tests in tests/), shared by the terminal's player and the manager's previews. Sizes are container units (cqmin): a slide needs a parent with container-type: size (frameStyle(); the manager's SlidePreview lays it out at 1920 × 1080 and scales it down, so previews match a TV). Both apps' Tailwind content include it |
packages/access/ |
<AccessProvider> (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), useCan, useModule, <Can>, <RequireModule> (CS-18); the fixed lists every app shares with the backend: sales points (salesPoints.js = core/sales_points.py) the 14 EU allergens (allergens.js = core/allergens.py, 6.3) and the menu's languages (menuLanguages.js = core/menu_languages.py, 6.4: el + en; a product's own name is its base text, translations in products.translations / categories.translations are for customer screens only; tests compare the lists), and <Allergens> (a product's allergens, the same in every app). Plain-JS subpaths @xenia/access/salesPoints, /allergens for Node tests |
packages/i18n/ |
Translations (locales/<lang>/<ns>.json), language resolution, venue-time / money / number formatting, the comma-or-dot number parser, and the guard scripts/check-i18n.mjs (CS-17). Sample: /i18n-sample (dev) |
.dockerignore |
The frontend images build with client-services/ as context (-f waiter_pwa/Dockerfile .), so this file decides what Docker sees. The backend still builds from local_backend/. |
Pack-specific rules
CS-1. Schema changes are Alembic revisions (branch platform-v2, APPS_PLATFORM D-13).
Change the model, then from local_backend/: alembic revision --autogenerate --rev-id NNNN_short_name -m "what changed". Review the generated file by hand (SQLite needs batch ops; data moves are written by hand), then run python -m pytest tests -q. The drift guard (tests/guards/test_migrations.py) fails if models and revisions disagree.
Update the Pydantic schema in the same commit. Revisions may drop or rename columns. Never use create_all: startup, seed/wipe scripts and tests all call core/schema.py::upgrade_to_head(). New model modules must be added to models/all.py.
A v1 database (tables, no alembic_version) is refused at startup; v1 data comes over only through tools/migrate_v1.py. Old dev databases (%LOCALAPPDATA%\pos\pos.db, tests/e2e/out/seed.db) must be deleted once.
(On main, the v1 rule still applies: _run_migrations() ALTER list, additive only.)
CS-2. New real-time events need both ends.
If the backend emits a new event type, handle it in waiter_pwa/src/context/LiveContext.jsx (and in the manager, if relevant), or state explicitly that it's ignored.
Events carry IDs; clients re-fetch the full object (/api/orders/{id}) instead of trusting partial payloads.
Control frames from routers/ws.py (3.1a) are not stored and have no seq: device.updated (a paired screen re-reads GET /api/devices/me), and just before the server closes a socket session.ended (4001) or device.revoked / device.updated (4003). The waiter and the manager ignore them (their next request gets the 401 that signs them out); the terminal acts on them. Events for one device: ws_bus.broadcast_sync(type, data, device_ids=[…]).
CS-3. The waiter app must survive bad networks. Waiters walk in and out of WiFi range and phones sleep. Any new waiter flow must:
- work from the IndexedDB cache when offline, or clearly block with an offline state
- never lose an order that was entered (queue it): queue it by id (
@xenia/apiwireLine, step 4.4) so the server prices it when the phone is back, and show what the server refused instead of dropping it (kv.refused_lines, the "Not sent" sheet) - tolerate duplicate or replayed events
- never hang on a request: every request that a screen waits for has a time limit or a retry (the bootstrap: 8 s, then offline + retry; step 4.6)
CS-4. Money and prices are snapshotted.
Prices, costs and discounts are copied onto order items and logs when the action happens (snapshot pattern, PriceEventLog). Reports read the snapshots, never the live catalogue.
CS-5. The proxy config lives in two places and must stay byte-identical.
install.sh writes the heredoc on client sites, and nginx-proxy/nginx.conf is the repo copy. Edit both together (global Rule 9) and check with:
sed -n "/<< 'EOF'/,/^EOF/p" install.sh | sed '1d;$d' | diff - nginx-proxy/nginx.conf
The plain-HTTP servers (80 default_server, 8081, 8082) must keep their LAN-only allow/deny block (tests/e2e/stack.mjs checks 8081 and 8082 from a non-LAN network).
A frontend image's Dockerfile copies every workspace's package.json before npm ci (the lockfile covers them all): a new workspace app adds its line to all of them.
CS-6. Permissions are checked on the backend.
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.
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:
- REST goes through
api/client.js(itsbaseURLisapiBase()). Any other fetch,EventSourceorWebSocketmust build its URL withapiBase()orwsUrl(). - Backend-served files (
/static/...images, avatars) are rendered throughassetUrl(). - Persistent venue-specific data (token, IDs of products/tables/zones) uses
storageKey()for localStorage keys and zustandpersistnames. The IndexedDB name comes fromdbName(). Device preferences (theme, payment safety…) stay global. - Features that need a secure context (service worker, camera, notifications, clipboard) must degrade gracefully when
deliveryMode()is'plain-web'.
CS-7. Greek-market realities. Staff UIs are used by Greek staff and must render Greek correctly, including on thermal printers (codepage). Money uses €.
Common commands
# Once, and after any dependency change: install every frontend from the workspace root
npm install # in client-services/, never inside an app folder
# Dev: backend with reload
cd local_backend; uvicorn main:app --reload --port 8000
# Dev: frontends (Vite proxies /api and /api/ws to :8000)
cd waiter_pwa; npm run dev # :5173
cd manager_dashboard; npm run dev # :5174
cd terminal; npm run dev # :5175 (paired screens; pairing from 3.1c)
cd waiter_pwa; npm run lint
# Build release images (VERSION comes from .env). See the parent's DEPLOYMENT_GUIDE.md.
docker compose -f docker-compose.yml -f docker-compose.dev.yml build
docker push registry.bonamin.net/pos-backend:<ver> # + pos-waiter, pos-manager, pos-terminal
Native Android app (waiter_pwa)
The same waiter code, bundled into an APK with Capacitor 8. It is sideloaded, not on Play Store yet.
cd waiter_pwa
npm run apk:debug # releases/xenia-waiter-<ver>-debug.apk (WebView debuggable via chrome://inspect)
npm run apk:release # releases/xenia-waiter-<ver>.apk, signed, AND copied to public/downloads/
-
Signing key:
%USERPROFILE%\.xenia\xenia-release.jks+keystore.properties. It lives outside the repo; back it up. A lost key means no phone can install updates (uninstall and reinstall on every phone). Cert SHA-25698:A2:60:25:…:61:7A. -
Versioning: bump both
versionCodeandversionNameinandroid/app/build.gradlefor every APK handed out. Android refuses an update whose versionCode isn't higher. -
Distribution:
apk:releasecopies the APK intopublic/downloads/, so the next web build (and Docker image) serves it athttp://<IP>/downloads/xenia-waiter.apk. The browser-mode install banner links there. Order:apk:release→docker compose … build. -
Native specifics:
androidScheme: http(originhttp://localhost)- cleartext allowed via
network_security_config.xml - the updater may download bundles over plain HTTP (
httpsOnly: falseincapacitor.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/) - back button handled in
src/native/backButton.js - first run shows only the pairing screen
-
android/local.properties(SDK path) is gitignored. Recreate it on a new machine:sdk.dir=C:/Users/<you>/AppData/Local/Android/Sdk. -
UI bundles (plan step 8): every waiter image also publishes the native UI bundle (
scripts/pack-bundle.mjs→/downloads/waiter-bundle.json+ zip). Phones run their venue's bundle via@capgo/capacitor-updater(manual mode, no Capgo cloud), driven bysrc/native/bundles.js.
CS-10. MIN_SHELL_BUILD guards native compatibility.
When web code starts relying on something new in android/ (a plugin, a Java class, a manifest change), bump MIN_SHELL_BUILD in src/native/shell.js and versionCode, in the same commit. Phones with an older APK then keep their current UI and show "update the app", instead of loading a UI that calls missing native code.
Every bundle must call markBundleReady() at start (BundleSync does this); otherwise it is rolled back after 15 s.
The native plugins (@capacitor/*, @capgo/*) are pinned to exact versions in waiter_pwa/package.json (no ^), so npm install/npm update never move them. Upgrading one is a deliberate change under this rule: new exact version, versionCode + MIN_SHELL_BUILD bump, Android e2e (stacks) run.
CS-9. Anything a native build needs must survive npx cap sync.
android/app/src/main/assets/public and the generated configs are rebuilt on every sync, so never edit them. Native changes go in android/app/src/main/** (manifest, res, java) or capacitor.config.json.
Testing
Automated tests cover the native-app/LAN work and licensing. See tests/e2e/README.md.
- Unit (seconds):
python -m pytest tests -qinlocal_backend/,npm testinwaiter_pwa/, andnpm test -w <@xenia/ui|@xenia/i18n|@xenia/api|@xenia/access|manager-dashboard>at the workspace root. - End-to-end:
node run-all.mjsintests/e2e/(the manager:manager.mjsevery page's main flow,setup.mjsa fresh install through the wizard,manager_look.mjsevery page in light and dark with contact sheets inout/manager-look/). That covers install.sh, licensing with a real cloud, browser modes, a compose stack of the release images (stack.mjs), and the Android emulator suites.--no-androidskips 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-12. Errors are codes, backend text is translated (branch platform-v2, D-12, §3.2).
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 HTTPExceptions 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).
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).
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. A role's defaults are the manifests' plus the venue's changes (role_permissions, Settings → Operation → "What each role may do"): create users with apply_role_template(user, db), and a new key added to a role later must be granted to existing users of that role in its Alembic revision (keys are copied at creation; see 0024). In endpoints a waiter can reach, check keys with authorize(request, db, user, key) (module, device scope, key, manager approval → access.denied / access.override_possible); the apps read permissions and approvable from bootstrap (useAllowed(key) → yes / approve / no), never a venue switch for what a person may do. 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).
Apps never send a price (step 4.4). Order lines go by id (services/pos_cart.py's line: product, quick add-ons, extras with sub-choices, preferences, removed ingredients) to POST /api/orders/{id}/items (the waiter, the manager's ordering tab) or the counter's /api/pos/*; the server prices them through orders.add_priced_items, the one function that writes order items with prices. A line carrying prices or selected_options is refused (order.line.client_price), so is the shape before 4.4 (items → order.lines_required); a by-hand change (price_adjustment) needs ordering.prices.modify or a manager's approval. Totals before sending come from POST /api/orders/quote (the counter: /api/pos/quote), the same code; offline an app may show its menu's prices only as an estimate. Apps whose cart keeps the stored selected_options shape build lines with @xenia/api wireLine / lineFromOptions (an option no longer on the menu throws LineError, never dropped). A preference set left out of a line takes its default, and a set at its free default isn't stored (tickets show only what differs).
Waiter texts (step 4.5). The waiter app has no text of its own: every label is a key in packages/i18n/locales/{en,el}/waiter.json (English first, Greek as the translation), read with useTranslation('waiter') in components and tw('key') (waiter_pwa/src/i18n.js) outside them; money with useFormat().formatMoney or money() from the same file, times with useFormat() (venue clock). waiter_pwa/tests/no-greek.test.mjs fails on any Greek letter in waiter_pwa/src (a Greek word the code must recognise is written with \u escapes). Don't name a variable t in a component that translates. The language is per person (user menu, saved with PATCH /api/auth/me), else the venue's. The e2e suites run the waiter in English (the test venue's language).
Paired devices (D-8, routers/devices.py, core/access/context.py) send X-Xenia-Device: <token> (on the WebSocket: device in the first frame); 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. Per-device settings are ConfigFields in DeviceApp.config (validated by core/modules/device_config.py, rendered by the manager's DeviceConfigFields), each with texts modules:<app>.config.<key>.label (+ .choices.<value>), never free JSON. 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).
CS-16. Shared UI lives in packages/ui and never restyles an app (branch platform-v2, D-15, §9).
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). The look comes from attributes on <html> set by applyLook (packages/ui/src/theme.js, 6.15): data-theme (always light/dark; "system" is resolved and followed in JS), data-palette (the colours: default, nord…) and data-style (the components' shape: rounded, sharp…), plus data-venue-theme (the venue's accent on the staff apps). A new palette or style is a token block in tokens.css (sections "Palettes" / "Styles") plus its name in PALETTES / STYLES and its label; components never hard-code a radius, border width or colour, so they follow it. 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. Board screens (the kitchen display, and any later screen in the same style) use the board design language: --x-board-* tokens in the same file (Tailwind bg-board-bg, text-board-ink-2…; always dark, contrast-tested too) for the board itself, and the normal components in data-theme="dark" for their dialogs, toasts and forms (the terminal sets an app's theme from apps/registry.js APP_THEMES). No hard-coded colours in app code: a colour that isn't a token yet becomes one (values the user stores, like a KDS screen's age colours, are data, not styling).
CS-20. Every screen follows DESIGN.md (2026-11-20).
Pages are <Page> (never their own padding / width / scrolling), filters sit in a <Toolbar> with one control height, choices are Dropdown (never a native select in a toolbar), sections are Tabs. Anything a second page needs goes into @xenia/ui first. tests/e2e/manager_layout.mjs checks the page rule at 1080p and ultrawide.
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. Module names, their limits and every permission key have texts in modules.json (modules:<module>.name, .limits.<key>, .permissions.<rest of the key, nested by its dots>); tests/test_module_texts.py fails for a new module or key without them in both languages. The v1 apps' Greek strings convert in phases 4 and 6. The @xenia/ui components get their texts from <UiLabelsProvider labels={useUiLabels()}> at the app root.
CS-18. Frontends talk to the backend through @xenia/api and read access from bootstrap (branch platform-v2, D-7, D-10, §9).
An app makes one client with createApiClient({ axios, baseURL, getToken, getDeviceToken, onUnauthorized }) (its own axios; the waiter passes baseURL: () => apiBase() when it moves, CS-8). Errors carry err.xenia = { code, params, message, status, offline }; show them with errorMessage(err, t) (texts in packages/i18n/locales/*/errors.json, which a test keeps complete against core/errors.py: a new backend code needs both texts). A 401 means "session ended" and logs out, so a form whose own wrong-credentials answer is a 401 (login, unlock, PIN checks) passes { xenia: { ignoreUnauthorized: true } }. Lock screens never log in again: they call POST /api/auth/unlock {pin} with the current session (same token; 5 wrong PINs end the session); manager sign-in sends client: "manager" and the waiter client: "waiter" (user_id or username + pin or password); both read their mode from bootstrap login (manager_mode, waiter_mode, waiter_require_username). Signing out calls POST /api/auth/logout so single-session venues free the seat; restoring the user after a reopen must not clear a lock (the waiter's authStore.restore, not 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). A paired device passes credentials: () => ({ device, token }) (sent in the first frame, never in the URL) and onRefused(code). 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-19. Device apps: who hears what, and replays (branch platform-v2, phase 3).
- A screen with sign-in
none(customer display) receives every broadcast event; send what is meant for one screen withdevice_ids=[…](the customer display'sdisplay.stategoes only to the displays linked to that POS) and what is meant for a role withuser_ids=[…]plus the screens that need it (call_incoming: users withcaller_id.use+ the counter screens). - A device app may only reach routes of modules in its
DeviceApp.scope. When an app must call another module's route, add one pattern for it (the POS hascustomer_display.state), never a wildcard. - Events are stored and replayed on reconnect (24 h). A screen that reacts with something visible must ignore stale ones: check the event's time (
call_incoming: older than a minute → no popup) or let it expire (display.state"paid" → idle after 12 s); state a screen needs after a restart comes from a GET (/api/display/state, the KDS list), not from replay. - What the device itself shows comes from its device config (
ConfigFields) or a venue setting. Designs a venue makes for its screens (the customer display's looks, 5.3; later signage playlists) are their own records with a manager page, and a device picks one with arefconfig field (none = the venue's default), never free JSON in the device.
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).
Everything else still needs manual checks before committing:
- the backend starts cleanly against an existing
pos.db(this catches missing migrations) npm run buildpasses for any frontend you touched- the flow was exercised by hand (the parent's
PLANS AND STRATEGIES/TESTING_CHECKLIST.md) - printing was checked against real hardware or
esc-pos-emulator
Say in the commit or hand-off what was and wasn't verified.