Compare commits

...
95 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 51b764fe7e test(e2e): display looks (two displays, two slideshows; looks UI with library pictures); docs
- terminal.mjs: the looks API drives the idle screen; a second look on the
  other display: two displays show two different slideshows from the library.
- manager.mjs: the default look's QR design through Settings.
- media.mjs: a new look with three pictures picked at once, a picture in a look
  can't be deleted.
- pack README: the customer display row; CS-19 (screen designs are records a
  device picks with a ref field).
- run-all --no-android: all passed except terminal's "server unreachable →
  banner" (8 s wait, under load); terminal.mjs alone right after: all passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:50:52 +02:00
bonaminandClaude Opus 5.5 6d84e43330 feat(manager): customer display looks: several, a default, one per display; pictures from the library (platform-v2 step 5.3)
Settings → Customer display lists the looks (default starred, how many
displays each), edits one (logo / picture with MediaField, the slideshow's
pictures picked several at a time, reordered, removed), new look (empty or a
copy), make default, delete, and "Which display shows which look". The Devices
page offers the looks for a display's Idle screen. MediaPicker: `multiple`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:50:52 +02:00
bonaminandClaude Opus 5.5 27d7bbb976 feat(backend): customer display looks on the media library, one per display (platform-v2 step 5.3)
- display_looks (Alembic 0028): named idle screens, one default; config is
  the 3.4 design with pictures as media library ids. 0028 turns the setting
  customer_display.idle into the look "Main" and moves its data/display_media
  pictures into the library (the old folder stays on disk).
- A display shows the look in its device config `look` (ref ConfigField,
  choices_from "display_looks", validated in device_config) or the default.
- /api/display/looks (GET also for core.devices.manage), POST, PUT,
  POST /{id}/default, DELETE (not the default; its displays go back to it);
  /api/display/displays and PUT /displays/{id}/look. A change sends
  display.settings only to the displays showing that look.
- /api/display/settings, /api/display/media* and their error codes are gone;
  GET /api/display/state keeps its shape (logo card size, image/slides full).
- Looks register their media usage (a picture in a look can't be deleted).
- tests: test_customer_display.py (7, incl. two displays two slideshows and
  the 0028 data move); 501 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:50:51 +02:00
bonaminandClaude Opus 5.5 87dff573df test(e2e): media suite (Media page batch upload, product photos, waiter offline photos); docs
- media.mjs: batch upload through the Media page (the owner's ITEM PHOTOS
  folders when present: 49 files incl. AVIF, all in), details and rename, a
  product's photo from the library and one uploaded on the spot named after
  the product, a used photo can't be deleted, the waiter fetches the photos
  ahead and shows them offline. In run-all.
- startBackend gives each test backend its own XENIA_MEDIA_DIR.
- pack README: the media row (usage registration, `image`, MediaField, offline).
- run-all --no-android: every suite passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:57:51 +02:00
bonaminandClaude Opus 5.5 15bd0f5b57 feat(waiter): keep the menu's photos for offline (platform-v2 step 5.2)
Right after the menu is read the phone downloads its photos (4 at a time,
services/photoCache.js). The library's year-long immutable headers keep them
in the browser cache; the installed PWA also caches /api/media/file/ cache-
first (workbox `xenia-media`). With no connection the menu still shows them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:57:51 +02:00
bonaminandClaude Opus 5.5 e09056a7a4 feat(manager): Media page, photo field for products and categories (platform-v2 step 5.2)
- Management → Media (src/pages/media/): every picture and video, search,
  pictures / videos, batch upload (many files or drop on the page) with a
  result per file, details (preview, display name, kind, resolution, length,
  file size, uploaded file, when / who, the sizes made, what uses it, delete
  off while used).
- MediaField: upload on the spot (into the library and set at once), pick
  from the library (MediaPicker, which can also upload), remove; after an
  upload on the spot "Name it after the product / category" renames it in
  Latin letters. Used by the product editor and the category dialog.
- nav: `anyPerm` (any of the keys that manage pictures); the route guard uses
  the same rule. Product rows have test ids.
- @xenia/i18n: latin() (Greek to Latin, the way venues write it) + tests.
- tests: manager media.test.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:57:50 +02:00
bonaminandClaude Opus 5.5 5ad4c4ef55 feat(backend): products and categories point at the media library (platform-v2 step 5.2)
- products.media_id / categories.media_id (Alembic 0027): the old
  /static/product_images photos are processed into the library (named after
  their product; missing or unreadable files logged and skipped; the old
  folder is left on disk) and products.image_url goes. The static mount is gone.
- APIs give `image` {id, name, thumb, card, full}; a product's image_url is its
  card size. media_id on create/update (null clears); media.not_a_picture for
  a video. POST /api/products/{id}/image is gone: uploads go to /api/media.
- Products and categories register their media usage: a photo in use can't
  be deleted.
- Media: AVIF pictures (Pillow 12.3), GET /api/media/{id} gives each stored
  size's bytes and resolution and the uploader's name; upload processing moved
  into services/media.ingest (also used by the data move).
- QR menu photo push (contract C-3): the library's card size, WebP.
- tests: test_product_photos.py (7, incl. the 0027 data move); 497 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:57:50 +02:00
bonaminandClaude Opus 5.5 238f8ec5a0 feat(backend): media library: files once by hash, WebP sizes, cached, protected while used (platform-v2 step 5.1)
- Table `media` (Alembic 0026): kind, name, original name, type, sha256
  (unique), bytes, width/height, video length, who and when.
- Files under /app/data/media/<sha[:2]>/<sha>/: the original, and for
  pictures thumb (200 px) / card (600) / full (1920) WebP, upright from
  EXIF, never enlarged, transparency kept. Videos (MP4, WebM) kept as
  uploaded; an MP4's length and size come from its header.
- GET/POST /api/media, GET/PATCH/DELETE /api/media/{id} for whoever manages
  the menu, customer display, signage or menu tablets. The same file again
  returns the existing item. The type comes from the bytes; 20 MB pictures,
  200 MB videos, 60 MP; refused uploads leave nothing behind.
- GET /api/media/file/<sha>/<variant>: public (LAN), Cache-Control
  public, max-age=1 year, immutable; byte ranges for video; a missing size
  is made again from the original.
- register_usage(kind, fn): what uses media (products, displays, signage
  from 5.2-5.4) declares it; delete is refused with media.in_use listing
  the users.
- tests: test_media.py (12); stack.mjs uploads 3 MB through both nginx hops
  and fetches a size with its cache headers (compose stack: all passed).
  Backend suite: 490 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:22:26 +02:00
bonaminandClaude Opus 5.5 24971533a0 fix(proxy): accept uploads up to 250 MB in every nginx hop
nginx's default client_max_body_size is 1 MB, so a phone photo (3-5 MB)
uploaded as a product image or customer-display image was refused with
413 before it reached the backend. The proxy (both copies, CS-5) and the
waiter, manager and terminal images now allow 250 MB; the backend checks
the real limits (media library: 20 MB pictures, 200 MB videos, step 5.1).
All five configs pass `nginx -t`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:22:26 +02:00
bonaminandClaude Opus 5.5 1fc34d6c9e docs+test: phase 4 wrap-up (platform-v2 step 4.99)
- Pack README: CS-3 now says orders are queued by id and priced on sync, refused lines
  are shown, and no request a screen waits for may hang; rows for the waiter's texts /
  colours guards and the table, ordering and bookings pages.
- run-all: the waiter suite's label lists what it covers.
- waiter.mjs: the language check waits for the profile save (the screen changes first).
- android.mjs: the "server really down" check accepts the offline screen in place of the
  app (the start-up data failing shows it there since the bootstrap time limit), not only
  on /offline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:09:18 +02:00
bonaminandClaude Opus 5.5 eba630e06e test(android): the sign-in screen check after pairing waits up to 15 s (a fresh install is slow to show it)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:29:21 +02:00
bonaminandClaude Opus 5.5 f57894dcb7 feat(waiter): table bookings on the phone; shared ReasonPicker (platform-v2 step 4.8c)
- Waiter: Bookings (side drawer, for whoever has connect_orders.manage or
  reservations.manage, with the online-orders app on): requests made online are
  confirmed or declined with a reason the guest sees; confirmed ones are seated at a free
  table (its seats shown, a warning mark when the party is bigger) or cancelled / marked
  as a no-show; the food ordered ahead and its kitchen time; live updates.
- Backend: the bookings routes take reservations.manage too (require_any).
- @xenia/ui ReasonPicker + reasonText (gallery, unit test), first piece moved from the
  terminal (4.6 → 4.8): the counter's online reject and booking decline dialogs use it;
  the waiter loads @xenia/ui styles.css (the .x-* components; tokens as before).
- Tests: waiter e2e +2 (request listed with the key, confirmed and seated from the phone);
  terminal.mjs and qr_table.mjs green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:10:14 +02:00
bonaminandClaude Opus 5.5 1e8271e370 feat(waiter): where each line came from; QR lines marked, the QR message opens the table (platform-v2 step 4.8b)
- order_items.source (Alembic 0025): waiter | counter | qr | online, set by the server
  (orders.add_priced_items: the phone / manager 'waiter', the counter 'counter'; the QR
  menu's lines 'qr', online orders 'online'; a split line keeps its source); lines of
  existing online orders backfilled 'online'; in the order's item output.
- Waiter: lines the guests sent from the QR menu (or an online order) carry a "📱 QR" /
  "🌐 Online" mark; the qr_order message's banner has "Open the table", and in the bell's
  list the message opens it.
- Tests: source per channel, migration 0025, QR placement marks 'qr'; waiter e2e +1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:59:57 +02:00
bonaminandClaude Opus 5.5 198f8ff571 feat(waiter): close with unpaid items as a setting, combine lines, seats (platform-v2 step 4.8a)
The owner's choices for 4.8 (2026-11-18), all configurable:
- Setting orders.close_with_unpaid (default off): when off, the server refuses to close
  an order with unpaid items (pos.order_unpaid) and the phone's CLOSE takes the payment
  first ("instant-pay close"); when on, CLOSE confirms and the items stay unpaid. Manager
  Settings → Operation, next to "auto-close after full payment" (unchanged).
- POST /api/orders/{id}/items/combine: unpaid lines of the same item (choices, note,
  price, course, kitchen state; no discount / deal / tab) become one line; the phone
  offers "Combine into one line" for selected lines or a grouped line. The grouping
  views (identical / same item) stay as they were.
- Seats: the table's seats next to its name on the cards (waiter Settings → Layout, on by
  default) and in the guests dialog, where more guests than seats only shows a hint.
- The table screen's last English-only labels (ADD, PAY, CLOSE, ACTIONS, SERVED, CLEAR,
  ALL) are keys too.
- Tests: test_close_and_combine.py (5), waiter e2e +5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:54:37 +02:00
bonaminandClaude Opus 5.5 beb53c65bb feat(waiter): the look on the shared tokens; the venue's colour (platform-v2 step 4.6)
- The waiter's --bg/--text/--accent… are made of @xenia/ui tokens: light / dark (user
  menu) and the venue's accent reach every screen; the 751 colour literals in
  waiter_pwa/src became tokens (by hue family and lightness), hex-alpha suffixes became
  fade() (color-mix), fixing 'var(--accent)18' tints that never showed.
- @xenia/ui: new `special` (violet: offers, discounts, deals; contrast-tested) and
  `on-colour` tokens.
- Setting venue.theme (teal | amber | blue | violet | rose, default amber), bootstrap
  venue.theme, manager Settings → Venue → Colour; the waiter sets data-venue-theme and
  the theme before the first render.
- Guard tests/no-colours.test.mjs; tests/e2e/waiter_look.mjs (every page light + dark,
  side-by-side compare page); waiter e2e +3; backend test_venue_theme.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:08:39 +02:00
bonaminandClaude Opus 5.5 d8c3a6c57c fix(access): the bootstrap request gets an 8 s time limit
A bootstrap request that never answered (seen on the Android emulator after a cold start
with the server down) left the app on its loading screen for good: no error, so no retry.
It now times out, counts as offline (cached bootstrap / offline screen) and is retried, so
the app comes back by itself when the server does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:08:38 +02:00
bonaminandClaude Opus 5.5 9e1912bce0 feat(waiter): a table's earlier orders (platform-v2 step 4.7)
- GET /api/tables/{id}/history: the table's closed / cancelled orders, newest first,
  for the waiters of its zone (ordering.orders.open), never older than the history
  module's history_days (free tier 31, D-6), module.disabled when history is off;
  each order with times, total (cancelled items left out), people and items.
- Waiter: a History tab on the table (and "This table's earlier orders" on a free
  table); orders expand to their items; the last answer is kept on the phone and
  shown offline, marked as saved; the plan's day limit is shown.
- Tests: test_table_history.py (4), waiter e2e +2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 04:45:31 +02:00
bonaminandClaude Opus 5.5 f8d91e7fae feat(waiter): English-first texts, part c: shift, log, chat, offline, notifications; language switch; guard (platform-v2 step 4.5c)
- Shift overview, order log, chat list / thread, offline + server search +
  rediscovery screens, notifications, the refused-lines sheet and the offline queue's
  reasons become keys; times and dates through useFormat() in the venue's clock.
- User menu: the other language(s) (data-testid menu-language-<lng>), saved to the
  person's profile (PATCH /api/auth/me) and the bootstrap reloaded (D-12).
- tests/no-greek.test.mjs: no Greek letter in waiter_pwa/src (the one Greek word the
  app recognises in staff messages is a \u escape).
- e2e: the test venue is English: waiter / browser / android use the English texts;
  waiter.mjs +3 (English by default, switch to Greek at once and saved, after reload);
  android bundle checks print what they saw when they fail.
- Pack README: the waiter texts rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 04:31:48 +02:00
bonaminandClaude Opus 5.5 2c4f78af47 feat(waiter): English-first texts, part b: table detail, ordering, options, payment (platform-v2 step 4.5b)
- Table detail (actions, item actions, split, price, discount, pay / revert / close,
  move / merge / transfer, guests, flags, assign, print), the order drawer (tabs,
  options, quick notes, price change, summary), add items (cart, totals, deals,
  search), the order summary and the summary before sending, the product picker.
- Money everywhere here in the language's format (`money()` in waiter i18n.js for
  helpers shared by several components, useFormat() elsewhere).
- The default quick notes are keys (the venue's own quick notes still win).
- Variables named `t` (tables, tabs, timers) renamed so they don't shadow t().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:59:12 +02:00
bonaminandClaude Opus 5.5 37155c0457 feat(waiter): English-first texts, part a: shell, sign-in, tables, settings, venues (platform-v2 step 4.5a)
- @xenia/i18n: new `waiter` namespace (en + el); the waiter's Greek texts become keys
  with English written fresh (Greek kept as the translation).
- App gates, side drawer / nav bars / notifications, user menu, login, table list and
  cards, settings, venues + pairing errors, install dialog, lock screen, update banners,
  QR scanner, favourites setup.
- Money and times through useFormat() (venue time, the language's number format):
  table cards, quick table view, user menu, notifications.
- waiter i18n.js: tw() for code outside components (pairing errors).
- The table-list's FavoritesSetupPage `.map(t => …)` renamed so it doesn't shadow t.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:50:33 +02:00
bonaminandClaude Opus 5.5 8e0a786bbc feat(ordering): orders priced by the server (platform-v2 step 4.4)
The waiter app (and the manager's ordering tab) send what was chosen, by id; the
server prices it with the counter's code. No app sends a price any more.

- POST /api/orders/{id}/items takes `lines` (pos_cart's line + course_id,
  price_adjustment, is_service_item): sales point checked first, refusals name the
  product and line (order.line.*, order.not_sold_here); prices or selected_options in a
  line -> order.line.client_price, the old `items` shape -> order.lines_required; a
  by-hand price change needs ordering.prices.modify or a manager's approval (audited
  PRICE_SET_BY_HAND). add_priced_items is the one writer of priced items (pos too).
- POST /api/orders/quote: the cart's total before sending; /api/pos/quote shares
  pos_cart.quote().
- pos_cart: a preference set left out takes its default; a set at its free default
  isn't stored; a default that costs is charged (the waiter never sent it: fixed);
  an extra's sub-choice is charged per extra (the counter charged it once: fixed).
- @xenia/api lines.js: lineFromOptions / wireLine / estimate / LineError.
- Waiter: lines on send; cart total from the quote ("≈ estimate" offline); summary
  shows the same prices; offline orders queued by id, priced on sync, refused lines
  shown on a "Δεν στάλθηκαν" sheet (no empty order opened); dead ItemOptionsModal gone.
- Tests: test_order_lines.py (14), lines.test.mjs, waiter e2e +6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:35:03 +02:00
bonaminandClaude Opus 5.5 bcf91bf6e9 test(android): self-healing WebView handle, fresh emulator, diagnostics (KI-015)
- lib/cdp.mjs: attach to the visible, non-empty page target (a replaced WebView can
  leave the old target listed first); a closed DevTools socket fails pending calls at
  once instead of hanging; every call has a timeout.
- lib/android.mjs: attach() follows the app's current process (socket named after its
  pid; an old one can linger) and re-attaches before a call when the process or the
  live page changed; a call cut off by the page going away is retried once.
  ensureDevice() reboots an emulator up longer than EMULATOR_MAX_UPTIME_MIN (30).
- android.mjs: switching venues waits until /venues lists them (the app may still be
  reloading into the last venue's bundle); a rediscovery timeout logs the page's DOM
  and console next to the screenshot.

Run alone: rediscovery 7/7, basics 3/3, stacks 21/21.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:35:02 +02:00
bonaminandClaude Opus 5.5 8abe4d92d3 feat(waiter): what a waiter may do comes from permission keys (platform-v2 step 4.3)
- Payments: ordering.orders.close checked on pay/close and the counter POS
  (waiters have it by default, owner decision); pay-offline always recorded.
- The venue switches waiter_cancellations / price_adjust / revert are gone:
  ordering.orders.cancel, ordering.prices.modify and the new
  ordering.payments.revert (overridable) decide; moves/split/transfer/merge
  need ordering.orders.open; discounts pricing.discounts.apply; chat chat.use.
- Venue role defaults: role_permissions (Alembic 0024), role_template(role, db),
  GET/PUT /api/waiters/roles/{role}/permissions applying the change to everyone
  with the role; manager Settings -> Operation -> "What each role may do".
  0024 also grants the new key to existing owners and store managers.
- Bootstrap `approvable`; @xenia/access useAllowed(key) -> yes/approve/no.
  The waiter shows each action by key, "with a manager's approval (PIN)" where
  allowed; GET /api/orders/cancel-permissions removed.
- Tests: test_waiter_keys.py (11), access allowed(), waiter.mjs +5, manager.mjs +3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 00:54:08 +02:00
bonaminandClaude Opus 5.5 a29a167977 fix(waiter): rediscovery probe timeout 1.5 s -> 3 s
A new plain-HTTP connection can take about a second on a busy network; inside
the 48-wide /24 scan the real server's answer then missed the 1.5 s limit and
the moved server was never found (seen on the Android emulator, 0.9 s first
connection). 3 s keeps a full scan under ~20 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 00:54:07 +02:00
bonaminandClaude Opus 5.5 8299184e3a feat(waiter): sign-in v2 on the phones (platform-v2 step 4.2)
- Login follows auth.waiter_login_mode / auth.waiter_require_username from the
  bootstrap: name + PIN, name + password, typed username, or a "paired screens
  only" message for tap mode. POST /api/auth/login {client: "waiter"}; a miss
  shows the translated error without a reload.
- POST /api/auth/login-by-id removed; bootstrap login carries waiter_mode and
  waiter_require_username.
- Sign-out ends the session on the server (POST /api/auth/logout), so
  single_session_waiter = refuse_new no longer strands a waiter.
- Lock on the phone: menu "Lock", automatic lock / sign-out after inactivity
  (security.auto_lock*, auto_logout*), unlock with the PIN in the same session,
  lock kept across app restarts (restore() no longer clears it).
- e2e: new waiter.mjs (22 checks) in run-all; android.mjs signs in for real and
  locks/unlocks on the emulator; TLS live check waits for the socket; the
  rediscovery helper re-attaches to a stale WebView handle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:25:00 +02:00
bonaminandClaude Opus 5.5 9f5498332a feat(waiter): the waiter app on the shared foundations (api client, access, i18n), lint clean, starts offline
Plan step 4.1. No visible change to layout or flows.
- api/client.js on @xenia/api createApiClient (CS-8 baseURL, 401 → sign out, no answer →
  backend-offline, err.xenia, the manager-approval retry); the PIN login handles its own 401
  (before, a wrong PIN reloaded the page).
- <AccessProvider> at the root with an i18n instance: modules, permission keys, venue,
  language from bootstrap; who is signed in comes with it (no more /api/auth/me polling).
  packages/access: AccessProvider gains `cache` (the last bootstrap per session; used when
  the server can't be reached, `offline` in the context, keeps retrying) and `failed` (the
  app's own screen when there's nothing cached). The waiter caches per venue, shows its
  offline page (server search) on a first start without a server, retries every 5 s;
  ServerRediscovery and BundleSync run outside the bootstrap.
- Role names → keys: the shift gate and the user menu use core.dashboard.access.
- One shared, offline-cached read of the venue settings (api/venueSettings.js) instead of
  seven GET /api/settings/ calls; apiError() shows backend error codes in the user's
  language (17 places).
- Lint: 78 errors → 0 (unused code, empty catches, two duplicate style keys, a component
  created during render, refs read during render → state, hooks after an early return);
  set-state-in-effect is a warning like the manager/terminal; lint in run-all.
- Tests: tests/bootstrapCache.test.mjs; e2e browser: an offline restart stays signed in.
  Android rediscovery waits for what the screen shows instead of fixed sleeps: 10/10 three
  runs in a row (KI-009). Terminal 3.4 waits for both displays before the sale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:37:47 +02:00
bonaminandClaude Opus 5.5 f85894a72e refactor(connect): one live connection, no token in any address (SSE removed)
Plan step 4.0. Owner (2026-11-17): no phone in use needs to keep working, so no
compatibility path.
- Removed the SSE channel: routers/sse.py (/api/sse/stream, which still accepted a JWT whose
  session had ended — a signed-out phone could keep listening), services/sse_bus.py (every
  backend module now calls services/ws_bus.broadcast_sync directly), waiter useSSE.js.
- Credentials only in the first frame: the waiter's useWebSocket and the manager's
  LiveProvider send {token} there like the terminal; routers/ws.py no longer reads ?token=
  (a token in a URL ends up in proxy and server logs).
- Waiter: SSEContext → LiveContext (LiveProvider, useLiveContext, liveAlive, the
  'live-event' / 'live-reconnected' window events), dead SSE compat code removed.
- Tests: a token in the address is refused, /api/sse/stream is 404; e2e browser (3 delivery
  modes) and manager assert no token in the live connection's address. Android taps now
  wait for their element (the fixed sleeps made the suite flaky, KI-009).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:49:21 +02:00
bonaminandClaude Opus 5.5 d0c6a10e47 docs: CS-19 device apps (who hears what, scope patterns, replays) — platform-v2 phase 3 wrap-up
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:12:22 +02:00
bonaminandClaude Opus 5.5 dabe807ce0 feat(connect): caller ID as an integration: calls on the signed-in live connection, matched on the server
Plan step 3.5.
- The public /api/phone/ws socket is removed (anyone on the LAN could listen to every
  caller). GET /api/phone/call-event stays public for the Grandstream UCM but is LAN-only in
  the proxy (the 443 blocks' LAN-only location now covers it, in nginx-proxy/nginx.conf and
  install.sh), with an optional shared secret (setting caller_id.secret → &key=).
- Calls are logged (phone_calls, migration 0023), matched to a customer on the server
  (services/caller_id.py: Greek number rules moved from the manager) and published as
  `call_incoming` {call_id, at, number, ext, customer card: visits, spent, last 3 orders} to
  users with caller_id.use and to the counter POS screens. GET /api/phone/calls (the log),
  GET /api/customers/lookup?phone=. Calls older than a minute don't pop up (replays).
- Manager: PhoneListener on the live connection and the shared Dialog (no more downloading
  every customer to match); Integrations → Caller ID shows the server's log live and the UCM
  Action URL. Counter: CallPopup with "New takeaway sale".
- Tests: tests/test_caller_id.py (10), terminal unit test, e2e terminal and manager.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:06:39 +02:00
bonaminandClaude Opus 5.5 88a9703902 feat(terminal): the customer display, with an idle screen each venue designs
Plan step 3.4. Owner (2026-11-16): the idle screen is configurable per venue.
- routers/customer_display.py (module customer_display, /api/display): the counter POS
  pushes its state (POST /api/display/state: idle | cart | paid with lines, total, paid,
  change); only the displays linked to that POS get `display.state`; the last state is kept
  in memory for a display that reconnects (GET /api/display/state). pos_counter's device
  scope includes customer_display.state.
- The idle screen: setting customer_display.idle (name, logo, logo + name, blank, one
  image, slideshow, QR code to the online ordering / QR menu / any link; a line of text;
  dark or light); images uploaded to /app/data/display_media (JPG/PNG/WebP/GIF ≤ 5 MB,
  random names, served publicly on the LAN); a change sends `display.settings` to every
  display. New key customer_display.manage (owners, store managers; migration 0022).
- Terminal: CustomerDisplayApp (cart with a large total, "Thank you" with the change for
  12 s, the venue's idle screen, its theme), logic.js (unit-tested); the POS pushes from the
  sale cart and the payment dialog (tables, online orders too) via useDisplay().
  qrcode.react added to the terminal (already in the workspace).
- Manager: Settings → Customer display (style cards, venue name, text, look, slide seconds,
  QR target/link/caption, image upload/pick/order/delete).
- Tests: tests/test_customer_display.py (3), terminal display.test.mjs (3); e2e terminal
  (linked vs unlinked display, < 1 s, paid, QR and slideshow idle screens), manager (the
  settings tab).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:34:05 +02:00
bonaminandClaude Opus 5.5 18d580d87c feat(manager): the venue's online ordering link and QR code on the Online ordering page
Plan phase 3S, step S.99.
- GET /api/connect/fees returns `links` {order, menu}: the ordering app and QR menu
  addresses, from the cloud's apps_url (heartbeat) and the site id.
- Manager: "Your ordering link" card (OrderingLink.jsx) on Online ordering: the address, its
  QR code, copy / open / print, to share or put on the website and window.
- Pack README: routers/fees.py row.
- Tests: the link (backend), the card (manager e2e).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 01:36:02 +02:00
bonaminandClaude Opus 5.5 652e6a26af feat(connect): the QR menu at the table: one code per table, orders straight onto the table
Plan phase 3S, step S.7.
- tables.qr_token (migration 0021): a random token per active table; services/table_qr.py
  (tokens, rotate, the snapshot's `qr` with the tokens' sha256 only, the code's link from the
  cloud's apps_url); setting connect_menu.table_ordering (read-only by default).
- /api/connect/qr (connect_menu.manage): the codes, ordering on/off, a new code per table or
  for all; table and QR changes push the menu at once (MENU_PATHS).
- Pull: a QR order with a table id goes onto the table's open order or a new one
  (services/qr_orders.py): items at the cloud's prices, kitchen tickets, KDS, order_updated
  (the waiters' phones and the counter), a `qr_order` message to the order's waiters or the
  table's zone waiters; audit QR_ORDER (a repeated pull adds nothing); the cloud is told
  "accepted" (the guest's page: in the kitchen). No usable table or no open day → the counter
  gets it as before. Waiter app: the message's look.
- Manager: Online → Table QR codes (/online/qr): ordering switch, the menu link, a QR card
  per table (print all), new code per table / for all.
- Heartbeat: apps_url kept in the license state.
- Tests: tests/test_qr_table.py (5); e2e qr_table.mjs (a real cloud and venue: table 5's
  code → two dishes on table 5's order, KDS, live event, the guest's page; a forged code
  refused; a new code kills the old one), in run-all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 01:26:55 +02:00
bonaminandClaude Opus 5.5 70c8f2bb57 feat(connect): table bookings from the online ordering app; food fired to the kitchen before arrival
Plan phase 3S, step S.6.
- Pull: "reservation" / "preorder" orders become Reservations waiting for an answer
  (status "requested"; services/online_reservations.py), with the food ordered ahead kept on
  the booking (items_json at the cloud's prices, the site's price check) — no order yet.
  Migration 0020 (reservations: online_order_cloud_id, online_ref, items_json, total,
  online_price_diff, fire_at, order_id, response_note).
- Confirm → the food's fire time = booking time − fire minutes (setting); the fire worker
  (connect_orders, every 20 s) turns the food into an order at that time (needs an open
  business day; waits otherwise): kitchen tickets, KDS (reference and time). Early arrival
  fires at once. Seating moves the order to the table (refused if the table has an open
  order). Decline / cancel / no-show with a reason. Every step mirrored to the cloud.
- Found: the KDS filter dropped every online order without an online status (SQL NULL in
  NOT(a AND b)) — made NULL-safe.
- Counter: Online → Bookings (requests first, then upcoming), BookingPanel (confirm,
  decline with reasons, food and when it goes to the kitchen, seat at a free table, cancel,
  no-show); the Online badge and chime count booking requests.
- Manager: Online ordering → Table bookings settings (on, food ahead, hours, slot, notice,
  days ahead, party size, fire minutes); the dashboard's reservations card confirms /
  declines online requests; the reservations router delegates online bookings' status steps.
- Tests: tests/test_online_bookings.py (8), unit tests (terminal, manager), e2e: order app
  (book with food → the venue confirms), terminal (request → confirm → the two dishes reach
  the KDS at the fire time, not before → seated), manager (booking settings).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:31:44 +02:00
bonaminandClaude Opus 5.5 0ca700279a feat(connect): the site side of online orders: fee line, customer's time, price check
Plan phase 3S, step S.5.
- Pull: an online order keeps the customer's time (orders.requested_for, None = as soon as
  possible) and delivery area; quick options are stored in the site's entry shape; items get
  their cost snapshot.
- The delivery fee is its own order line: a system product (products.system_key
  "delivery_fee", lifecycle "system", sold nowhere; services/system_products.py), created on
  first use in the venue's language with the VAT group most products use. Added printed and
  served, so kitchen tickets and the KDS never see it; paid at the counter with the items,
  counted in the shift, on the fiscal receipt with its VAT group. Never listed in the
  catalogue (products list, export, edit endpoints → 404) and never added by hand.
- Price check (services/online_check.py): each line priced as the snapshot prices it, at the
  order's time, and the fee through the same engine with the site's rules and the cloud's
  area id; differences kept on orders.online_price_diff and shown. The customer pays what
  the cloud charged.
- Counter: time chip (or as soon as possible), area, fee line, price warning; takeaway is
  its own kind (was shown as "at the venue") and finishes as "collected". KDS cards show the
  online reference and the time; kitchen tickets print the reference, the type and the time.
- Manager: Online ordering → "The fee on the receipt" (name, VAT group;
  PUT /api/connect/fees/fee-product, fees.vat_group_unknown); the online orders page shows
  the time, area and price warning.
- Migration 0019. Tests: tests/test_online_site_side.py (6), terminal unit test, e2e
  (terminal: fee, time, warning, paid in full; manager: fee line settings).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:38:25 +02:00
bonaminandClaude Opus 5.5 8ea44d71aa feat: online ordering settings (services, hours, preparation, slots) and the order app e2e (platform-v2 3S, S.4)
- connect_orders.ordering setting; GET/PUT /api/connect/fees/ordering (validated:
  services, hours per day incl. past midnight, preparation, slot minutes, days ahead,
  ASAP); pushed to the cloud with the menu (snapshot `ordering`).
- Manager: the Online ordering page gains "Services and hours" (OrderingSettings.jsx; logic
  in feesLogic.js, unit-tested); nav label "Online ordering".
- tests/e2e/order_app.mjs: a real cloud + the built order app in a phone-sized browser:
  takeaway and delivery placed, priced by the cloud (fee by area, minimum refused), the
  site moves the delivery to delivered and the page follows; a rejection with its reason;
  Greek. In run-all, with the order app's unit tests.
- Tests: backend +1 (406), manager unit +1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:39:13 +02:00
bonaminandClaude Opus 5.5 df27133af9 docs: fee engine has a byte-identical copy in the cloud (pack README)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:29:41 +02:00
bonaminandClaude Opus 5.5 9bfe54554d feat: delivery areas and fee rules with "test an order" (platform-v2 3S, S.3)
- models/fees.py + Alembic 0018: delivery_areas, fee_rules; key connect_orders.fees
  (owner, store manager; existing ones get it).
- services/fees.py: the pure engine (set / add / % / free / minimum, conditions: sales
  points, areas, products total, item count, days, time incl. past midnight, stop), the
  same file as the cloud's; tests/fixtures/fee_cases.json shared, plus a test that the
  cloud copy is identical.
- routers/fees.py at /api/connect/fees: areas and rules CRUD (validated), order, preview.
- Snapshot carries fees + the venue's time zone; a change to products, pricing or fees
  pushes the menu within ~5 s (middleware -> cloud_sync.request_menu_push).
- Manager: Online -> Delivery fees page (@xenia/ui): rules in order with words for each,
  areas with postcodes, "Test an order"; en/el texts; feesLogic.js unit-tested.
- Tests: test_fees.py (39), manager unit +5, manager.mjs +7 on the real page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:28:29 +02:00
bonaminandClaude Opus 5.5 ffeb2b45cb feat: the menu snapshot carries a price per sales point; pulled orders keep the cloud's sales point and table (platform-v2 3S, S.2)
- services/cloud_sync.menu_snapshot(db) (split out of the push, tested): sold_at + prices
  per customer-app sales point from the pricing engine; digital_price = the QR menu's.
- store_online_orders: sales_point from the cloud (older clouds: from the type), takeaway
  orders typed takeaway, the QR menu's table in front of the customer's note.
- manager e2e: waits for the live connection (html[data-live]) instead of a fixed 1.5 s,
  and for the server to record "read" (two timing races seen in a full run).
- Tests: +2 in test_sales_points.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 11:38:46 +02:00
bonaminandClaude Opus 5.5 1b468fe44b feat: sales points, offerings and prices per sales point (platform-v2 phase 3S, step S.1)
- core/sales_points.py: in_store, in_store_takeaway, qr_table, online_takeaway,
  online_delivery, online_preorder (+ old channel names mapped).
- Alembic 0017: orders.sales_point (backfilled), products.sold_at (from digital_visible),
  digital_price/digital_discount -> item price modifiers for the QR menu and online,
  order_channel conditions -> sales points; drops the three digital columns.
- Every order records its sales point; the pricing engine's channel is it; items not sold
  there are refused (order.not_sold_here, pos.line_invalid not_sold_here).
- POS menu: only what the counter sells, prices per counter sales point; the screen shows
  the order type's products and prices. Waiter app asks for in-person products.
- Cloud snapshot: products sold by the customer apps, priced by the engine.
- Manager: product "Where it's sold" tab; pricing condition shows sales points.
- Products API, catalogue export/import carry sold_at.
- Tests: test_sales_points.py (8, incl. the migration), access +1, terminal +1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 11:00:40 +02:00
bonaminandClaude Opus 5.5 f2182dcb37 feat(pos): refunds at the counter on a fiscal driver layer (platform-v2 3.3e)
- services/fiscal/: one driver interface (prepare_receipt / prepare_credit_note -> send,
  credit_notes flag, status); the dTEC100extra folder bridge moved into txt_file.py as the
  first driver, same command files. fiscal_service.py removed, callers moved.
- Refunds: models/refund.py + Alembic 0016 (refunds, refund_items; ordering.refunds for
  existing owners/managers). services/refunds.py: today's business day, the cashier's open
  shift, partial quantities, items from another shift need ordering.refunds or a manager's
  approval (check()/authorize() return the override row). Paid items are never edited.
- POS: GET /api/pos/receipts, GET /api/pos/receipts/{id}, POST /api/pos/orders/{id}/refund
  (cash opens the drawer; fiscal "manual" when the driver can't issue credit notes).
- Shift totals subtract refunds and now count discounts; day close and business-day
  reports carry refunds.
- Terminal: Receipts mode (ReceiptsView, ReceiptPanel, logic/refunds.js), en/el texts.
- Tests: test_pos_refunds.py (12), terminal unit +1, terminal.mjs +7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:44:17 +02:00
bonaminandClaude Opus 5.5 d542cf7d34 feat(backend,terminal): online orders on the counter POS (platform-v2 step 3.3d)
- Counter POS gets an "Online" mode (module on + connect_orders.manage): New / In
  progress / Finished, a chime on arrival (and every 30 s while one waits), badge,
  toast in any mode; the order panel offers only the next step: accept / reject with
  a reason, preparing, ready or out for delivery, then take the payment (shared
  PaymentDialog, drawer, shift) and mark delivered/served.
- connect_orders router on v2 conventions: require(connect_orders.manage), error
  codes online.not_found / online.status_changed, the cloud's step order enforced,
  audit rows, GET /api/connect/orders/board. POS device scope gains connect_orders.*;
  barista and barman get the key by default.
- Fixes: the KDS showed online orders before acceptance; accepting printed no
  kitchen tickets; a pull whose synced mark failed stored the order twice
  (store_online_orders skips known cloud ids); pulled orders lacked the business day
  and delivery type; rejected orders kept active items; delivered sets closed_at/by.
- Online orders belong to holders of connect_orders.manage (_can_access_order), so
  the counter pays them with POST /api/pos/orders/{id}/pay.
- Tests: test_pos_online.py (5), terminal unit +1, terminal.mjs +17 with a fake
  cloud (pull, synced, status mirror); fixed a timing race in a 3.3c check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 05:42:06 +02:00
bonaminandClaude Opus 5.5 988d413d8e feat(backend,terminal): tables at the counter, shared live with the waiter phones (platform-v2 3.3c)
- POS: GET /api/pos/tables (the cashier's zones as in the waiter app, each open order's
  totals, people, ready items, flags, reservation), POST /api/pos/tables/{id}/items (into
  the table's order or a new one via orders.open_order + add_items), POST
  /api/pos/orders/{id}/pay (chosen items, cash/card/split, drawer on cash), POST
  /api/pos/orders/{id}/close (only when nothing is unpaid). Quote takes order_id so the
  order's items count for cart conditions (shared pos_cart.order_cart, used by add_items).
- New codes pos.table_not_found, pos.table_not_yours, pos.items_changed, pos.order_unpaid.
- Fix: item cancels (DELETE item, cancel-items) now broadcast order_updated, so phones and
  kitchen screens see them at once.
- Terminal: Sale | Tables switch, zone list, table cards by zone, TablePanel (order lines,
  new lines, send, pay selected/all, cancel with approval, close), generic PaymentDialog.
- Tests: test_pos_tables.py (8), terminal unit, terminal.mjs +17 with a live phone socket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 02:15:54 +02:00
bonaminandClaude Opus 5.5 bff82a332a feat(terminal): quick sale at the counter: cash/card/split, change, cash drawer, fiscal (platform-v2 3.3b)
- POST /api/pos/sales: all checks first (shift, lines, payment split, cash given,
  discount → ordering.prices.modify or manager approval, fiscal VAT groups), then the
  existing open_order / add_items / pay_items functions, so tickets, KDS, price events,
  shift totals and the fiscal receipt work as for any order.
- Cash drawer: printer_service.open_cash_drawer (ESC @ + ESC p 0 25 250) to the screen's
  receipt printer on cash, logged and audited (DRAWER_OPENED / DRAWER_FAILED).
- orders._can_access_order: the people assigned to an order may act on it (a cashier's
  own takeaway order); pos_cart prices a batch with the lines before it, as add_items does.
- Terminal: Charge → payment dialog (exact cash pre-selected, quick amounts, change,
  card, split by line), per-line discounts, sale summary and "Same again".
- Tests: backend +6 (socket printer receives the drawer kick, fiscal file in the bridge
  folder), terminal unit +1, terminal.mjs +9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:28:33 +02:00
bonaminandClaude Opus 5.5 17bee66df1 feat(terminal): counter POS screen with server-priced cart and shift gate (platform-v2 3.3a)
- Backend /api/pos (pos_counter): session (business day, the cashier's own shift,
  self-start, who can open the day), menu (sellable products with every kind of choice,
  no costs; price now from the pricing engine), quote (lines by id → the waiter's
  selected_options entries with DB prices → resolve_price as orders do; pos.line_invalid).
- POS device settings: default order type, start category, receipt printer (new ref
  sources categories / printers, also in the manager's Devices dialogs).
- Terminal apps/pos: shift gate (start shift with drawer cash), categories, search,
  product grid, price check, options dialog, cart priced by the backend.
- Tests: backend test_pos (13), terminal pos.test.mjs, manager refOptions,
  terminal.mjs +10 POS checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:55:30 +02:00
bonaminandClaude Opus 5.5 b1112b249e feat(manager): remove the KDS page; app cards lead to pairing a screen (platform-v2 3.2d)
- Deleted pages/KdsPage.jsx, its /kds route, nav entry and text: the kitchen display
  runs only on paired screens (D-25).
- Apps: cards of apps that run on a screen get "Set up a screen" (core.devices.manage)
  → /devices?pair=<app>, which opens the pair dialog on that app.
- manager.mjs: no "Open" on the KDS card, "Set up a screen" lands on the pair dialog,
  /kds is gone; the module-off rule stays covered by the Notes checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 20:46:50 +02:00
bonaminandClaude Opus 5.5 6b237fd169 feat(backend): KDS item claims across screens; zone screens only touch their own items (platform-v2 3.2c)
- order_items.claimed_by / claimed_at (Alembic 0015). POST/DELETE
  /api/kds/orders/{id}/items/{item}/claim (kds.bump): someone else's claim is refused
  (kds.item_claimed), letting go works for anyone with kds.bump; live kds_item_claimed.
  In progress claims for whoever did it; done/served/pending/declined clear the claim.
- Fix: order-level status and decline from a zone screen changed every zone's items;
  now only the screen's zone, and a zone screen sees the order status of its own items.
- Terminal: "I'm on it" / "Let go" on the selected card, the cook's name on claimed items.
- Tests: backend +6, terminal unit +1, terminal.mjs +6 with a second screen and cook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 20:25:34 +02:00
bonaminandClaude Opus 5.5 77e0adbe9c feat(ui): board design language as global tokens; KDS on tokens and shared components (platform-v2 3.2b-2)
- @xenia/ui: --x-board-* tokens (the kitchen display's look: dark board, light cards,
  status colours, card radius/shadows, number font), Tailwind board.* colours, contrast
  test for the board pairs; near-identical shades merged.
- New shared Stepper component (gallery + ui.mjs), labels ui.decrease / ui.increase.
- KDS: theme.js maps to the board tokens, no colour literals left (only stored setting
  values); decline / call waiter / settings use Dialog, Button, Switch, Select, Stepper;
  toasts are @xenia/ui toasts (ToastProvider at the terminal root).
- Terminal: apps can set their theme (APP_THEMES, KDS dark) while they run.
- CS-16: board screens and "no hard-coded colours in app code".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 20:02:35 +02:00
bonaminandClaude Opus 5.5 5f6d4ab428 feat(terminal): kitchen display on paired screens, live without polling (platform-v2 3.2b)
Port of the manager's KdsPage.jsx into terminal/src/apps/kds, split into pure logic
(layout packing, age, buckets, rounds, totals, status cycle, settings; unit-tested) and
components (card, item, action bars, dialogs, item totals, rails, settings panel).
- Settings are the device's config; the settings panel saves them (managers only),
  zoom changes the size for the session.
- Orders reload on live events and every reconnect; polling only while the live
  connection is down (DeviceProvider exposes liveUp; useLiveEvents helper).
- "Tap to start" unlocks sound; venue clock via useFormat; English-first texts.
- Undo of an item recomputes the order status at once; undo/redo clear the selection.
- Tests: terminal unit +15, terminal.mjs +12 KDS checks (no polling, live order + chime,
  item/undo/prepare/decline, settings permission, change made elsewhere), backend
  regression for an item back to pending.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:27:11 +02:00
bonaminandClaude Opus 5.5 d5c4400fde feat(backend): KDS settings as device config, zone enforced for kitchen screens, KDS-only API (platform-v2 3.2a)
- KDS manifest: 23 typed settings (prep zone, board, waiting-time minutes and colours,
  behaviour) replacing the KDS page's localStorage settings.
- ConfigField: colour type, "after" ordering (warning < late < flash), groups for the
  manager's dialogs, ".none" text for an empty ref choice.
- routers/kds.py: a KDS device gets only its zone's orders, prints to its zone by default
  and signs waiter messages with its zone/name. New GET /api/kds/context and
  POST /api/kds/orders/{id}/retry-print so the screen never leaves its kds.* scope.
  Unused v1 /items and /items/{id}/status endpoints removed (D-21).
- PATCH /api/devices/me/config: a screen changes its own settings when the signed-in
  person holds core.devices.manage.
- Manager Devices dialogs: settings in sections, colour pickers, "All zones".
- Tests: test_kds_device.py, colour/ordered fields; terminal.mjs scope + zone checks;
  manager.mjs settings sections; stack.mjs detaches the non-LAN network before the
  restart check (one flaky 403).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:56:59 +02:00
bonaminandClaude Opus 5.5 c24cb72640 feat(terminal): pairing, sign-in per mode, device app router and live states (platform-v2 3.1c)
- Pairing screen: requests a code, shows it big, polls with the secret, new code on
  expiry, keeps the device token; "removed from the venue" notice after a revoke.
- Sign-in per device mode: PIN (name + PinPad), tap your name, password (name +
  password), none (straight into the app). Names = holders of <app>.access, refreshed
  every 30 s and on reconnect. Slim bar with screen, user and Sign out; idle sign-out
  after the device's auto_sign_out_minutes; hourly token refresh (same session).
- DeviceProvider: GET /api/devices/me (retried while unreachable), session, the live
  connection with credentials in the first frame (device.updated -> reload, app moved ->
  sign out, device.revoked -> forget, session.ended -> sign out), offline banner;
  useLiveEvent for apps. Screen choice is pure (device/flow.js, unit-tested).
- Blocked screen: app turned off / not licensed / device refused, recovers by itself.
- @xenia/access AccessProvider: autoRetryMs (retry bootstrap while unreachable).
- Tests: terminal unit tests (screen choice, live actions, idle, pairing polls), new
  tests/e2e/terminal.mjs (18 checks), manager.mjs owner flow now pairs and signs in on
  the real terminal screen; run-all runs terminal.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:29:18 +02:00
bonaminandClaude Opus 5.5 7ff3c3b48e feat(terminal): terminal app shell, pos-terminal image, LAN-only proxy port 8082 (platform-v2 3.1b)
- terminal/: new workspace app (Vite + React 19 + Router 7, Tailwind on the shared
  preset, @xenia/i18n namespace `terminal`, @xenia/api client sending X-Xenia-Device,
  @xenia/access bootstrap). Apps are lazy chunks by app_key (kds, pos_counter,
  customer_display placeholders); start screen; "unknown app" screen; dev-only
  /ui-gallery and /i18n-sample. Device + session tokens in a storage wrapper.
- Image pos-terminal (terminal/Dockerfile, context client-services/); every frontend
  Dockerfile copies terminal/package.json for npm ci.
- docker-compose(.dev).yml: service terminal; proxy publishes 8082.
- Proxy (nginx-proxy/nginx.conf == install.sh heredoc, CS-5): server :8082, LAN-only
  allow/deny, WebSocket upgrade; the terminal upstream is resolved per request so the
  proxy still starts on a stack without the terminal container.
- install.sh prints the screens address.
- Tests: terminal unit tests + lint in run-all; new tests/e2e/stack.mjs (release images
  on one compose stack: :8082 serves the app, /api + WebSocket through both hops,
  403 from a non-LAN docker network on 8082 and 8081, proxy up without terminal).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:02:20 +02:00
bonaminandClaude Opus 5.5 bda5cde92b feat(backend): live connection and per-device settings for paired screens (platform-v2 3.1a)
- WebSocket: credentials may come in the first frame ({cursor, token?, device?}).
  A device token alone connects a paired screen (login-none apps get every event, a
  sign-in app only events addressed to it); a terminal session's JWT needs its own
  device, as over HTTP. Refusals send {type: refused, data: {code}} + close 4001/4003.
- ws_bus: registry of open sockets by user, session and device. Ending a session
  closes its sockets (session.ended); revoke/reassign close the device's sockets
  (device.revoked / device.updated); edits and module on/off send device.updated.
  Events can target devices (device_ids=..., sync_events.target_device_ids, rev 0014).
  Pushes go through each socket's own loop (call_soon_threadsafe).
- Device config: DeviceApp.config = typed ConfigFields, validated on pair/edit/
  reassign (validation.device_config), effective values (defaults filled) in both
  device views and the module catalogue. First field: auto_sign_out_minutes (KDS, POS).
- Manager: DeviceConfigFields renders an app's fields in the pair and edit dialogs.
- @xenia/api createLiveClient: `credentials` and `onRefused` options.
- Tests: tests/test_live.py (11), module texts for config fields, live client,
  devices logic, manager.mjs device setting + live socket checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:31:59 +02:00
bonaminandClaude Opus 5.5 034426f870 fix: orders CSV export, Online Orders live refresh, starter flags and quick messages
Cleanup before platform-v2 phase 3 (owner-approved).
- KI-008: GET /api/reports/orders/export read order_history's dicts as ORM rows and
  always failed with 500; it also ignored business_day_id (the Today page sends it).
  Rebuilt on the dicts, header even when empty. tests/test_reports_export.py.
- KI-010: OnlineOrdersPage listened on /api/stream (never existed: no live refresh,
  a 404 every few seconds). It now refetches on the shared live connection
  (online_order_received / online_order_updated / ready); 20 s polling stays as a
  fallback. manager.mjs checks nothing asks for /api/stream.
- KI-007: the setup wizard seeds the 10 default table flags and 5 quick messages in
  the venue language (services/defaults.py), only when none exist. v1's seed never
  worked (NOT NULL columns missing). Managers edit them in Settings -> Operation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 14:08:54 +02:00
bonaminandClaude Opus 5.5 f1f20f7bba feat(backend): sign people out after N days without use (auth.idle_days, default 14)
Platform-v2 step 2.99d, owner decision 2026-11-14.
- New core setting auth.idle_days (int, default 14, 0 = never). A manager, waiter or
  paired-device session unused for that long ends with reason "idle" on its next
  request (sessions.validate) or when someone opens "Signed in now"
  (sessions.end_idle in GET /api/auth/sessions). Support keeps its own 4 h expiry.
- Manager: Settings -> Sign-in & security -> "Sign people out after" (7/14/30/60/90
  days / Never; a value set elsewhere is kept); "Signed in now" names the reason.
  Texts en/el.
- Tests: backend 284 (+ 14-day default, list drops idle ones, setting incl. 0);
  manager e2e checks the default and saving 30. The support-access check that
  failed once in ~8 runs now saves a screenshot and the page's alert text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:38:00 +02:00
bonaminandClaude Opus 5.5 cc4e76019b chore: deliberate dependency upgrades; drop legacy-peer-deps; Capacitor 8.6.2 (shell build 2)
Platform-v2 step 2.99c.
- Both apps on the same current versions: React 19.3.1, react-query 5.107.1,
  router 7.18.5, axios 1.21.1, zustand 5.1, vite 8.3.8, plugin-react 6.3; manager
  lucide-react 1.14 -> 1.73, recharts 3.8 -> 3.10.
- i18next 27.1.1 + react-i18next 18.0.1 (exact pins). Shared options moved to
  packages/i18n/src/options.js with returnEmptyString: true (27 shows the key for an
  empty text otherwise); tests/instance.test.mjs guards it, plus fallback, code
  casing and plurals.
- vite-plugin-pwa 2.0 lists Vite 8 as a peer: .npmrc (legacy-peer-deps) removed,
  `npm install` resolves without it.
- Native (CS-10): @capacitor/core/android/cli 8.6.2, @capacitor/app 8.1.2,
  @capgo/capacitor-updater 8.54.2; versionCode 2 / versionName 1.1.0 and
  MIN_SHELL_BUILD 2. capacitor-updater 8.54 refuses plain-HTTP downloads by
  default, which broke every bundle check in the stacks suite: httpsOnly: false in
  capacitor.config.json (venues have no domains; zips are sha256-checked).
- npm audit: 6 left, all in workbox-build 7.4.1 (build time).
Full run-all incl. Android passes (Android re-run after the httpsOnly fix).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:22:51 +02:00
bonaminandClaude Opus 5.5 e9b6ef57e0 chore: patch npm advisories in shipped and build code; add a manager ESLint config
Platform-v2 step 2.99b.
- npm update of the advised packages, within their ranges: what ships to browsers
  is axios 1.15.1 -> 1.21.1 and react-router(-dom) 7.14.1 -> 7.18.5 (both apps);
  build tools: vite 8.0.9 -> 8.3.8 (rolldown 1.2), postcss 8.5.33, babel 7.29.x,
  browserslist, js-yaml, zod, brace-expansion, nanoid, source-map-js... 30 -> 11
  advisories; the 11 left are build-time only (vite-plugin-pwa/workbox-build chain,
  @capacitor/cli -> xcode -> uuid) and move to 2.99c.
- manager_dashboard/eslint.config.js = the waiter's rules; `npm run lint -w
  manager-dashboard` checks the v2 code (file list in the script), in run-all.mjs.
  set-state-in-effect is a warning until phase 6 moves page loading to react-query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:35:50 +02:00
bonaminandClaude Opus 5.5 7cbd0325a4 refactor(backend): remove the v1 auth and permission leftovers no frontend uses
Platform-v2 step 2.99a. After 2.6 no frontend calls these any more:
- POST /api/auth/login needs `client` (manager/waiter/terminal); the no-`client`
  path with v1 rules and the `legacy_manager` single-session exception are gone.
- GET /api/setup/security-config (bootstrap's `login` replaced it in 2.6b).
- POST /api/recovery/use (a recovery code works in the normal login's
  password field).
- PUT /api/waiters/{id}/permission and /reset-permissions (the permission editor
  saves keys with PUT /{id}/permissions); staff create/update ignore perm_* fields.
- The v1 perm_* projection: core/access/legacy.py deleted, UserOut carries only
  `permissions` (no app reads the 13 booleans, waiter included).
e2e manager login sends client "manager"; smoke_routes too. Backend 281 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:08:01 +02:00
bonaminandClaude Opus 5.5 eb22997f8e test(e2e): owner flow end to end (platform-v2 2.6g)
manager.mjs: sign in -> KDS on from its Apps card -> pair a screen on the
Devices page (device side via the API) -> the chef is refused, then gets
kds.access + kds.bump in the permission editor -> signs in on that screen
with their PIN and reads /api/kds/orders -> listed under "Signed in now".
87 checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:04:43 +02:00
bonaminandClaude Opus 5.5 2426ffddad feat(manager): notification bell, sign-in/venue/print settings, log download (platform-v2 2.6f)
- Bell in the header: /api/platform/notifications with unread count, live via
  the new LiveProvider (one createLiveClient connection) on platform_notification
  and reconnect; mark read / all; warning+critical pop a toast.
- Settings: Sign-in card (manager/waiter/device modes, require username, one
  session per manager/waiter, username autofill) replaces the dead v1
  security.login_method card; new "Venue & language" tab (language, time zone);
  print alert threshold in Printing. Tab labels are i18n keys.
- Technical > Log files: list + download of the daily logs (owner-level).
  Backend: GET /api/system/logs, /api/system/logs/{date} (core.settings.manage),
  error system.log_not_found.
- Setup wizard asks staff language and time zone (setup/init stores them).
- @xenia/ui theme helpers (applyTheme, getStoredTheme); the manager stays light
  until phase 6 converts the older pages (owner decision 2026-11-14).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 09:01:26 +02:00
bonaminandClaude Opus 5.5 92bc1b0113 feat(manager): staff permission editor, signed-in sessions, approvals log (platform-v2 2.6e)
- Staff: the 13 perm_* tick columns become one Permissions column (count,
  "changed from role") opening an editor grouped by module, from
  /api/waiters/permission-catalog: switches labelled per key, keys you don't
  hold are disabled with the reason, reset to role defaults (names what it
  can't give), save the whole set; access.cannot_grant explained by label.
- "Signed in now" (/management/sessions): who, where (app or device), since,
  last active, your own session marked; end session; show ended + reason.
- "Manager approvals" (/management/approvals): the override audit with
  action label, asked by, approved by, device, used/not used, order link.
- Backend: sessions list adds device_name/device_app/current/expires_at;
  overrides list adds device_name/expires_at.
- Permission labels for every key in modules.json (en/el), guarded by
  test_module_texts; manager unit tests for the editor logic; e2e 66 checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:10:57 +02:00
bonaminandClaude Opus 5.5 cc00ec39c7 feat(manager): Devices page — pair by code, app, name, sign-in mode, link, change app, remove
Platform-v2 step 2.6d:
- /devices (core.devices.manage, sidebar): devices from /api/devices with
  status (online / last seen / waiting for the device / app turned off /
  removed), app, sign-in mode (own or venue default), linked device; usage per
  device app against the license limit (devices)
- pair dialog: code as typed (normalized), app (only apps that are on, "all in
  use" when the limit is reached), name, sign-in mode for apps with a choice,
  optional linked device; license.limit_reached explained with the app's limit
- edit (name, sign-in mode, link), change app (signs out whoever is on it),
  remove with confirm (the device goes back to pairing), show removed
- manager_dashboard gets node --test (tests/platform.test.mjs: module states,
  dependents, device status/usage/room/links), added to run-all
- e2e manager.mjs: 54 checks (+ wrong code, normalized code, pair, the device
  picks up its token, online, rename, change app, remove → device.revoked)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 23:22:43 +02:00
bonaminandClaude Opus 5.5 1f28016122 docs(backend): CS-13 — a new module needs its staff texts in modules.json
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:34:32 +02:00
bonaminandClaude Opus 5.5 0d0b2d78e1 feat(manager): Apps, Integrations and License pages on the module catalogue
Platform-v2 step 2.6c:
- Apps (device apps, features, always-included core) and Integrations: module
  cards from GET /api/platform/modules with state (on / off / waiting for a
  dependency / not in your license / always on), dependencies, limits and an
  Open button where the manager has a page; core.modules.manage toggles them
  (PUT /api/platform/modules/{key}), with a confirm listing the modules that
  stop too; bootstrap reloads so the sidebar follows at once
- License page: licensed / free (with the reason) / development, site id,
  validity, last contact, "check the license now" (POST /api/system/sync-license),
  every module's entitlement and limits
- i18n: new `modules` namespace (names, descriptions, limit labels, en + el)
  kept complete against the registry by local_backend/tests/test_module_texts.py
- nav: Integrations and License in the sidebar; old AppsPage removed
- e2e manager.mjs: 43 checks (+ card states, toggle from the card, dependency
  warning, integrations, license page)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:33:54 +02:00
bonaminandClaude Opus 5.5 49a412d748 feat(manager): v2 sign-in (login modes, support access, license notice) and an unlock endpoint for the lock screen
Platform-v2 step 2.6b:
- backend: POST /api/auth/unlock {pin|password} checks the CURRENT session's
  user and keeps the session (no new login/token); 5 wrong tries end it
  (auth.wrong_pin with attempts_left, then auth.session_ended); bootstrap
  gains `login` (manager_mode, autofill_username, support)
- manager LoginPage rewritten on @xenia/ui + i18n: client "manager", password
  or PIN pad per setting, remembered/only account card, support access panel
  (challenge -> code -> 4 h session, not remembered as an account), notice
  when the license runs the free tier (expired/inactive/locked/clock/unverified)
- lock screen on /api/auth/unlock with the shared PinPad
- @xenia/ui PinPad: variable length (minLength/maxLength, OK key, Enter)
- e2e manager.mjs: 33 checks (+ lockout after 5 wrong PINs, PIN login mode,
  support access with a wrong then right code)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:17:09 +02:00
bonaminandClaude Opus 5.5 df57fd1552 feat(manager): shell navigation from modules + permission keys; profile menu language
Platform-v2 step 2.6a:
- shell/nav.js: one nav definition (module + key per page) read by the sidebar,
  the page titles and a RouteGuard around the layout outlet (and /kds): a module
  that's off hides its items and its routes say "turned off"; a missing key
  hides the item and the route says "no access". Same keys as before (v1
  permission names mapped), plus the module check
- labels/breadcrumbs are keys in a new i18n namespace `manager` (en + el)
- removed the browser-only feature toggles (usePhase2Features, Settings ->
  Λειτουργίες, F-033), PermissionGuard and usePermissions
- profile menu: language, saved to the profile (PATCH /api/auth/me) and
  bootstrap reloaded
- e2e manager.mjs: module off/on, no-key user, language switch live + saved

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 21:48:08 +02:00
bonaminandClaude Opus 5.5 78c8824356 feat(api): @xenia/api + @xenia/access; the manager logs in and loads bootstrap through them
Platform-v2 step 2.5 (APPS_PLATFORM D-7, D-10, §9):
- @xenia/api: createApiClient (app passes its axios; session/device headers,
  err.xenia codes, 401/offline hooks, manager-override retry: ask PIN, grant,
  retry once with X-Xenia-Override); errorMessage; createLiveClient = the
  waiter's WebSocket logic (cursor replay, backoff, online) moved unchanged
- @xenia/access: AccessProvider (bootstrap per session token, language +
  venue formats, translated ui labels, approval dialog), useAccess/useCan/
  useModule, Can, RequireModule
- i18n: errors namespace for every backend code (en/el, test vs core/errors.py),
  override/access texts
- manager: client from createApiClient, AccessProvider in a layout route,
  /kds behind RequireModule, usePermissions from bootstrap keys; login and
  unlock no longer treat a wrong password/PIN as "session ended" (a wrong
  lock-screen PIN used to log the manager out)
- waiter: useWebSocket is a thin wrapper over createLiveClient
- tests: api/access unit tests; new e2e suite tests/e2e/manager.mjs; CS-18

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 20:38:31 +02:00
bonaminandClaude Opus 5.5 dbb8d5f0f4 feat(i18n): @xenia/i18n translations, language resolution and venue-time formatting
Platform-v2 step 2.4 (APPS_PLATFORM D-11, D-12, §7.2, §8):
- i18next 26.7.2 + react-i18next 17.1.13 (exact); en/el locale files
  (common, dev); createI18n, I18nProvider, useLanguage, setUserLanguage
  (screen first, then PATCH /api/auth/me through an app-provided save)
- resolveLanguage: user -> device -> venue -> en
- useFormat(): dates/times always in the venue zone from bootstrap (24 h,
  DST-safe, business dates never shifted), relative times, money and
  numbers per language; parseNumber accepts a comma or a dot
- scripts/check-i18n.mjs guard: keys missing in en, placeholder mismatches,
  dates formatted without the venue zone in new code (fails); missing el (warns)
- @xenia/ui components read their texts from UiLabelsProvider; useUiLabels()
  supplies the translated set
- dev-only /i18n-sample in the manager; ui.mjs e2e checks it with the browser
  in New York; unit tests in run-all; lockfile keeps both apps' versions
- new pack rule CS-17

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 19:51:11 +02:00
bonaminandClaude Opus 5.5 3580f2815c feat(ui): @xenia/ui design tokens, Tailwind preset and base components
Platform-v2 step 2.3 (APPS_PLATFORM D-15 §9):
- tokens.css: --x- prefixed colours (light/dark/system + 5 venue accent themes),
  spacing, radius, type scale, shadows, motion, z-index; variables only
- components.css: .x-* classes only, no element selectors (new rule CS-16)
- Button, IconButton, Dialog, Sheet, Toast, PinPad, InfoTip, EmptyState,
  Spinner, Field/Input/Textarea/Select, Switch (accessible: focus trap and
  restore, ARIA wiring, 44px targets)
- tailwind-preset.js (adds names only); manager uses it + styles.css, the
  waiter imports tokens.css; existing screens unchanged
- dev-only /ui-gallery in the manager; e2e suite tests/e2e/ui.mjs; unit tests
  for PIN rules and WCAG AA contrast of every token pair, both in run-all

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 19:33:58 +02:00
bonaminandClaude Opus 5.5 c7102f1c89 feat(manager): upgrade to React 19, React Router 7 and Vite 8 (same versions as the waiter)
Platform-v2 step 2.2: react/react-dom 19.2.5, react-router-dom 7.14.1, vite 8.0.9,
@vitejs/plugin-react 6.0.1, and react-is 19.2.5 (recharts' peer dependency, no
longer installed implicitly). React and the router are now shared by both apps
at the workspace root; the waiter resolves exactly the versions it had.
- .npmrc legacy-peer-deps for the whole workspace (vite-plugin-pwa 1.2 does not
  list Vite 8 yet; the waiter always installed this way)
- manager Vite dev/preview proxies /api, /api/ws and /static to :8000 like the waiter
No code changes were needed: every route renders and the main flows work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 18:27:10 +02:00
bonaminandClaude Opus 5.5 17bef9915f chore(waiter): pin the Capacitor/Capgo native plugins to exact versions
A native plugin upgrade needs a versionCode + MIN_SHELL_BUILD bump (CS-10), so it
must never arrive as a side effect of npm install/update (it broke UI-bundle
updates during platform-v2 step 2.1). Versions unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 18:15:19 +02:00
bonaminandClaude Opus 5.5 905c2955b0 chore(build): frontends become one npm workspace; images build from client-services/
Platform-v2 step 2.1 (APPS_PLATFORM D-15):
- root package.json with workspaces (packages/*, waiter_pwa, manager_dashboard)
  and empty @xenia/{ui,i18n,api,access} skeletons (filled in 2.3-2.5)
- one root package-lock.json generated from the two old app locks, so every
  dependency keeps its exact version (a fresh resolve moved the Capacitor and
  Capgo native plugins and broke UI-bundle updates); apps keep nested trees
- waiter/manager Dockerfiles build with context client-services/ (npm ci per
  workspace), root .dockerignore replaces the per-app ones; manager on node 22
- Vite dedupes react/react-dom so source-imported packages share the app's React
- waiter eslint ignores build outputs and the Android project

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:47:29 +02:00
bonaminandClaude Opus 5.5 3699935347 fix(install): e2e compose stacks replace a data/pos.db left by a v1-era run
tests/e2e/lib/proc.mjs: composeStack() reuses out/<project>/data between runs; a database from before platform-v2 has no alembic_version, so the v2 backend refused it and the stack came up unhealthy (android.mjs stacks failed at docker compose up). The v1 check used for the seed template is now a shared isV1Database() and also applied to each stack's pos.db. android.mjs stacks: 21/21 after the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 13:09:42 +02:00
bonamin 6d42be95f8 feat(backend): a product can be listed in several categories, with one primary category
Platform v2 step 1.13 (APPS_PLATFORM D-23).
- product_categories(product_id, category_id, sort_order); products.category_id becomes
  products.primary_category_id (revision 0013 moves the data: one listing per product at its
  old position). services/catalog.py keeps the rule "the primary is one of its categories"
  and fixes up products when a category is deleted.
- Products API: category_ids + primary_category_id in and out, plus categories
  [{category_id, sort_order}]; GET /api/products/?category_id= lists a category's products in
  that category's order; PUT /reorder with category_id orders within a category. category_id
  stays as dev scaffolding (section 3.3): output = primary, input = "move the primary".
- Primary category: ticket grouping and prep-zone category order, the order-item category
  snapshot (1.12), report filters for waste-only rows and /meta/products.
- Every listing: price modifier / deal / min-quantity category targets, deal free choices,
  the QR menu snapshot (product in each category it's listed in; images pushed once).
- Catalogue export v2: each category lists all its products with "primary" and
  "category_sort_order"; import restores listings and order. v1 files are refused (D-21).
- New errors catalog.unknown_category, catalog.primary_not_listed.
2026-11-13 12:39:02 +02:00
bonaminandClaude Opus 5.5 3c5751025c refactor(backend): drop the legacy products.printer_zone_id and its print fallbacks
Routing has been by prep zone only since v1, which nulled this column on every start, so the four fallbacks in printer_service.py never ran. Revision 0012 drops the column (its unnamed FK goes with the batch rebuild). The unused legacy GET /api/kds/items keeps its single 'no zone' group. Product create/update/export/import no longer mention it. Scheduled in plan step 1.0 for the catalogue rework (1.13).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:28:13 +02:00
bonaminandClaude Opus 5.5 82c6ca4e0a feat(backend): order items keep the product and category they were sold under; reports use them
Platform v2 step 1.12 (APPS_PLATFORM D-18, CS-4).
- order_items.product_name (NOT NULL), category_id, category_name (revision 0011, back-filled from
  the current catalogue). A before_flush hook in models/order.py fills them for every new item,
  whoever creates it; an item created with product_name set is left alone (importer).
- Reports read the snapshots: order history, shift/printer/prep-zone breakdowns, cancellations,
  product and category performance (grouped by the category as sold, newest name in the period
  wins), and the printed product/category reports. Catalogue listings (unsold products in 'full'
  mode, meta endpoints, waste-only rows) keep live names on purpose.
- Order detail and OrderItemOut expose product_name/category_id/category_name next to the live
  .

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:33:55 +02:00
bonaminandClaude Opus 5.5 834fe6e250 feat(backend): alert managers while a ticket keeps failing to print (setting print.alert_after_failures, default 2)
Owner request after step 1.11: hear about a failing ticket during service, not only when it's abandoned.
- New notification print.failing (critical, all managers) when a print job's failed attempts reach
  print.alert_after_failures (ordering setting, default 2, 0 = never). Once per job; jobs on the same
  printer within an hour fold into one notification. print.failed_final (abandoned) stays.
- Both the first attempt (route-and-print, sent after its commit) and the retry sweep report it.
- Texts in en/el; tests for 1/2/3/0 and folding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:28:12 +02:00
bonaminandClaude Opus 5.5 5a21f67b42 feat(backend): platform notifications service with audiences, dedupe, read state and first producers
Platform v2 step 1.11 (APPS_PLATFORM section 10).
- notifications + notification_reads (revision 0010). Text = i18n key notification.<key> + params,
  rendered in the reader's language (en, el added).
- core/notifications.py: notify(key, severity, audience, params, dedupe_key, ttl/expires_at, fold)
  never raises; audience all_managers | perm:<key> | user:<id>; a live duplicate only bumps
  count/last_at (no unread reset, no event). New ones emit WS platform_notification {id} to the
  audience's users (current apps ignore it; phase 2 manager shows it).
- API (core, /api/platform/notifications; /api/notifications is chat's): list with unread count,
  POST /{id}/read, POST /read-all.
- Producers: license.limit_reached (device pairing/reassign/over-limit device, per module/limit/day,
  owners), license.expiring (14/7/3/1 days, from apply_license, owners), support.access_used (each
  use, core.settings.manage), print.failed_final (abandoned retry job, per printer/hour, managers).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:13:37 +02:00
bonaminandClaude Opus 5.5 94a68b1c06 perf(backend): tests skip the event bus's sync_events write (5 s lock wait per broadcast)
services.ws_bus persists every broadcast through its own connection, which waited on the test transaction until SQLite's 5 s busy timeout and then failed quietly. An autouse fixture stubs _persist_event; no test uses the replay buffer. Full suite 61 s -> 17 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:13:37 +02:00
bonaminandClaude Opus 5.5 3a522e457d feat(backend): support access by offline challenge codes replaces the master account
Platform v2 step 1.10 (APPS_PLATFORM D-16, section 6.5).
- POST /api/auth/support/challenge (public): an 8-character challenge, stored 15 min
  (support_challenges, revision 0009; at most 5 open). POST /api/auth/support/verify
  {challenge, code}: code = base32(HMAC(SUPPORT_SECRET, site_id + challenge))[:10];
  single use, 5 wrong codes burn the challenge. Opens a 4 h support session
  (client=support, synthetic superadmin) with a hard end: sessions.expires_at.
- core/support_codes.py (stdlib only) is the derivation; tools/support_code.py
  (--init, --site-secret <SITE_ID>, <SITE_ID> <CHALLENGE>) uses it on the builder's
  machine with the master key in %USERPROFILE%/.xenia/support_master_key.txt.
- MASTER_USERNAME/MASTER_PASSWORD removed (config, login, docker-compose.yml,
  .env.example); SUPPORT_SECRET added; install.sh asks for it.
- e2e: backends get SUPPORT_SECRET from a test master key and log in with challenge
  codes (lib/support.mjs, license_e2e.py); install.mjs expects the new prompt.
- Pack rule CS-15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 10:52:16 +02:00
bonaminandClaude Opus 5.5 650fee7873 feat(backend): manager override with one-time PIN approval for cancel, price change, over-limit discount
Platform v2 step 1.9 (APPS_PLATFORM D-10).
- Perm(..., overridable=True). check() answers access.override_possible (not
  access.denied) for such keys, and consumes an X-Xenia-Override token for them.
- POST /api/access/override {key, username, pin}: the approver must hold the key
  (module effective); returns a token valid 60 s, once, for that key and the
  requesting session only (sha256 stored). Wrong PINs throttled per session.
  GET /api/access/overrides: audit list (core.staff.manage).
- access_overrides table (revision 0008): who asked, session, who approved, device,
  key, created/expires/used, target. The revision also grants core.devices.manage and
  the new pricing.discounts.over_limit to existing owners/store managers.
- Overridable: ordering.orders.cancel (the three cancel endpoints; the order audit log
  notes "override #n approved by user m"), ordering.prices.modify (price adjust), and
  new pricing.discounts.over_limit (waiter discounts beyond their limits; the reason
  goes in params). The venue switch discounts.enabled is never overridable.
- /orders/cancel-permissions adds override_possible; permission catalogues expose
  `overridable`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:57:37 +02:00
bonaminandClaude Opus 5.5 c699542565 fix(backend): waiter discounts crashed after order_discounts.price_before/after were dropped
Revision 0001_v2_baseline dropped order_discounts.price_before/price_after as unused,
but POST /api/orders/{id}/items/discount still passed them to OrderDiscount, so every
waiter discount failed with a 500 on platform-v2. Nothing reads them from
order_discounts: the before/after prices are recorded in price_event_log (CS-4).
Found while testing step 1.9 (manager override of discount limits).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:53:07 +02:00
bonaminandClaude Opus 5.5 91da3aeb27 feat(backend): paired devices with device tokens, scope, limits and terminal login
Platform v2 step 1.8 (APPS_PLATFORM D-8, section 6.3).
- devices + device_pair_requests tables (Alembic 0007_devices); sessions.device_id
  becomes a FK. Device tokens are stored as sha256 only; the plain token is generated
  when the device picks it up, once.
- /api/devices: pair-request (public, rate-limited, LAN-only in the proxy) + polling
  with a per-request secret; manager approve/list/rename/config/login mode/link/
  reassign/revoke (key core.devices.manage); the device's own /me and /me/users.
- Approving or reassigning checks the app's licence and its `devices` limit
  (license.limit_reached); after a downgrade the newest devices beyond the limit are
  refused, the oldest keep working.
- X-Xenia-Device: core/access/context.py loads the device (device.not_paired /
  device.revoked), tags logs with device=, throttles last_seen_at. check() and
  module_required() apply the app's scope (device.out_of_scope); require_device(app).
- POST /api/auth/login {client: "terminal"} uses the device's login mode (device ->
  auth.default_login_mode -> app's first mode); tap/none only here. The session is
  bound to the device (device.required without its header) and replaces the
  device's previous user. Revoke/reassign end the device's sessions.
- Registry: a device app with user logins must declare '<app>.access'.
- Proxy: location /api/devices/pair-request LAN-only on the :443 servers (both copies).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:44:40 +02:00
bonaminandClaude Opus 5.5 1d7a521e05 chore(backend): smoke_routes tool - GET every endpoint per role on a demo DB
The check used after each platform-v2 step (until now a scratch script): calls every parameterless GET endpoint as the demo manager and demo waiter, in dev mode or with licensing enforced (--free), and lists 5xx responses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:55:10 +02:00
bonaminandClaude Opus 5.5 e128cc37ec feat(backend): heartbeat v2 sends the module catalogue; license e2e on v2
Platform v2 step 1.7, site side (APPS_PLATFORM D-20, D-21; contract C-1 v2).
- cloud_sync heartbeat body is {version, local_ip, module_catalog}; the
  catalogue (key, kind, name, depends, limits) comes from the manifests and
  drives the sysadmin module editor
- license_e2e.py runs against the v2 cloud: free-tier checks use an ordering
  endpoint (the catalogue stays available), new section 8 edits the site's
  modules in the cloud and checks kds becomes module.not_licensed and
  reports.history_days = 30 after the next heartbeat (25/25 pass)
- e2e seed templates made by v1 code (no alembic_version) are detected and
  reseeded automatically (license_e2e.py and lib/proc.mjs)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:28:20 +02:00
bonaminandClaude Opus 5.5 9f1e12156e feat(backend): DB sessions, login modes, single-session rules
Platform v2 step 1.6 (APPS_PLATFORM D-8, D-9, §6.2, §6.4).
- sessions table (revision 0006); every JWT carries `sid` and is accepted
  only while its session is active (validated per request, 10 s cache that
  is dropped the moment a session ends); the in-memory blacklist is gone, so
  logout and "end session" survive restarts
- one login path, POST /api/auth/login {client, username?, user_id?, pin?,
  password?}: manager mode password|pin (username-only "none" removed, D-8),
  waiter mode pin|password|tap (tap answers auth.mode_needs_device until
  paired devices exist), optional "waiter must type username", and the app's
  access key (core.dashboard.access / waiter_app.access)
- auth.single_session_manager / _waiter: off | refuse_new | end_old
- /login without `client` = the current manager UI with v1 rules (pin or
  password; refuse_new treated as end_old because its lock screen re-logs-in);
  /login-by-id is a deprecated wrapper for the current waiter app;
  /login-no-auth removed
- GET /api/auth/sessions, POST /api/auth/sessions/{id}/end (core.staff.manage);
  blocking a user ends their sessions; refresh keeps the session; logout
  takes the bearer header (or ?token= as before)
- settings API validates enum/bool/int values from the manifests;
  security.login_method migrated to auth.manager_login_mode
- tests: modes, single-session rules, logout, refresh, forged token without
  session, manager session list/end

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:13:00 +02:00
bonaminandClaude Opus 5.5 3ede13e04a refactor(backend): platform API uses real permission keys
Bootstrap and /api/platform/modules now return the keys the user holds (user_permissions) instead of the role template, and enabling/disabling a module needs core.modules.manage instead of core.settings.manage (both were step 1.3 placeholders until keys existed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:51:41 +02:00
bonaminandClaude Opus 5.5 b7fda58af9 feat(backend): permission keys replace the 13 perm_* columns
Platform v2 step 1.5 (APPS_PLATFORM D-7, D-17, §3, §6.1).
- user_permissions(user_id, key); revision 0005 copies existing v1 flags into
  keys (frozen mapping) and drops the perm_* columns; can_cancel_orders gone
- core/access: check() = module effective + key held (superadmin implicit,
  override keys wired for 1.9); holds()/can(); markers require/require_any/
  public/require_device; role templates from manifests; queries.holders_filter
  replaces User.perm_x == True; legacy.py projects/accepts the v1 booleans
  for the current manager/waiter UIs only (§3.3, temporary)
- routers.deps: require_manager/... are now aliases of require("<key>");
  history endpoints use history.view; superadmin-only = core.system.admin;
  get_current_user carries the "signed_in" marker
- every inline perm_* read in routers/services converted to holds()
- staff API: permission catalogue by module with role templates, get/set a
  user's keys, reset to role template; legacy flag toggles still work; a
  non-superadmin can only grant keys they hold (access.cannot_grant)
- setup wizard creates the first account as owner (v1: store_manager, who
  couldn't change settings); demo/seed manager is owner
- roles.py keeps only the role list and labels
- guards: every route has an access marker (19 open routes marked public()
  on purpose; /waiters/roles now needs sign-in), no perm_* attribute reads
- tests: check matrix, templates, projection, staff permission API, grant
  guard, 0005 data copy; pack rule CS-14

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:51:06 +02:00
bonaminandClaude Opus 5.5 0d43e6a111 feat(backend): license entitlements, enforced limits, free tier
Platform v2 step 1.4 (APPS_PLATFORM D-3..D-6, D-21, §5).
- core/modules/entitlements.py: compute() turns the evaluated license into
  per-module grants: the v2 token's `modules` map (own `exp` with the 5-day
  grace, never cut mid-service) + the free tier; no/invalid token, expired
  after grace, inactive, locked or clock tampering -> free tier only; core
  always. limit(module, name) with token value -> manifest licensed_default ->
  free value; None = unlimited. LICENSE_MODE=off (dev/test only) = everything
- module gating says why: module.not_licensed (402, the first unlicensed
  module in the dependency chain) before module.disabled (403)
- services/license.py accepts only v2 tokens with a modules map; the v1
  "legacy unsigned 72h" path is gone
- apply_license() always installs entitlements (startup before workers,
  every heartbeat, workday close); workers follow license changes
- the global license middleware is deleted (no more whole-API 402/423);
  license_state moved to services/license_state.py
- history_days enforced in every report/history endpoint: lower date bounds
  clamped (also when no "from" is given), and business days older than the
  limit refused by id (license.history_limited); data is never deleted
- bootstrap/modules API show license mode, entitlement source and limit values
- LICENSE_MODE=off in docker-compose.dev.yml and the e2e launchers; sites
  default to enforced
- tests: entitlement rules, limits, the three done-when checks, signed-token
  apply_license path; license tests moved to v2 tokens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:32:57 +02:00
bonaminandClaude Opus 5.5 231a97c186 feat(backend): module registry, manifests, enable/disable without restart
Platform v2 step 1.3 (APPS_PLATFORM §4, §5.3, D-4, D-19).
- core/modules: Module/Perm/Limit/SettingDef/DeviceApp/Mount model; registry
  that discovers modules/<key>/manifest.py and validates it (keys, kinds,
  dependencies and cycles, permission prefixes and roles, unique settings,
  each router claimed once and importable, device_app only on apps, workers);
  free_tier.py (D-5 constant, used from 1.4)
- 25 manifests (the §4.2 map) with permission keys + default roles derived
  from today's perm_* meaning, limits, device apps and the 55 settings
- main.py mounts every router from the manifests; non-core routers carry
  Depends(module_required(key)) -> 403 module.disabled while off
- site_modules table (revision 0004), cached enablement; disabling a module
  also turns off modules that depend on it; core can't be disabled
- worker supervisor: connect_menu / connect_orders / connect_remote are now
  separate workers (v1's single _connect_loop split), started and stopped as
  their modules turn on and off; crashes are logged and restarted
- GET /api/platform/bootstrap (venue name/tz/language/currency, effective
  modules, user, language, role-template permission keys), GET /modules,
  PUT /modules/{key}
- settings API derives its key list and defaults from the manifests
- reports router split: history endpoints on history_router (`history`
  module, free tier later) under the same /api/reports prefix
- tests: registry validation, mount coverage, toggle round-trip, dependency
  propagation, bootstrap/catalogue shape, supervisor; pack rule CS-13

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:46:52 +02:00
bonaminandClaude Opus 5.5 968b6c78fb feat(backend): error codes, backend i18n (en/el) and language fields
Platform v2 step 1.2 (APPS_PLATFORM D-12, §3.2, §8).
- core/errors.py: XeniaError + CODES registry; handlers give every error the
  {"error": {code, params, message}, "detail"} shape: XeniaError, wrapped
  HTTPException (http.<status>, detail untouched), validation.invalid (FastAPI
  detail list kept), and internal.error 500 with the request id (body, header
  and log line)
- orders: the 18 "Order not found" raises -> XeniaError("order.not_found")
- core/i18n: t(key, lang, **params) with en/el JSON (en fallback), venue/zone/
  user language resolution, normalize_language; 56 print keys
- printer_service: every printed label goes through keys. Kitchen,
  cancellation and service-item tickets print in the prep zone's language
  (-> venue.language); reports/receipts/synopsis in venue.language. Greek
  output is unchanged. Print retries now pass the job's zone (language and
  item grouping were lost on retries)
- users.language, prep_zones.language (revision 0003), setting venue.language
  (default en); editable via PATCH /auth/me, staff update, prep zones API;
  "" = inherit
- tests: error shapes, key/placeholder parity, fallback, kitchen ticket per
  zone/venue language, language APIs; pack rule CS-12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:29:31 +02:00
bonaminandClaude Opus 5.5 ab1e61a10f feat(backend): UTC time model - venue zone, business date, aware-only datetimes
Platform v2 step 1.1 (APPS_PLATFORM D-11, §7, D-24).
- core/timeutil.py: utcnow, venue_tz (venue.timezone, cached, invalidated on
  change - no restart), to_venue/venue_date/venue_strftime, parse_api_datetime
  (offset -> UTC; naive = venue-local; date = venue midnight), business_date_of
  /business_date_window (rollover hour, default 06:00), LocalClock + is_within,
  UTCDateTime column type (naive writes raise, reads are aware UTC), iso_z
- every model column is UTCDateTime; Pydantic UTCDatetime emits "...Z"
- business_days.business_date set at open; revision 0002 adds it (backfilled)
  and makes sync_events.created_at a UTCDateTime (AUTOINCREMENT restated)
- tz.py deleted; system.timezone setting replaced by venue.timezone (validated)
  + business_day.rollover_hour; manager timezone picker writes venue.timezone
- fixes: price-group schedules/time_range used the container's zone (happy
  hour bug); traffic report bucketed by UTC hour; reports' "date" meant the UTC
  calendar day, now the business date; reservations stored venue-local naive
  times (no-show check 2-3 h off) and listed by func.date; schedule week used
  UTC midnights; fiscal file names used container-local time
- seed.py/demo_seed.py create store_manager with role permissions (regression
  from step 1.0: v1's startup ALTER list used to rename/grant role 'manager')
- tzdata dependency; guard tests/guards/test_no_naive_time.py (AST scan);
  tests/test_timeutil.py covers the §7.3 DST cases and the API checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:12:35 +02:00
bonaminandClaude Opus 5.5 d3d328804e refactor(backend): Alembic owns the local schema; v1 ALTER list deleted
Platform v2 step 1.0 (APPS_PLATFORM D-13, D-17).
- migrations/ with env.py (render_as_batch, models/all.py metadata, no
  fileConfig) and baseline 0001_v2_baseline autogenerated from the models and
  reviewed; it also seeds the pos_settings rows a fresh v1 install got
- core/schema.py::upgrade_to_head() is the only way the schema is built:
  app startup, seed.py, demo_seed.py, wipe_database.py and the tests. It
  refuses v1 databases (tables without alembic_version) with a clear error
- main.py: _run_migrations() and create_all removed (723 lines)
- sync_events became a model (was raw DDL); price_event_log order indexes
  declared on the model; unused order_discounts.price_before/after dropped
- tests/guards: no-drift + idempotent upgrade + install defaults + v1 refusal
  + no create_all; placeholders for the time (1.1) and access (1.5) guards
- CS-1 rewritten for Alembic on this branch

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:54:15 +02:00
bonaminandClaude Opus 5.5 980127379b chore(backend): DB-backed pytest harness (temp SQLite, real app, per-test rollback)
Platform v2 step 0.5. conftest.py now points DATABASE_URL/LOG_DIR/TLS_DIR at
a temp folder before anything imports config, builds the schema once per
session, and gives each test a connection-level transaction that is rolled
back (app commits become SAVEPOINT releases). Fixtures: db, client (TestClient
with get_db overridden, license open, no lifespan), make_user, login. Tests
using them are auto-marked `db`, so -m "not db" keeps the quick set.
test_harness.py proves login -> /api/auth/me and the rollback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:40:53 +02:00
bonaminandClaude Opus 5.5 9fa728c039 feat(backend): daily request-tagged log files + print job lifecycle logging
Platform v2 step 0.4 (APPS_PLATFORM §10). New core/logging.py:
- root logger -> stderr + <db dir>/logs/xenia-YYYY-MM-DD.log (UTC date,
  /app/data/logs in Docker, $LOG_DIR overrides); files older than the
  system.log_retention_days setting (default 30) are pruned
- line format: UTC ISO time, level, logger, [req= user= device=], message
- RequestContextMiddleware (pure ASGI): request id per request, X-Request-ID
  response header, one http line per request (DEBUG for plain reads)
- auth tags the user via set_log_context; uvicorn loggers routed through ours
Print jobs now log created / attempt / success / failed / abandoned with the
job id, so a missing ticket can be traced. Removed cloud_sync's basicConfig.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:31:38 +02:00
bonaminandClaude Opus 5.5 e560d93cd5 chore(backend): v1 timestamp audit tool for the platform-v2 history import
Classifies every datetime column of a v1 pos.db as UTC or venue-local by
comparing it with server-written events (orders.opened_at, audit-log
PAYMENT/ORDER_CLOSED rows, business days). Read-only. Used by the importer
(platform-v2 plan step 7.1); results are recorded in plan step 0.3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:37:23 +02:00
621 changed files with 53971 additions and 16017 deletions
+22
View File
@@ -0,0 +1,22 @@
# Build context for the frontend images is client-services/ (APPS_PLATFORM D-15).
# Only the workspace root, packages/ and the app folders are needed.
.git
.env
*.env
**/node_modules
**/dist
**/dist-native
**/dev-dist
data
certs
docs
tests
tools
local_backend
nginx-proxy
install.sh
logo.png
waiter_pwa/android
waiter_pwa/releases
waiter_pwa/tests
terminal/tests
+4 -3
View File
@@ -15,9 +15,10 @@ LICENSE_GRACE_HOURS=24
# the router's DHCP.
HOST_IP=
# Break-glass support account (leave blank to disable)
MASTER_USERNAME=
MASTER_PASSWORD=
# Support access (challenge codes, works offline). The builder makes this value with
# python tools/support_code.py --site-secret <SITE_ID>
# Blank = no support access on this site.
SUPPORT_SECRET=
# Volumes — absolute paths on the client machine
DATA_PATH=/opt/xenia/data
+14 -2
View File
@@ -2,6 +2,8 @@ services:
backend:
build: ./local_backend
image: ${REGISTRY}/pos-backend:${VERSION:-latest}
environment:
- LICENSE_MODE=off # dev machine: every module, no limits (never on a site)
ports:
- "8000:8000"
volumes:
@@ -9,7 +11,8 @@ services:
waiter_pwa:
build:
context: ./waiter_pwa
context: . # npm workspace root (packages/ are shared)
dockerfile: waiter_pwa/Dockerfile
args:
APP_VERSION: ${VERSION:-dev}
image: ${REGISTRY}/pos-waiter:${VERSION:-latest}
@@ -18,7 +21,16 @@ services:
manager_dashboard:
build:
context: ./manager_dashboard
context: .
dockerfile: manager_dashboard/Dockerfile
image: ${REGISTRY}/pos-manager:${VERSION:-latest}
ports:
- "5174:80"
terminal:
build:
context: .
dockerfile: terminal/Dockerfile
image: ${REGISTRY}/pos-terminal:${VERSION:-latest}
ports:
- "5175:80"
+12 -2
View File
@@ -6,6 +6,7 @@ services:
- SITE_ID=${SITE_ID}
- SITE_KEY=${SITE_KEY}
- CLOUD_URL=${CLOUD_URL}
- LICENSE_MODE=${LICENSE_MODE:-enforced} # 'off' only for dev/test stacks (all modules, no limits)
- SECRET_KEY=${SECRET_KEY}
- LICENSE_GRACE_HOURS=${LICENSE_GRACE_HOURS:-24}
- DATABASE_URL=sqlite:////app/data/pos.db
@@ -13,8 +14,7 @@ services:
- HOST_IP=${HOST_IP:-}
- TLS_PORT=${TLS_PORT:-8443} # published port of the proxy's TLS entry (advertised to the app)
- HTTP_PORT=${HTTP_PORT:-80} # published plain-HTTP LAN port (app downloads UI bundles from it)
- MASTER_USERNAME=${MASTER_USERNAME:-}
- MASTER_PASSWORD=${MASTER_PASSWORD:-}
- SUPPORT_SECRET=${SUPPORT_SECRET:-}
volumes:
- ${DATA_PATH}:/app/data
- ${LOGO_PATH}:/app/logo.png:ro
@@ -53,6 +53,13 @@ services:
depends_on:
- backend
# Paired screens: KDS, counter POS, customer display (platform v2, phase 3)
terminal:
image: ${REGISTRY}/pos-terminal:${VERSION:-latest}
restart: unless-stopped
depends_on:
- backend
proxy:
image: nginx:alpine
ports:
@@ -60,6 +67,7 @@ services:
- "443:443"
- "4443:4443"
- "8081:8081" # manager over plain HTTP (LAN only)
- "8082:8082" # terminal (paired screens) over plain HTTP (LAN only)
- "8443:8443" # native app over TLS with a pinned key (LAN only)
volumes:
- ./nginx-proxy/nginx.conf:/etc/nginx/conf.d/default.conf:ro
@@ -72,6 +80,8 @@ services:
condition: service_started
manager_dashboard:
condition: service_started
terminal:
condition: service_started
restart: unless-stopped
volumes:
+78 -14
View File
@@ -15,7 +15,8 @@ This folder is its **own git repo**, nested inside the `xenia-pos` parent repo.
| `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` |
| `proxy` | nginx:alpine | — | 80, 443, 4443, 8081, 8443. See the header of `nginx-proxy/nginx.conf` for the full routing map. Waits for the backend to be healthy | stock |
| `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.
@@ -38,34 +39,57 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `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/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). 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` |
| `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|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more |
| `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` | axios instance: auth header, 401 → logout, network error → offline |
| `waiter_pwa/src/context/SSEContext.jsx` | Real-time lifecycle, event → store/cache updates, visibility refresh |
| `waiter_pwa/src/db/posdb`, `src/services/offlineOrders` | Offline cache and queued orders |
| `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) |
| `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` |
| `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) |
| `packages/access/` | `<AccessProvider>` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, `<Can>`, `<RequireModule>` (CS-18) |
| `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 go through `_run_migrations()`.**
A new table: `create_all` handles it. A new column on an existing table: append an `ALTER TABLE <t> ADD COLUMN ...` to the `migrations` list in `local_backend/main.py`, with a SQLite-safe default for `NOT NULL`.
Add the column to the SQLAlchemy model **and** the Pydantic schema in the same commit. Never drop or rename columns.
**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/SSEContext.jsx` (and in the manager, if relevant), or state explicitly that it's ignored.
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)
- never lose an order that was entered (queue it): queue it **by id** (`@xenia/api` `wireLine`, 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.
@@ -73,10 +97,11 @@ Prices, costs and discounts are copied onto order items and logs when the action
**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) must keep their LAN-only `allow`/`deny` block.
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 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.**
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`:
@@ -91,17 +116,21 @@ Staff UIs are used by Greek staff and must render Greek correctly, including on
## Common commands
```powershell
# 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
docker push registry.bonamin.net/pos-backend:<ver> # + pos-waiter, pos-manager, pos-terminal
```
## Native Android app (waiter_pwa)
@@ -120,6 +149,7 @@ npm run apk:release # releases/xenia-waiter-<ver>.apk, signed, AND copied to p
- **Native specifics:**
- `androidScheme: http` (origin `http://localhost`)
- 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/`)
- back button handled in `src/native/backButton.js`
- first run shows only the pairing screen
@@ -130,17 +160,51 @@ npm run apk:release # releases/xenia-waiter-<ver>.apk, signed, AND copied to p
**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](../tests/e2e/README.md)**.
- **Unit (seconds):** `python -m pytest tests -q` in `local_backend/`, and `npm test` in `waiter_pwa/`.
- **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.
- **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, a compose stack of the release images (`stack.mjs`), 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-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 `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).
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 `ConfigField`s 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). 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`. **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-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 with `device_ids=[…]` (the customer display's `display.state` goes only to the displays linked to that POS) and what is meant for a role with `user_ids=[…]` plus the screens that need it (`call_incoming`: users with `caller_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 has `customer_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 (`ConfigField`s) 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 a `ref` config 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 build` passes for any frontend you touched
+104
View File
@@ -71,6 +71,8 @@ if [ ! -f "$SCRIPT_DIR/.env" ]; then
DETECTED_IP=$(detect_host_ip)
read -rp " Enter this machine's LAN IP [${DETECTED_IP}]: " INPUT_HOST_IP
INPUT_HOST_IP=${INPUT_HOST_IP:-$DETECTED_IP}
echo " Support access: the builder runs python tools/support_code.py --site-secret <SITE_ID>"
read -rp " Enter SUPPORT_SECRET (blank = no support access): " INPUT_SUPPORT_SECRET
if [ -z "$INPUT_SECRET_KEY" ]; then
INPUT_SECRET_KEY=$(openssl rand -hex 32)
@@ -81,6 +83,7 @@ if [ ! -f "$SCRIPT_DIR/.env" ]; then
sed -i "s/^SITE_KEY=.*/SITE_KEY=${INPUT_SITE_KEY}/" "$SCRIPT_DIR/.env"
sed -i "s/^SECRET_KEY=.*/SECRET_KEY=${INPUT_SECRET_KEY}/" "$SCRIPT_DIR/.env"
sed -i "s/^HOST_IP=.*/HOST_IP=${INPUT_HOST_IP}/" "$SCRIPT_DIR/.env"
sed -i "s/^SUPPORT_SECRET=.*/SUPPORT_SECRET=${INPUT_SUPPORT_SECRET}/" "$SCRIPT_DIR/.env"
echo ""
echo " .env written. Review it at: $SCRIPT_DIR/.env"
@@ -106,9 +109,11 @@ cat > "$SCRIPT_DIR/nginx-proxy/nginx.conf" << 'EOF'
# :80 anything else (bare LAN IP) → waiter app over plain HTTP, LAN only
# /manager → redirect to :8081
# :8081 → manager dashboard over plain HTTP, LAN only
# :8082 → terminal (paired screens: KDS, POS, customer display), LAN only
# :443 waiter.* / manager.* / bare IP → https (needs certs/cert.pem + key.pem)
# :4443 → manager over https
# :8443 → native app over TLS (backend-managed key, pinned), LAN only
# /api/devices/pair-request on :443 → LAN only (device pairing, D-8)
#
# Every proxied location forwards WebSocket upgrades (/api/ws/connect) and
# disables buffering (SSE), otherwise live events never reach phones / KDS.
@@ -118,6 +123,10 @@ map $http_upgrade $connection_upgrade {
'' close;
}
# Uploads: the media library takes pictures up to 20 MB and videos up to 200 MB
# (local_backend/services/media.py checks the real limits; nginx's default is 1 MB).
client_max_body_size 250m;
# ── Plain HTTP ────────────────────────────────────────────────────────────────
server {
@@ -192,6 +201,43 @@ server {
}
}
server {
listen 8082 default_server;
server_name _;
# Terminal app for paired screens (KDS, counter POS, customer display; plan step 3.1b).
# LAN only: plain HTTP must never be reachable from the internet, even if the
# client forwards ports on their router. Relies on Docker preserving the real
# client IP (default iptables port publishing on Linux).
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 127.0.0.0/8;
allow fc00::/7;
allow fe80::/10;
allow ::1;
deny all;
# Resolved per request (Docker DNS), so the proxy still starts on a stack that has no
# terminal container yet (an older docker-compose.yml): only :8082 fails then (502).
resolver 127.0.0.11 valid=30s ipv6=off;
set $terminal_upstream http://terminal:80;
location / {
proxy_pass $terminal_upstream;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_buffering off;
}
}
# ── HTTPS ─────────────────────────────────────────────────────────────────────
server {
@@ -203,6 +249,25 @@ server {
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
# So is the phone system's call webhook (caller ID, plan step 3.5): only the venue's UCM calls it.
location ~ ^/api/(devices/pair-request|phone/call-event) {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 127.0.0.0/8;
allow fc00::/7;
allow fe80::/10;
allow ::1;
deny all;
proxy_pass http://backend:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
proxy_pass http://waiter_pwa:80;
proxy_http_version 1.1;
@@ -227,6 +292,25 @@ server {
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
# So is the phone system's call webhook (caller ID, plan step 3.5): only the venue's UCM calls it.
location ~ ^/api/(devices/pair-request|phone/call-event) {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 127.0.0.0/8;
allow fc00::/7;
allow fe80::/10;
allow ::1;
deny all;
proxy_pass http://backend:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
proxy_pass http://manager_dashboard:80;
proxy_http_version 1.1;
@@ -251,6 +335,25 @@ server {
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
# So is the phone system's call webhook (caller ID, plan step 3.5): only the venue's UCM calls it.
location ~ ^/api/(devices/pair-request|phone/call-event) {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
allow 127.0.0.0/8;
allow fc00::/7;
allow fe80::/10;
allow ::1;
deny all;
proxy_pass http://backend:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /api/ {
proxy_pass http://backend:8000;
proxy_http_version 1.1;
@@ -387,6 +490,7 @@ echo ""
echo "Done! Services running. From any phone or PC on this network:"
echo " Waiter app: http://${HOST_IP_NOW}"
echo " Manager app: http://${HOST_IP_NOW}/manager (→ port 8081)"
echo " Screens: http://${HOST_IP_NOW}:8082 (kitchen display, counter POS; pair them under Devices)"
echo ""
echo "Tip: reserve ${HOST_IP_NOW} for this machine in the router's DHCP settings"
echo " so the address never changes."
+11
View File
@@ -0,0 +1,11 @@
# Alembic CLI config for local_backend (APPS_PLATFORM D-13).
# The app never reads this file: startup calls core/schema.py::upgrade_to_head().
# The DB URL comes from config.settings (DATABASE_URL), not from here.
#
# cd local_backend
# alembic revision --autogenerate --rev-id 0002_short_name -m "short description"
# (rev ids are NNNN_slug, numbered in order; then REVIEW the generated file by hand)
# alembic upgrade head
[alembic]
script_location = migrations
file_template = %%(rev)s
+7 -3
View File
@@ -21,10 +21,14 @@ class Settings(BaseSettings):
DATABASE_URL: str = f"sqlite:///{_DB_DEFAULT.as_posix()}"
VERSION: str = "0.3.1"
CONNECT_SYNC_INTERVAL_SECONDS: int = 30 # how often to poll for pending online orders
# Licensing (APPS_PLATFORM D-3..D-6). "enforced": modules come from the signed v2
# token, or the free tier without one. "off": every module, no limits; ONLY for dev
# machines and test suites (docker-compose.dev.yml, tests/e2e). Never on a site.
LICENSE_MODE: str = "enforced"
# Break-glass master account — lives only in env vars, never in the DB
MASTER_USERNAME: str = ""
MASTER_PASSWORD: str = ""
# Support access (APPS_PLATFORM D-16): this site's secret, made by the builder with
# tools/support_code.py --site-secret <SITE_ID>. Empty = no support access.
SUPPORT_SECRET: str = ""
model_config = {"env_file": str(_HERE / ".env"), "env_file_encoding": "utf-8"}
+6
View File
@@ -0,0 +1,6 @@
"""Platform v2 core: cross-cutting services every module uses (APPS_PLATFORM §10).
Agent note: things that belong here are shared by all modules and have no
business meaning of their own (logging, time, errors, access, module registry).
Feature code goes in its module, not here.
"""
+31
View File
@@ -0,0 +1,31 @@
"""Access control (APPS_PLATFORM §3, D-7, D-8, D-17).
allowed(key) = module_of(key) is effective (licence ∪ free) ∩ enabled
AND (no device OR key in the device app's scope) devices (D-8)
AND (user is superadmin OR user holds key user_permissions
OR a valid manager-override token for key) override.py (D-10)
Use it through the route markers in core/access/deps.py:
require("ordering.orders.cancel") one key (returns the user)
require_any("a.b", "c.d") any of several keys
signed_in any logged-in user (routers.deps.get_current_user)
public() deliberately open (health, login, pairing...)
require_device("kds") device-only endpoints: a paired device running kds
require_device() any paired device (returns the Device)
and inside code with can(user, key) for conditional behaviour (e.g. managers see all orders).
Every route must carry one of these markers somewhere in its dependencies; the guard
tests/guards/test_route_access.py fails otherwise.
Devices (D-8): a request with header X-Xenia-Device carries a paired device
(context.py). Its scope limits both keys (check) and which modules' routes it may reach
(module_required), and a user session started on a device only works with that device.
Manager override (D-10): keys declared Perm(..., overridable=True) answer
access.override_possible instead of access.denied; a manager's PIN gives a one-time
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),
deps.py (route markers), queries.py (find users holding a key). The v1 perm_* projection
(legacy.py) was removed in step 2.99: no frontend reads or writes the booleans.
"""
+65
View File
@@ -0,0 +1,65 @@
"""The one access decision (APPS_PLATFORM §3.1)."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Optional
from core.errors import XeniaError
from core.modules.registry import all_permissions
@dataclass
class AccessContext:
user: Any = None # User row, or the support account (routers.deps.make_support_user); None for device-only calls
session: Any = None # session id (sid) of the user's login
device: Any = None # Device row when the call comes from a paired device (D-8)
override_token: Optional[str] = None # X-Xenia-Override (D-10); consumed by check() when needed
target: Optional[str] = None # what the request acts on, for the override audit row
def module_of(key: str) -> str:
try:
return all_permissions()[key][1]
except KeyError:
raise ValueError(f"unknown permission key {key!r}: declare it in a module manifest") from None
def holds(user, key: str) -> bool:
"""Does the user have the key (ignoring modules)? Superadmin has every key (D-7)."""
if user is None:
return False
if getattr(user, "role", None) == "superadmin":
return True
return key in user_keys(user)
def user_keys(user) -> frozenset[str]:
rows = getattr(user, "permission_rows", None) or []
return frozenset(r.key for r in rows)
def can(user, key: str, db=None) -> bool:
"""Full check without raising: module effective AND user holds the key."""
from core.modules.state import is_effective
return is_effective(module_of(key), db) and holds(user, key)
def check(ctx: AccessContext, key: str, db=None):
"""Raise the right XeniaError unless `key` is allowed for this request. Returns the
AccessOverride row when a manager's approval was used (else None)."""
from core.modules.state import blocked_error, is_effective
module = module_of(key)
if not is_effective(module, db):
raise blocked_error(module, db)
if ctx.device is not None:
from core.access.context import in_scope
if not in_scope(ctx.device.app_key, key):
raise XeniaError("device.out_of_scope", app=ctx.device.app_key, key=key)
if holds(ctx.user, key):
return
from core.access.override import consume, is_overridable
if is_overridable(key):
if ctx.override_token:
return consume(db, ctx.override_token, key, ctx.session, ctx.target)
raise XeniaError("access.override_possible", key=key)
raise XeniaError("access.denied", key=key)
+151
View File
@@ -0,0 +1,151 @@
"""Who is calling: the request's device and user (APPS_PLATFORM §3.1, D-8, step 1.8).
- current_device(request, db): the paired device named by header `X-Xenia-Device`, or None
when the header is absent. Unknown token -> device.not_paired; revoked -> device.revoked;
beyond its app's `devices` limit -> license.limit_reached. Cached on request.state, so
the several dependencies that need it look it up once per request.
- get_context: FastAPI dependency -> AccessContext(user | None, session sid | None, device | None).
For endpoints that accept a device alone or a device + user.
- Device scope (D-8): a device may only use permission keys of its own app plus the
patterns in its manifest's DeviceApp.scope (in_scope), and only routes of those modules
(module_in_scope, applied by core.modules.state.module_required to every non-core router).
Core routes stay reachable (login, /me, bootstrap, live events); keyed core routes are
still checked key by key.
Agent notes:
- The token is a long random secret; only its sha256 is stored (models/device.py).
- last_seen_at is written at most every LAST_SEEN_EVERY_S.
- A user session started on a device (client "terminal") is bound to it: routers.deps.
get_current_user refuses it without that device's header (device.required), so scope
can't be escaped by dropping the header. The WebSocket (routers/ws.py, 3.1a) applies the
same rule with the device token in its first frame; the legacy SSE stream doesn't (it
goes in phase 4).
"""
from __future__ import annotations
import hashlib
from datetime import timedelta
from fnmatch import fnmatchcase
from typing import Optional
from fastapi import Depends, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session
from core.access.check import AccessContext
from core.errors import XeniaError
from core.timeutil import utcnow
from database import get_db
DEVICE_HEADER = "X-Xenia-Device"
LAST_SEEN_EVERY_S = 60
_NO_DEVICE = object()
_optional_bearer = HTTPBearer(auto_error=False)
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
def device_app(app_key: str):
"""The DeviceApp of an app module, or None."""
from core.modules.registry import registry
m = registry().get(app_key)
return m.device_app if m is not None else None
def scope_patterns(app_key: str) -> tuple[str, ...]:
da = device_app(app_key)
return (f"{app_key}.*",) + (tuple(da.scope) if da else ())
def in_scope(app_key: str, key: str) -> bool:
"""May a device running `app_key` use permission `key`?"""
return any(fnmatchcase(key, p) for p in scope_patterns(app_key))
def module_in_scope(app_key: str, module: str) -> bool:
"""May a device running `app_key` call routes of `module` at all?"""
return module == app_key or any(p.split(".", 1)[0] == module for p in scope_patterns(app_key))
def over_limit(db, device) -> Optional[int]:
"""The app's device limit if this device is beyond it (oldest devices keep working
after a downgrade, D-6), else None."""
from core.modules import entitlements
from models.device import Device
cap = entitlements.limit(device.app_key, "devices")
if cap is None:
return None
older = db.query(Device).filter(Device.app_key == device.app_key, Device.revoked_at.is_(None),
Device.id < device.id).count()
return cap if older >= cap else None
def lookup_device(db, token: str):
"""The Device for a raw token, applying revocation and the limit. Raises XeniaError."""
from core.logging import set_log_context
from models.device import Device
dev = db.query(Device).filter(Device.token_hash == hash_token(token)).first()
if dev is None:
raise XeniaError("device.not_paired")
if dev.revoked_at is not None:
raise XeniaError("device.revoked")
cap = over_limit(db, dev)
if cap is not None:
from routers.devices import notify_limit
notify_limit(dev.app_key, "devices", cap, db)
raise XeniaError("license.limit_reached", module=dev.app_key, limit="devices", max=cap)
set_log_context(device=dev.id)
now = utcnow()
if dev.last_seen_at is None or now - dev.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S):
dev.last_seen_at = now
db.commit() # runs before the endpoint body, so nothing else is pending yet
return dev
def current_device(request: Request, db) -> Optional[object]:
cached = getattr(request.state, "xenia_device", _NO_DEVICE)
if cached is not _NO_DEVICE:
return cached
token = request.headers.get(DEVICE_HEADER)
dev = lookup_device(db, token) if token else None
request.state.xenia_device = dev
return dev
def check_device_scope(device, module: str) -> None:
if device is not None and not module_in_scope(device.app_key, module):
raise XeniaError("device.out_of_scope", app=device.app_key, key=module)
def context_for(request: Request, user, db) -> AccessContext:
"""AccessContext of a request whose user is already known (require() and inline checks)."""
from core.access.override import HEADER
return AccessContext(user=user, session=getattr(request.state, "xenia_sid", None),
device=current_device(request, db), override_token=request.headers.get(HEADER),
target=f"{request.method} {request.url.path}")
def authorize(request: Request, db, user, key: str, target: str | None = None):
"""check() from inside an endpoint (module, device scope, key, manager override). Returns
the AccessOverride row when a manager approved it, else None."""
from core.access.check import check
ctx = context_for(request, user, db)
if target:
ctx.target = target
return check(ctx, key, db)
def get_context(request: Request, db: Session = Depends(get_db),
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer)) -> AccessContext:
"""Device (if any) + user (if a bearer token is sent). An invalid token is an error here:
endpoints that want "anonymous unless valid" (bootstrap) handle that themselves."""
from routers.deps import user_from_token
device = current_device(request, db)
user = sid = None
if credentials:
user, sid = user_from_token(credentials.credentials, request, db)
from core.access.override import HEADER
return AccessContext(user=user, session=sid, device=device, override_token=request.headers.get(HEADER),
target=f"{request.method} {request.url.path}")
+81
View File
@@ -0,0 +1,81 @@
"""Route access markers (APPS_PLATFORM §3.1, D-17).
Each marker is a FastAPI dependency with an `__xenia_access__` attribute. The route
guard (tests/guards/test_route_access.py) walks every route's dependency tree and fails
any route without a marker, so "forgot to protect" can't ship.
"""
from __future__ import annotations
from fastapi import Depends, Request
from sqlalchemy.orm import Session
from core.access.check import AccessContext, check
from core.access.context import context_for, current_device
from core.errors import XeniaError
from database import get_db
def _mark(fn, *marker):
fn.__xenia_access__ = marker
return fn
def require(key: str):
"""The user must hold `key`, and its module must be effective. Returns the user."""
# Keys are not validated here (routers are imported while the registry loads);
# tests/guards/test_route_access.py checks every marker's key exists.
from routers.deps import get_current_user
def _dep(request: Request, user=Depends(get_current_user), db: Session = Depends(get_db)):
check(context_for(request, user, db), key, db)
return user
_dep.__name__ = f"require_{key.replace('.', '_')}"
return _mark(_dep, "require", key)
def require_any(*keys: str):
"""The user must hold at least one of `keys` (in an effective module). Returns the user."""
from routers.deps import get_current_user
def _dep(request: Request, user=Depends(get_current_user), db: Session = Depends(get_db)):
last = None
ctx = context_for(request, user, db)
for k in keys:
try:
check(ctx, k, db)
return user
except XeniaError as e:
last = e
raise last
_dep.__name__ = "require_any_" + "_".join(k.replace(".", "_") for k in keys)
return _mark(_dep, "require_any", *keys)
def public():
"""Deliberately open endpoint (health, identity, login, pairing request...)."""
def _dep():
return None
return _mark(_dep, "public")
def require_device(app_key: str | None = None):
"""Device-only endpoint (D-8): the request must carry a valid X-Xenia-Device token.
With `app_key`, the device must run that app and the app's module must be effective
(licensed and enabled). Without it, any paired device (e.g. GET /api/devices/me, which
must answer even when the app is turned off so the screen can say so). Returns the Device."""
def _dep(request: Request, db: Session = Depends(get_db)):
dev = current_device(request, db)
if dev is None:
raise XeniaError("device.not_paired")
if app_key is not None:
if dev.app_key != app_key:
raise XeniaError("device.out_of_scope", app=dev.app_key, key=app_key)
from core.modules.state import blocked_error, is_effective
if not is_effective(app_key, db):
raise blocked_error(app_key, db)
return dev
_dep.__name__ = f"require_device_{app_key or 'any'}"
return _mark(_dep, "require_device", app_key or "*")
+137
View File
@@ -0,0 +1,137 @@
"""Manager override (APPS_PLATFORM D-10, plan step 1.9).
Flow
1. A user calls an action they lack an *overridable* key for (Perm(..., overridable=True))
-> 403 `access.override_possible` {key}.
2. The client asks for a manager's username + PIN and calls
POST /api/access/override {key, username, pin} with the user's own session.
grant() checks the PIN and that the approver may use the key (module effective + holds
it) and returns a token valid for TOKEN_TTL_S, once, for that key and that session.
3. The client retries the action with header X-Xenia-Override: <token>. check() (for
require() routes) or require_override() (for checks inside an endpoint) consumes it.
Agent notes:
- consume() commits at once, so a token can't be used twice even if the action then fails.
A token for another key or another session is refused WITHOUT being burned.
- Only the sha256 of the token is stored. Every approval is a row in access_overrides
(who asked, who approved, key, when used, target); failures are logged, not stored.
- PIN guessing is throttled per requesting session (MAX_FAILURES in FAILURE_WINDOW_S).
- Endpoints whose own rule is more than "holds key" (e.g. cancelling also needs the
venue setting orders.waiter_cancellations_allowed) call require_override() directly
when their rule says no; pass `target` ("order:12") so the audit row says what it was for.
"""
from __future__ import annotations
import logging
import secrets
import threading
import time
from collections import deque
from datetime import timedelta
from core.errors import XeniaError
from core.timeutil import utcnow
logger = logging.getLogger("xenia.access")
HEADER = "X-Xenia-Override"
TOKEN_TTL_S = 60
MAX_FAILURES = 5
FAILURE_WINDOW_S = 300
_lock = threading.Lock()
_failures: dict[str, deque] = {}
def reset_throttle() -> None:
with _lock:
_failures.clear()
def is_overridable(key: str) -> bool:
from core.modules.registry import all_permissions
entry = all_permissions().get(key)
return bool(entry and entry[0].overridable)
def _throttled(who: str) -> bool:
now = time.monotonic()
with _lock:
q = _failures.setdefault(who, deque())
while q and now - q[0] > FAILURE_WINDOW_S:
q.popleft()
return len(q) >= MAX_FAILURES
def _fail(who: str) -> None:
with _lock:
_failures.setdefault(who, deque()).append(time.monotonic())
def grant(db, *, key: str, username: str, pin: str, requester, sid: str | None, device=None):
"""Check the approver and create a one-time token. Returns (token, AccessOverride row)."""
import bcrypt
from core.access.check import can
from core.access.context import hash_token
from core.modules.registry import all_permissions
from models.access_override import AccessOverride
from models.user import User
if key not in all_permissions():
raise XeniaError("access.unknown_key", key=key)
if not is_overridable(key):
raise XeniaError("access.not_overridable", key=key)
who = sid or f"user:{getattr(requester, 'id', None)}"
if _throttled(who):
raise XeniaError("access.override_rate_limited")
approver = db.query(User).filter(User.username == username, User.is_active == True).first() # noqa: E712
if approver is None or not pin or not approver.pin_hash or \
not bcrypt.checkpw(pin.encode(), approver.pin_hash.encode()):
_fail(who)
logger.warning("override.denied reason=credentials key=%s requester=%s approver=%s",
key, getattr(requester, "id", None), username)
raise XeniaError("auth.invalid_credentials")
if not can(approver, key, db):
logger.warning("override.denied reason=approver_lacks_key key=%s requester=%s approver=%s",
key, getattr(requester, "id", None), approver.id)
raise XeniaError("access.approver_lacks_key", key=key)
token = secrets.token_urlsafe(24)
now = utcnow()
row = AccessOverride(key=key, token_hash=hash_token(token), requested_by=getattr(requester, "id", None) or None,
requested_session=sid, approved_by=approver.id,
device_id=getattr(device, "id", None), created_at=now,
expires_at=now + timedelta(seconds=TOKEN_TTL_S))
db.add(row)
db.commit()
logger.info("override.granted id=%s key=%s requester=%s approver=%s", row.id, key, row.requested_by, approver.id)
return token, row
def consume(db, token: str, key: str, sid: str | None, target: str | None = None):
"""Use a token for `key` in session `sid`. Returns the AccessOverride row (approved_by
says who approved). Raises access.override_invalid."""
from core.access.context import hash_token
from models.access_override import AccessOverride
row = db.query(AccessOverride).filter(AccessOverride.token_hash == hash_token(token)).first()
now = utcnow()
reason = ("unknown" if row is None else "used" if row.used_at is not None else
"expired" if row.expires_at < now else "wrong_key" if row.key != key else
"wrong_session" if row.requested_session != sid else None)
if reason:
logger.warning("override.refused reason=%s key=%s id=%s", reason, key, getattr(row, "id", None))
raise XeniaError("access.override_invalid")
row.used_at = now
row.target = (target or "")[:200] or None
db.commit()
logger.info("override.used id=%s key=%s target=%s approver=%s", row.id, key, row.target, row.approved_by)
return row
def require_override(request, db, key: str, target: str | None = None, **params):
"""Inside an endpoint whose own rule said no: accept a valid override token for `key`,
otherwise raise access.override_possible (params go along, e.g. reason=...)."""
token = request.headers.get(HEADER)
if not token:
raise XeniaError("access.override_possible", key=key, **params)
return consume(db, token, key, getattr(request.state, "xenia_sid", None),
target or f"{request.method} {request.url.path}")
+21
View File
@@ -0,0 +1,21 @@
"""Find users by permission key (replaces v1 filters like User.perm_access_dashboard == True)."""
from __future__ import annotations
from sqlalchemy import or_, select
def holders_filter(key: str):
"""SQLAlchemy filter: superadmins, or users with a grant for `key`."""
from models.user import User
from models.user_permission import UserPermission
return or_(User.role == "superadmin",
User.id.in_(select(UserPermission.user_id).where(UserPermission.key == key)))
def users_with_key(db, key: str, active_only: bool = True):
"""Query of users holding `key` (superadmins included)."""
from models.user import User
q = db.query(User).filter(holders_filter(key))
if active_only:
q = q.filter(User.is_active == True) # noqa: E712
return q
+81
View File
@@ -0,0 +1,81 @@
"""Role templates (D-7): the default keys of each role.
A role is a label plus a template. The template is copied into user_permissions when a
user is created and on "reset to role defaults"; after that the user's keys are theirs.
The template starts from the module manifests (Perm(..., roles=...)) and the venue can change
it (plan step 4.3, models/role_permission.py): role_template(role, db) includes those changes,
and set_role_keys() saves a role's new keys and applies the difference to everyone with
that role (a key given to the role is given to each of them; a key taken away is taken
from each of them; their other keys stay as they are).
"""
from __future__ import annotations
from core.modules.registry import all_permissions
def manifest_template(role: str) -> set[str]:
"""The role's keys as the manifests declare them. Superadmin: none (implicit-all)."""
if role == "superadmin":
return set()
return {k for k, (p, _m) in all_permissions().items() if role in p.roles}
def role_template(role: str, db=None) -> set[str]:
"""Keys a new user with this role gets: the manifests' plus the venue's changes (with db)."""
keys = manifest_template(role)
if db is None or role == "superadmin":
return keys
from models.role_permission import RolePermission
catalogue = all_permissions()
for row in db.query(RolePermission).filter(RolePermission.role == role).all():
if row.key not in catalogue:
continue # a key whose module is gone
if row.granted:
keys.add(row.key)
else:
keys.discard(row.key)
return keys
def set_role_keys(db, role: str, keys) -> tuple[list[str], list[str]]:
"""Make `keys` the role's template and apply the change to everyone with the role.
Returns (added, removed) compared with the template before. No commit."""
from core.errors import XeniaError
from models.role_permission import RolePermission
from models.user import User
catalogue = all_permissions()
wanted = set(keys)
unknown = wanted - set(catalogue)
if unknown:
raise XeniaError("access.unknown_key", key=sorted(unknown)[0])
before = role_template(role, db)
base = manifest_template(role)
db.query(RolePermission).filter(RolePermission.role == role).delete()
for k in sorted(wanted - base):
db.add(RolePermission(role=role, key=k, granted=True))
for k in sorted(base - wanted):
db.add(RolePermission(role=role, key=k, granted=False))
added, removed = sorted(wanted - before), sorted(before - wanted)
if added or removed:
for user in db.query(User).filter(User.role == role).all():
mine = {r.key for r in user.permission_rows}
set_user_keys(user, (mine | set(added)) - set(removed))
return added, removed
def set_user_keys(user, keys) -> None:
"""Replace a user's grants with `keys` (validated against the catalogue)."""
from models.user_permission import UserPermission
catalogue = all_permissions()
unknown = set(keys) - set(catalogue)
if unknown:
from core.errors import XeniaError
raise XeniaError("access.unknown_key", key=sorted(unknown)[0])
wanted = set(keys)
user.permission_rows = [r for r in user.permission_rows if r.key in wanted] + \
[UserPermission(key=k) for k in sorted(wanted - {r.key for r in user.permission_rows})]
def apply_role_template(user, db=None) -> None:
set_user_keys(user, role_template(user.role, db))
+207
View File
@@ -0,0 +1,207 @@
"""API errors as stable codes (APPS_PLATFORM D-12, §3.2).
Every error response has this shape:
{"error": {"code": "order.not_found", "params": {"order_id": 7}, "message": "Order 7 not found."},
"detail": "Order 7 not found."}
- code: stable identifier; frontends translate it (i18n key `errors.<code>`).
- params: values the translated text can use.
- message: English, for logs, curl and un-migrated screens.
- detail: kept for frontends written before v2 (they read `detail`).
New and converted code raises XeniaError:
raise XeniaError("order.not_found", order_id=order_id)
The status comes from the registry below; pass status= only to override it.
Plain HTTPException (still in most v1 routers; converted gradually, plan step 6.x)
is wrapped as code "http.<status>" with its original `detail` untouched.
Request validation errors become "validation.invalid" with the field errors in params.
Unhandled exceptions become "internal.error" (500) with the request id in params.
Agent notes:
- Add every new code to CODES with its HTTP status and English message (str.format
placeholders from params). tests/test_errors.py fails on a raised code that
isn't registered (via XeniaError's constructor).
- Codes are part of the API contract: never rename one; add a new one instead.
"""
from __future__ import annotations
import logging
from http import HTTPStatus
from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
logger = logging.getLogger("xenia.errors")
# code -> (HTTP status, English message)
CODES: dict[str, tuple[int, str]] = {
# access / licensing / modules (filled in by steps 1.3-1.9)
"access.denied": (403, "You don't have permission to do this ({key})."),
"access.override_possible": (403, "A manager can approve this ({key})."),
"access.override_invalid": (403, "This approval isn't valid any more. Ask a manager again."),
"access.not_overridable": (422, "{key} can't be approved by a manager."),
"access.approver_lacks_key": (403, "That account can't approve this ({key})."),
"access.override_rate_limited": (429, "Too many wrong PINs. Wait a few minutes and try again."),
"access.unknown_key": (422, "There is no permission {key}."),
"access.cannot_grant": (403, "You can only give permissions you have yourself ({key})."),
"module.disabled": (403, "The {module} module is turned off."),
"module.not_licensed": (402, "This site's license doesn't include {module}."),
"module.unknown": (404, "There is no module {module}."),
"module.cannot_disable": (400, "{module} is part of the core and can't be turned off."),
"license.limit_reached": (402, "License limit reached for {module} {limit} ({max})."),
"license.expired": (402, "The license has expired."),
"license.history_limited": (402, "This license shows only the last {days} days of history ({module})."),
# identity
"auth.invalid_credentials": (401, "Wrong username or password."),
"auth.session_ended": (401, "Your session has ended. Please log in again."),
"auth.session_exists": (409, "You're already logged in on another {client}. Log out there first."),
"auth.login_mode_not_allowed": (403, "This way of logging in isn't enabled ({mode})."),
"auth.mode_needs_device": (403, "Logging in by {mode} only works on a paired device."),
"auth.username_required": (422, "Enter your username."),
"auth.client_not_allowed": (403, "This account can't use the {client} app."),
"auth.session_not_found": (404, "Session not found."),
"auth.wrong_pin": (401, "Wrong PIN. {attempts_left} tries left before you are signed out."),
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
"auth.support_code_invalid": (401, "That support code is wrong or has expired. Ask for a new challenge."),
"auth.support_rate_limited": (429, "Too many support challenges. Wait a few minutes and try again."),
"pos.shift_required": (409, "Start your shift before selling."),
"pos.payment_invalid": (422, "This payment doesn't add up ({reason})."),
"pos.fiscal_vat_missing": (422, "Fiscal receipts are on, but these products have no VAT group: {names}."),
"pos.line_invalid": (422, "Cart line {line} can't be sold as chosen ({reason})."),
"pos.table_not_found": (404, "Table {table_id} not found."),
"pos.table_not_yours": (403, "{table} isn't in your zones. A manager can add the zone to your account."),
"pos.items_changed": (409, "Some of these items were paid or cancelled in the meantime. Check the order and try again."),
"pos.order_unpaid": (409, "Items still unpaid: {count}. Take the payment or cancel them first."),
"order.items_not_combinable": (422, "These lines can't be combined: only unpaid lines of the same item, with the same choices, note, price and kitchen state, and no discount, deal or tab."),
"order.not_sold_here": (422, "{name} isn't sold for this kind of order."),
"order.lines_required": (422, "This app sent the order in an old format. Update the app and send it again."),
"order.line.product_unavailable": (422, "{name} isn't available any more (line {line})."),
"order.line.option_gone": (422, "{name}: a chosen option doesn't exist any more (line {line}). Remove it and add it again."),
"order.line.choice_missing": (422, "{name}: a required choice is missing (line {line})."),
"order.line.quantity": (422, "{name}: that quantity isn't allowed (line {line})."),
"order.line.price": (422, "{name}: that price change isn't allowed (line {line})."),
"order.line.client_price": (422, "{name}: the app sent its own prices, but prices come from the server (line {line}). Update the app."),
"fees.area_not_found": (404, "Delivery area {area_id} not found."),
"fees.rule_not_found": (404, "Fee rule {rule_id} not found."),
"fees.area_in_use": (409, "This area is used by fee rules: {rules}. Change those rules first."),
"fees.order_invalid": (422, "The new order must list every rule once."),
"fees.vat_group_unknown": (422, "VAT group {vat_group_id} isn't one of the fiscal machine's groups."),
"refund.invalid": (422, "This refund doesn't add up ({reason})."),
"refund.too_old": (409, "Only payments from today's business day can be refunded at the counter."),
"refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."),
"online.not_found": (404, "Online order {order_id} not found."),
"online.status_changed": (409, "This online order was changed on another screen in the meantime. Check where it is now."),
"caller_id.key_invalid": (403, "The phone system's key is missing or wrong."),
"display.qr_url_missing": (422, "Enter the link the QR code opens."),
"display.look_unknown": (404, "Look {look_id} not found."),
"display.look_default": (409, "The default look can't be deleted. Make another look the default first."),
"display.not_a_display": (404, "Device {device_id} isn't a customer display."),
"media.not_found": (404, "File {media_id} isn't in the media library."),
"media.type": (422, "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4 or WebM)."),
"media.too_big": (413, "The file is too big (at most {max_mb} MB)."),
"media.too_many_pixels": (422, "The picture is too large (at most {max_mp} megapixels)."),
"media.unreadable": (422, "This picture can't be read. Save it again as JPG or PNG and upload it."),
"media.in_use": (409, "This file is used by {uses}. Remove it there first."),
"media.not_a_picture": (422, "Pick a picture here, not a video."),
"reservation.not_found": (404, "Booking {reservation_id} not found."),
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
"reservation.table_unknown": (404, "Table {table_id} not found."),
"reservation.table_busy": (409, "That table already has an open order. Pick another table, or close that order first."),
"kds.item_not_found": (404, "Item {item_id} not found on this order."),
"kds.item_claimed": (409, "{name} is already on this item."),
"kds.claim_needs_staff": (403, "Only a staff member can claim an item."),
"device.revoked": (401, "This device was removed. Pair it again."),
"device.not_paired": (401, "This device isn't paired with the venue."),
"device.out_of_scope": (403, "A {app} device can't do this ({key})."),
"device.required": (401, "This login belongs to a paired device. Use it from that device."),
"device.not_found": (404, "Device {device_id} not found."),
"device.pair_code_invalid": (404, "That pairing code is wrong or has expired."),
"device.pair_rate_limited": (429, "Too many pairing requests. Wait a few minutes and try again."),
"device.not_an_app": (422, "{app} is not an app that runs on a device."),
"device.login_mode_invalid": (422, "A {app} device can't use the login mode {mode}."),
"device.link_invalid": (422, "Device {device_id} can't be linked to this device."),
# validation
"validation.invalid": (422, "Some fields are invalid."),
"validation.unknown_language": (422, "Unsupported language: {language}."),
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
"validation.setting_value": (422, "{key} can't be set to {value!r}."),
"validation.device_config": (422, "This device setting is not valid: {key}."),
# server
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
# domain
"order.not_found": (404, "Order {order_id} not found."),
"notification.not_found": (404, "Notification {notification_id} not found."),
"system.log_not_found": (404, "There is no log file for {date}."),
"catalog.unknown_category": (422, "There is no category {category_id}."),
"catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."),
}
class XeniaError(Exception):
"""An API error with a registered code. raise XeniaError("order.not_found", order_id=5)."""
def __init__(self, code: str, status: int | None = None, **params):
if code not in CODES:
raise KeyError(f"unregistered error code {code!r}: add it to core/errors.py CODES")
default_status, template = CODES[code]
self.code = code
self.status = status or default_status
self.params = params
try:
self.message = template.format(**params)
except (KeyError, IndexError):
self.message = template
super().__init__(self.message)
def error_body(code: str, message: str, params: dict | None = None, detail=None) -> dict:
return {"error": {"code": code, "params": params or {}, "message": message},
"detail": message if detail is None else detail}
async def _xenia_error_handler(request: Request, exc: XeniaError):
return JSONResponse(error_body(exc.code, exc.message, exc.params), status_code=exc.status)
async def _http_exception_handler(request: Request, exc: StarletteHTTPException):
detail = exc.detail
if isinstance(detail, str):
message = detail
elif isinstance(detail, dict) and isinstance(detail.get("message"), str):
message = detail["message"]
else:
try:
message = HTTPStatus(exc.status_code).phrase
except ValueError:
message = "Error"
return JSONResponse(error_body(f"http.{exc.status_code}", message, detail=detail),
status_code=exc.status_code, headers=getattr(exc, "headers", None))
async def _validation_handler(request: Request, exc: RequestValidationError):
errors = [{"field": ".".join(str(p) for p in e.get("loc", ())[1:]) or None,
"type": e.get("type"), "message": e.get("msg")} for e in exc.errors()]
# `detail` stays FastAPI's usual list, so existing frontends keep working
return JSONResponse(error_body("validation.invalid", CODES["validation.invalid"][1],
{"errors": jsonable_encoder(errors)}, detail=jsonable_encoder(exc.errors())),
status_code=422)
async def _unhandled_handler(request: Request, exc: Exception):
"""Last resort: a bug. Logged with the traceback; the client gets the request id
(also in the X-Request-ID header) so support can find the log lines."""
from core.logging import current_request_id
rid = getattr(request.state, "request_id", None) or current_request_id() or "-"
logger.exception("http.unhandled_error request_id=%s path=%s", rid, request.url.path)
err = XeniaError("internal.error", request_id=rid)
return JSONResponse(error_body(err.code, err.message, err.params), status_code=500,
headers={"X-Request-ID": rid})
def install_error_handlers(app: FastAPI) -> None:
app.add_exception_handler(Exception, _unhandled_handler)
app.add_exception_handler(XeniaError, _xenia_error_handler)
app.add_exception_handler(StarletteHTTPException, _http_exception_handler)
app.add_exception_handler(RequestValidationError, _validation_handler)
+139
View File
@@ -0,0 +1,139 @@
"""Backend translations for text the backend itself renders (APPS_PLATFORM D-12, §8).
What uses it: printed tickets and reports, and later server-rendered notification text.
What does NOT: API errors (they return codes + English, core/errors.py) and UI text
(frontends translate with i18next).
Files: core/i18n/<lang>.json, nested objects; keys are dotted paths ("print.ticket.order").
English (en.json) is the source and the fallback: a key missing in another language
falls back to English; a key missing in English returns the key itself and logs a warning.
Placeholders use str.format syntax: "Table {table}", "TOTAL: {total:.2f}e".
Language resolution (§8): user.language -> device language (step 1.8) -> venue.language -> "en".
Printing: prep_zone.language -> venue.language.
Agent notes:
- Add a key to en.json first, then el.json. tests/test_i18n.py checks both files have
the same keys and the same placeholders.
- Greek print text is written WITHOUT accents on purpose: the thermal printers use
code page CP737, and the venue's tickets have always looked like that.
- The venue language is cached; the settings router calls invalidate() when it changes.
"""
from __future__ import annotations
import json
import logging
import threading
from pathlib import Path
logger = logging.getLogger("xenia.i18n")
_DIR = Path(__file__).resolve().parent
DEFAULT_LANGUAGE = "en"
def _flatten(obj: dict, prefix: str = "") -> dict[str, str]:
out = {}
for k, v in obj.items():
key = f"{prefix}{k}"
if isinstance(v, dict):
out.update(_flatten(v, key + "."))
else:
out[key] = str(v)
return out
def _load() -> dict[str, dict[str, str]]:
return {f.stem: _flatten(json.loads(f.read_text(encoding="utf-8"))) for f in sorted(_DIR.glob("*.json"))}
CATALOG: dict[str, dict[str, str]] = _load()
SUPPORTED_LANGUAGES: tuple[str, ...] = tuple(sorted(CATALOG))
def is_supported(lang: str | None) -> bool:
return lang in CATALOG
def t(key: str, lang: str | None = None, **params) -> str:
"""Translate key into lang (fallback: English, then the key itself)."""
template = CATALOG.get(lang or DEFAULT_LANGUAGE, {}).get(key)
if template is None:
template = CATALOG[DEFAULT_LANGUAGE].get(key)
if template is None:
logger.warning("i18n.missing_key key=%s lang=%s", key, lang)
return key
try:
return template.format(**params) if params else template
except (KeyError, IndexError, ValueError):
logger.warning("i18n.bad_params key=%s lang=%s params=%s", key, lang, sorted(params))
return template
# ── language resolution ──────────────────────────────────────────────────────
_lock = threading.Lock()
_cache: dict = {}
def configure(venue_language: str | None = None) -> None:
with _lock:
if venue_language is not None:
_cache["venue"] = venue_language
def invalidate() -> None:
with _lock:
_cache.clear()
def venue_language() -> str:
"""The `venue.language` setting (default "en"), cached."""
with _lock:
lang = _cache.get("venue")
if lang is None:
lang = DEFAULT_LANGUAGE
try:
from database import SessionLocal
from models.settings import PosSettings
db = SessionLocal()
try:
row = db.query(PosSettings).filter(PosSettings.key == "venue.language").first()
if row and is_supported(row.value):
lang = row.value
finally:
db.close()
except Exception:
pass
with _lock:
_cache["venue"] = lang
return lang
def normalize_language(value):
"""API input for a language field: "" or None -> None (inherit); a supported code -> itself.
Anything else raises XeniaError("validation.unknown_language")."""
if value is None or value == "":
return None
if not is_supported(value):
from core.errors import XeniaError
raise XeniaError("validation.unknown_language", language=value)
return value
def resolve_language(*candidates: str | None) -> str:
"""First supported language among candidates (most specific first), else the venue's."""
for c in candidates:
if is_supported(c):
return c
return venue_language()
def user_language(user) -> str:
"""§8 order for a user: user.language -> (device, step 1.8) -> venue -> en."""
return resolve_language(getattr(user, "language", None))
def zone_language(zone) -> str:
"""Language of tickets printed for a prep zone: zone.language -> venue."""
return resolve_language(getattr(zone, "language", None))
+101
View File
@@ -0,0 +1,101 @@
{
"print": {
"aligned": {
"order": "Παραγγελια: #{value}",
"table": "Τραπεζι: {value}",
"time": "Ωρα: {value}"
},
"cancel": {
"banner": "*** AKYPΩΣH ***"
},
"receipt": {
"closed": "Εκλεισε: {value}",
"opened": "Ανοιχτηκε: {value}",
"order_title": "ΠΑΡΑΓΓΕΛΙΑ #{value}"
},
"report": {
"avg_duration": "Μ. διαρκεια: {minutes:.0f} λεπτα",
"categories_title": "ΑΝΑΦΟΡΑ ΚΑΤΗΓΟΡΙΩΝ",
"details": "ΑΝΑΛΥΤΙΚΑ",
"from": "Απο: {value}",
"grand_total": "ΣΥΝΟΛΟ ΟΛΩΝ",
"items": "Αντικειμενα: {value}",
"orders": "Παραγγελιες: {value}",
"pct_revenue": "% Εσοδων",
"pct_units": "% Τεμαχιων",
"period": "Περιοδος: {value}",
"prep_zone_title": "ΖΩΝΗ ΠΡΟΕΤΟΙΜΑΣΙΑΣ",
"print_jobs": "Εκτυπωσεις: {value}",
"printer": "Εκτυπωτης: {value}",
"printer_title": "ΑΝΑΦΟΡΑ ΕΚΤΥΠΩΤΗ",
"product_breakdown": "ΑΝΑΛΥΣΗ ΠΡΟΙΟΝΤΩΝ",
"product_shares": "{revenue:.2f}e | {rev}% εσ. {qty}% τεμ.",
"products_full_title": "ΠΛΗΡΗΣ ΑΝΑΛΥΣΗ ΠΡΟΙΟΝΤΩΝ",
"products_title": "ΑΝΑΦΟΡΑ ΠΡΟΙΟΝΤΩΝ",
"qty_units": "{value} τεμ.",
"revenue": "Εσοδα",
"table": "Τραπεζι: {value}",
"table_orders_avg": "{count} παρ. / μ.ο. {avg:.2f}e",
"tables_title": "ΑΝΑΦΟΡΑ ΤΡΑΠΕΖΙΩΝ",
"to": "Εως: {value}",
"total": "ΣΥΝΟΛΟ: {value:.2f}e",
"total_items": "Συνολο ειδων: {value}",
"total_qty": "Συνολο τεμ.: {value}",
"units": "Τεμαχια",
"value": "Αξια: {value:.2f}e",
"value_caps": "ΑΞΙΑ: {value:.2f}e",
"waiter": "Σερβιτορος: {value}",
"waiter_title": "ΑΝΑΦΟΡΑ ΣΕΡΒΙΤΟΡΟΥ",
"workday": "Εργασιμη: {value}"
},
"synopsis": {
"paid": "ΠΛΗΡΩΜΕΝΑ:",
"paid_total": "Πληρωμενο: {value:.2f}e",
"pending": "ΕΚΚΡΕΜΗ:",
"remaining": "Εκκρεμει: {value:.2f}e",
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ"
},
"ticket": {
"compact_guests": " | {count}ατ.",
"compact_header": "Παρ. #{order} | Τρ. {table} | {time} | {waiter}",
"date_label": "Ημερομηνια:",
"end": "Τελος Παραγγελιας",
"guests_label": "Ατομα:",
"note": "Σημ: {note}",
"order_title": "Παραγγελια #{order}",
"table_label": "Τραπεζι:",
"table_value": "Τραπεζι {table}",
"waiter_label": "Σερβιτορος:",
"without": "ΧΩΡΙΣ:",
"for_label": "Για:",
"asap": "Το συντομοτερο",
"online_label": "Online:",
"type": {
"delivery": "Διανομη",
"takeaway": "Παραλαβη",
"dine_in": "Τραπεζι",
"preorder": "Προπαραγγελια"
}
}
},
"notification": {
"license": {
"limit_reached": "Συμπληρώθηκε το όριο της άδειας: το {module} επιτρέπει {max} {limit}. Αναβαθμίστε την άδεια για περισσότερα.",
"expiring": "Η άδεια λήγει σε {days} ημέρες ({expires_at}). Ανανεώστε την για να κρατήσετε όλες τις λειτουργίες."
},
"support": {
"access_used": "Η υποστήριξη της Xenia συνδέθηκε στο κατάστημα (από {ip})."
},
"print": {
"failed_final": "Ένα δελτίο της παραγγελίας #{order_id} δεν τυπώθηκε ποτέ στον εκτυπωτή {printer} ({attempts} προσπάθειες).",
"failing": "Ένα δελτίο της παραγγελίας #{order_id} δεν έχει τυπωθεί ακόμα στον εκτυπωτή {printer} (αποτυχημένες προσπάθειες μέχρι τώρα: {attempts}· συνεχίζει να προσπαθεί). Ελέγξτε τον εκτυπωτή."
}
},
"system_product": {
"delivery_fee": "Μεταφορικά"
},
"qr": {
"order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.",
"sender": "QR μενού"
}
}
+101
View File
@@ -0,0 +1,101 @@
{
"print": {
"aligned": {
"order": "Order: #{value}",
"table": "Table: {value}",
"time": "Time: {value}"
},
"cancel": {
"banner": "*** CANCELLED ***"
},
"receipt": {
"closed": "Closed: {value}",
"opened": "Opened: {value}",
"order_title": "ORDER #{value}"
},
"report": {
"avg_duration": "Avg. duration: {minutes:.0f} min",
"categories_title": "CATEGORY REPORT",
"details": "DETAILS",
"from": "From: {value}",
"grand_total": "ALL PRINTERS",
"items": "Items: {value}",
"orders": "Orders: {value}",
"pct_revenue": "% revenue",
"pct_units": "% units",
"period": "Period: {value}",
"prep_zone_title": "PREP ZONE",
"print_jobs": "Print jobs: {value}",
"printer": "Printer: {value}",
"printer_title": "PRINTER REPORT",
"product_breakdown": "PRODUCT BREAKDOWN",
"product_shares": "{revenue:.2f}e | {rev}% rev. {qty}% qty",
"products_full_title": "FULL PRODUCT BREAKDOWN",
"products_title": "PRODUCT REPORT",
"qty_units": "{value} pcs",
"revenue": "Revenue",
"table": "Table: {value}",
"table_orders_avg": "{count} ord. / avg {avg:.2f}e",
"tables_title": "TABLE REPORT",
"to": "To: {value}",
"total": "TOTAL: {value:.2f}e",
"total_items": "Total items: {value}",
"total_qty": "Total qty: {value}",
"units": "Units",
"value": "Value: {value:.2f}e",
"value_caps": "VALUE: {value:.2f}e",
"waiter": "Waiter: {value}",
"waiter_title": "WAITER REPORT",
"workday": "Workday: {value}"
},
"synopsis": {
"paid": "PAID:",
"paid_total": "Paid: {value:.2f}e",
"pending": "PENDING:",
"remaining": "Remaining: {value:.2f}e",
"title": "ORDER SUMMARY"
},
"ticket": {
"compact_guests": " | {count}pax",
"compact_header": "Ord. #{order} | Tbl {table} | {time} | {waiter}",
"date_label": "Date:",
"end": "End of order",
"guests_label": "Guests:",
"note": "Note: {note}",
"order_title": "Order #{order}",
"table_label": "Table:",
"table_value": "Table {table}",
"waiter_label": "Waiter:",
"without": "NO:",
"for_label": "For:",
"asap": "As soon as possible",
"online_label": "Online:",
"type": {
"delivery": "Delivery",
"takeaway": "Takeaway",
"dine_in": "Table",
"preorder": "Pre-order"
}
}
},
"notification": {
"license": {
"limit_reached": "License limit reached: {module} allows {max} {limit}. Upgrade the license to add more.",
"expiring": "The license expires in {days} days ({expires_at}). Renew it to keep every feature."
},
"support": {
"access_used": "Xenia support logged in to this venue (from {ip})."
},
"print": {
"failed_final": "A ticket for order #{order_id} never printed on {printer} ({attempts} attempts).",
"failing": "A ticket for order #{order_id} hasn't printed on {printer} yet (failed attempts so far: {attempts}; still retrying). Check the printer."
}
},
"system_product": {
"delivery_fee": "Delivery fee"
},
"qr": {
"order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.",
"sender": "QR menu"
}
}
+306
View File
@@ -0,0 +1,306 @@
"""Backend logging: one daily text file per UTC day, tagged with the request (APPS_PLATFORM §10).
Line format (human-readable, grep-friendly):
2026-11-12T10:39:25.226Z INFO services.printer_service [req=3f9a1c2e user=5 device=-] print.job.failed job=12 ...
Where files go:
<log dir>/xenia-YYYY-MM-DD.log (the date is the UTC date of the line)
log dir = $LOG_DIR, else "logs" next to the SQLite database
= /app/data/logs in Docker (DATABASE_URL=sqlite:////app/data/pos.db)
= %LOCALAPPDATA%\\pos\\logs in Windows dev
Files older than the retention (setting `system.log_retention_days`, default 30) are deleted.
How a line gets its tags:
RequestContextMiddleware puts a small mutable dict in a ContextVar for each
HTTP request. Auth code calls `set_log_context(user=...)`, which mutates that
dict. A mutable dict (not separate ContextVars) is used on purpose: FastAPI
runs sync dependencies and endpoints in worker threads with a *copy* of the
context, so a ContextVar.set() in a dependency would not be seen by the
endpoint, but a change to the shared dict is.
Lines from background threads (print retry, cloud sync) show req=-.
Agent notes:
- Call `setup_logging()` once, at import time of main.py, so uvicorn's own
loggers are re-pointed to our handlers (uvicorn configures logging before it
imports the app, so we run after it and win).
- Message style for new code: an event key first, then key=value pairs, e.g.
logger.info("print.job.created job=%s order=%s printer=%s", ...). That keeps
the file greppable by event.
- Never log secrets (tokens, PINs, passwords, license keys).
"""
from __future__ import annotations
import logging
import os
import re
import secrets
import sys
import time
from contextvars import ContextVar
from datetime import datetime, timedelta, timezone
from pathlib import Path
from core.timeutil import utcnow
DEFAULT_RETENTION_DAYS = 30
FILE_PREFIX = "xenia-"
_FILE_RE = re.compile(r"^xenia-(\d{4}-\d{2}-\d{2})\.log$")
_FORMAT = "%(asctime)s %(levelname)-5s %(name)s [req=%(req)s user=%(user)s device=%(device)s] %(message)s"
# The per-request context: {"req": str, "user": str|None, "device": str|None}
_ctx: ContextVar[dict | None] = ContextVar("xenia_log_ctx", default=None)
# ── context ──────────────────────────────────────────────────────────────────
def new_request_id() -> str:
return secrets.token_hex(4)
def set_log_context(**values) -> None:
"""Tag the current request's log lines, e.g. set_log_context(user=5).
No-op outside a request (background threads)."""
ctx = _ctx.get()
if ctx is not None:
for k, v in values.items():
ctx[k] = None if v is None else str(v)
def current_request_id() -> str | None:
ctx = _ctx.get()
return ctx["req"] if ctx else None
class ContextFilter(logging.Filter):
"""Adds req/user/device attributes to every record (\"-\" when unknown).
Attached to handlers, so records from every logger get them."""
def filter(self, record: logging.LogRecord) -> bool:
ctx = _ctx.get() or {}
record.req = ctx.get("req") or "-"
record.user = ctx.get("user") or "-"
record.device = ctx.get("device") or "-"
return True
class UtcFormatter(logging.Formatter):
"""ISO-8601 UTC timestamps with milliseconds and a Z."""
converter = time.gmtime
def formatTime(self, record, datefmt=None): # noqa: N802 (stdlib name)
dt = datetime.fromtimestamp(record.created, tz=timezone.utc)
return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{int(record.msecs):03d}Z"
# ── file handler ─────────────────────────────────────────────────────────────
class DailyFileHandler(logging.Handler):
"""Writes to <dir>/xenia-<UTC date>.log and switches file when the UTC date changes.
Why not TimedRotatingFileHandler: it writes to a fixed name and renames at
rollover, which gives `xenia.log.2026-11-12` names, and its rename fails on
Windows while another process has the file open. Opening a new dated file
needs no rename. Old files are pruned at each switch and at startup.
"""
def __init__(self, directory: Path, retention_days: int = DEFAULT_RETENTION_DAYS):
super().__init__()
self.directory = Path(directory)
self.directory.mkdir(parents=True, exist_ok=True)
self.retention_days = retention_days
self._date: str | None = None
self._stream = None
def path_for(self, date_str: str) -> Path:
return self.directory / f"{FILE_PREFIX}{date_str}.log"
def _open_for(self, date_str: str) -> None:
if self._stream:
self._stream.close()
self._stream = open(self.path_for(date_str), "a", encoding="utf-8")
self._date = date_str
self.prune()
def emit(self, record: logging.LogRecord) -> None:
try:
date_str = datetime.fromtimestamp(record.created, tz=timezone.utc).strftime("%Y-%m-%d")
if date_str != self._date:
self._open_for(date_str)
self._stream.write(self.format(record) + "\n")
self._stream.flush()
except Exception:
self.handleError(record)
def prune(self, today: datetime | None = None) -> list[Path]:
"""Delete files whose date is more than retention_days before today (UTC)."""
today = (today or utcnow()).date()
cutoff = today - timedelta(days=self.retention_days)
removed = []
for f in self.directory.glob(f"{FILE_PREFIX}*.log"):
m = _FILE_RE.match(f.name)
if not m:
continue
try:
if datetime.strptime(m.group(1), "%Y-%m-%d").date() < cutoff:
f.unlink()
removed.append(f)
except (ValueError, OSError):
continue
return removed
def close(self) -> None:
self.acquire()
try:
if self._stream:
self._stream.close()
self._stream = None
self._date = None
finally:
self.release()
super().close()
# ── setup ────────────────────────────────────────────────────────────────────
_file_handler: DailyFileHandler | None = None
def default_log_dir() -> Path:
if os.environ.get("LOG_DIR"):
return Path(os.environ["LOG_DIR"])
from config import settings
url = settings.DATABASE_URL
db_path = url.split("sqlite:///", 1)[1] if url.startswith("sqlite:///") else "./pos.db"
return Path(db_path).resolve().parent / "logs"
def setup_logging(log_dir: Path | None = None, level: int = logging.INFO,
retention_days: int = DEFAULT_RETENTION_DAYS) -> DailyFileHandler:
"""Configure the root logger: console (stderr) + daily file. Idempotent."""
global _file_handler
root = logging.getLogger()
for h in list(root.handlers):
if getattr(h, "_xenia", False):
root.removeHandler(h)
h.close()
fmt = UtcFormatter(_FORMAT)
ctx_filter = ContextFilter()
console = logging.StreamHandler(sys.stderr)
file_handler = DailyFileHandler(log_dir or default_log_dir(), retention_days)
for h in (console, file_handler):
h.setFormatter(fmt)
h.addFilter(ctx_filter)
h._xenia = True
root.addHandler(h)
root.setLevel(level)
# uvicorn installs its own handlers before importing the app. Send its
# server/error lines through ours; per-request lines come from our
# middleware instead of uvicorn.access (which has no request id).
for name in ("uvicorn", "uvicorn.error"):
lg = logging.getLogger(name)
lg.handlers.clear()
lg.propagate = True
access = logging.getLogger("uvicorn.access")
access.handlers.clear()
access.propagate = False
access.disabled = True
file_handler.prune()
_file_handler = file_handler
return file_handler
def apply_retention_setting(db) -> None:
"""Read `system.log_retention_days` from the settings table and prune. Called at startup."""
if _file_handler is None:
return
from models.settings import PosSettings
try:
row = db.query(PosSettings).filter(PosSettings.key == "system.log_retention_days").first()
days = int(row.value) if row and row.value else DEFAULT_RETENTION_DAYS
except Exception:
days = DEFAULT_RETENTION_DAYS
_file_handler.retention_days = max(1, days)
_file_handler.prune()
# ── request middleware ───────────────────────────────────────────────────────
_http_log = logging.getLogger("xenia.http")
_SLOW_MS = 1000
class RequestContextMiddleware:
"""Pure ASGI middleware: gives each HTTP/WebSocket request an id, puts it in
the log context and the `X-Request-ID` response header, and logs one line
per HTTP request (INFO for writes, errors and slow requests; DEBUG for
ordinary reads, so polling doesn't flood the file)."""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] not in ("http", "websocket"):
return await self.app(scope, receive, send)
req_id = new_request_id()
token = _ctx.set({"req": req_id, "user": None, "device": None})
# Also on request.state: the last-resort error handler runs outside this middleware
scope.setdefault("state", {})["request_id"] = req_id
start = time.perf_counter()
status_holder = {"code": None}
async def send_wrapper(message):
if message["type"] == "http.response.start":
status_holder["code"] = message["status"]
headers = list(message.get("headers", []))
headers.append((b"x-request-id", req_id.encode()))
message = {**message, "headers": headers}
await send(message)
try:
await self.app(scope, receive, send_wrapper)
except Exception:
_http_log.exception("http.unhandled %s %s", scope.get("method", "WS"), scope.get("path"))
raise
finally:
if scope["type"] == "http":
ms = int((time.perf_counter() - start) * 1000)
code = status_holder["code"]
method = scope.get("method", "")
lvl = logging.DEBUG
if method not in ("GET", "HEAD", "OPTIONS") or (code or 500) >= 400 or ms >= _SLOW_MS:
lvl = logging.WARNING if (code or 500) >= 500 else logging.INFO
_http_log.log(lvl, "http %s %s status=%s ms=%d", method, scope.get("path"), code, ms)
_ctx.reset(token)
# ── download (plan step 2.6f) ────────────────────────────────────────────────
def log_dir() -> Path:
"""Where the daily files are: the active handler's folder, else the default."""
return _file_handler.directory if _file_handler is not None else default_log_dir()
def list_log_files(directory: Path | None = None) -> list[dict]:
"""[{date, name, size}] newest first, for the manager's log download."""
d = directory or log_dir()
out = []
if d.is_dir():
for f in d.glob(f"{FILE_PREFIX}*.log"):
m = _FILE_RE.match(f.name)
if m:
out.append({"date": m.group(1), "name": f.name, "size": f.stat().st_size})
return sorted(out, key=lambda x: x["date"], reverse=True)
def log_file_for(date_str: str, directory: Path | None = None) -> Path | None:
"""The file of one UTC day, or None (bad date or no file). Only names we write."""
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", date_str or ""):
return None
f = (directory or log_dir()) / f"{FILE_PREFIX}{date_str}.log"
return f if f.is_file() else None
+1
View File
@@ -0,0 +1 @@
"""Module system: manifests, registry, enablement, gating, workers (APPS_PLATFORM §4, §5.3, D-19)."""
+162
View File
@@ -0,0 +1,162 @@
"""Platform endpoints (APPS_PLATFORM §4.1, §7.2, §9): /api/platform/...
GET /bootstrap what every frontend loads first: venue (name, tz, language,
currency), the effective modules, the license state, the login
settings a login screen needs, and, if logged in, the user,
their language and permission keys. Works without login (login
screens need the venue language and zone).
GET /modules the full catalogue with each module's state (logged in).
PUT /modules/{key} enable/disable a module; applies at once (D-19).
Agent notes:
- `permissions` = the keys the caller holds (user_permissions; superadmin: all, D-7),
limited in bootstrap to effective modules.
- `approvable` = keys the caller lacks that a manager may approve (Perm overridable,
effective modules): the apps show those actions and let the approval dialog run (4.3).
- Access: PUT needs core.modules.manage (owner template).
- `entitled`/`entitlement`/limit `value` come from core/modules/entitlements.py (step 1.4).
"""
from __future__ import annotations
from core.access.deps import public
from typing import Optional
from fastapi import APIRouter, Depends, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel
from sqlalchemy.orm import Session
from core import i18n, timeutil
from core.modules import device_config, entitlements, state
from core.modules.registry import all_permissions, registry
from database import get_db
from core.access.deps import require
from routers.deps import get_current_user
router = APIRouter()
_optional_bearer = HTTPBearer(auto_error=False)
def permission_keys_for(user) -> list[str]:
"""The keys a user holds (user_permissions; superadmin: every key)."""
from core.access.check import user_keys
perms = all_permissions()
if getattr(user, "role", None) == "superadmin":
return sorted(perms)
return sorted(k for k in user_keys(user) if k in perms)
def _setting(db: Session, key: str, default: str) -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row and row.value else default
def _module_out(m, enabled: dict, effective: frozenset) -> dict:
ent = entitlements.current()
grant = ent.grants.get(m.key)
return {
"key": m.key, "kind": m.kind, "name": m.name, "description": m.description,
"depends": list(m.depends),
"entitled": grant is not None,
"entitlement": ({"source": grant.source, "exp": grant.exp, "exp_deferred": grant.exp_deferred}
if grant else None),
"enabled": enabled.get(m.key, True),
"effective": m.key in effective,
"can_disable": m.can_disable,
"permissions": [{"key": p.key, "description": p.description, "roles": list(p.roles),
"overridable": p.overridable} for p in m.permissions],
"limits": [{"key": lim.key, "description": lim.description, "free": lim.free,
"licensed_default": lim.licensed_default,
"value": ent.limit(m.key, lim.key)} for lim in m.limits],
"settings": [{"key": sd.key, "type": sd.type, "default": sd.default, "description": sd.description}
for sd in m.settings],
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope),
"config": device_config.describe(m.device_app.config)}
if m.device_app else None),
"workers": len(m.workers),
}
def _login_info(db: Session) -> dict:
from config import settings as cfg
from core import sessions
return {
"manager_mode": sessions.manager_login_mode(db), # password | pin
# the waiter app's sign-in (plan 4.2): pin | password | tap (tap = paired screens only:
# a phone shows that it can't sign in that way)
"waiter_mode": sessions.waiter_login_mode(db),
"waiter_require_username": sessions.waiter_requires_username(db),
"autofill_username": _setting(db, "security.autofill_username", "true") == "true",
"support": bool(cfg.SUPPORT_SECRET and cfg.SITE_ID), # "Support access" is offered
}
@router.get("/bootstrap", dependencies=[Depends(public())])
def bootstrap(
request: Request,
db: Session = Depends(get_db),
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer),
):
user = None
if credentials:
try:
user = get_current_user(request, credentials, db)
except Exception:
user = None # an expired/invalid token just means "not logged in" here
effective = state.effective_set(db)
out = {
"venue": {
"name": _setting(db, "venue.name", "") or None,
"timezone": timeutil.venue_tz().key,
"language": i18n.venue_language(),
"currency": _setting(db, "venue.currency", "EUR"),
"theme": _setting(db, "venue.theme", "amber") or "amber", # the accent colour (4.6, data-venue-theme)
"business_day_rollover_hour": timeutil.rollover_hour(),
},
"modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective],
"license": {"mode": entitlements.current().mode, "reason": entitlements.current().reason},
# what a login screen needs before anyone is signed in (plan step 2.6b)
"login": _login_info(db),
"languages": list(i18n.SUPPORTED_LANGUAGES),
"user": None,
"language": i18n.venue_language(),
"permissions": [],
"approvable": [],
}
if user is not None:
out["user"] = {"id": user.id, "username": user.username, "full_name": user.full_name,
"role": user.role, "language": getattr(user, "language", None)}
out["language"] = i18n.user_language(user)
out["permissions"] = [k for k in permission_keys_for(user)
if all_permissions()[k][1] in effective]
# keys the user lacks that a manager may approve on the spot (D-10): the apps offer
# those actions and the approval dialog does the rest (plan step 4.3)
held = set(out["permissions"])
out["approvable"] = sorted(k for k, (p, m) in all_permissions().items()
if p.overridable and m in effective and k not in held
and getattr(user, "role", None) != "superadmin")
return out
@router.get("/modules")
def list_modules(db: Session = Depends(get_db), user=Depends(get_current_user)):
enabled = state.enabled_map(db)
effective = state.effective_set(db)
return {"modules": [_module_out(m, enabled, effective) for m in registry().values()],
"permissions": permission_keys_for(user)}
class ModuleToggle(BaseModel):
enabled: bool
@router.put("/modules/{key}")
def set_module(key: str, body: ModuleToggle, db: Session = Depends(get_db),
user=Depends(require("core.modules.manage"))):
effective = state.set_enabled(db, key, body.enabled, user_id=getattr(user, "id", None) or None)
from services import ws_bus
ws_bus.notify_device(every_device=True) # paired screens re-read their app_status (3.1a)
enabled = state.enabled_map(db)
return _module_out(registry()[key], enabled, effective)
+136
View File
@@ -0,0 +1,136 @@
"""Per-device settings of an app (plan step 3.1a): what the manager may store in
devices.config and what the device reads back.
- validate(fields, config, db) -> dict | None: the cleaned config to store. Unknown keys,
wrong types, values outside choices/min/max and refs to missing rows raise
validation.device_config {key}. None/{} -> None (all defaults).
- effective(fields, stored, db=None) -> dict: every field, its stored value when still
valid, else its default. What GET /api/devices/me returns, so a screen never handles
a missing or stale value (an old free-form config, a prep zone that was deleted).
- for_app(app_key) -> the app's ConfigFields (from its manifest's DeviceApp.config).
Agent notes:
- Fields are declared in the app's manifest (core/modules/model.py ConfigField). A new
field needs its label in packages/i18n/locales/{en,el}/modules.json
(`<app>.config.<key>.label`, plus `.choices.<value>` per choice); test_module_texts fails
otherwise. The manager renders the fields generically (DeviceConfigFields.jsx).
- `ref` sources: "prep_zones" (PrepZone ids), "categories" (Category ids), "printers" (active
Printer ids), "devices:<app_key>" (live devices of that app).
- `color` = "#rrggbb" (lower-cased when stored). `after="<key>"` (int fields): the value must be
greater than that field's (stored or default) value, e.g. KDS age thresholds; a stored
config that breaks the order reads back as the defaults of every ordered field (3.2a).
- `group` only sections the manager's dialogs (modules:<app>.config_groups.<group>).
"""
from __future__ import annotations
import re
from core.errors import XeniaError
MAX_STR = 200
_COLOR = re.compile(r"^#[0-9a-fA-F]{6}$")
def for_app(app_key: str) -> tuple:
from core.access.context import device_app
da = device_app(app_key)
return tuple(da.config) if da else ()
def _bad(key: str):
return XeniaError("validation.device_config", key=key)
def _ref_exists(source: str, value: int, db) -> bool:
if source == "prep_zones":
from models.prep_zone import PrepZone
return db.get(PrepZone, value) is not None
if source == "categories":
from models.product import Category
return db.get(Category, value) is not None
if source == "printers":
from models.printer import Printer
p = db.get(Printer, value)
return p is not None and bool(p.is_active)
if source == "display_looks":
from models.display_look import DisplayLook
return db.get(DisplayLook, value) is not None
if source.startswith("devices:"):
from models.device import Device
d = db.get(Device, value)
return d is not None and d.revoked_at is None and d.app_key == source.split(":", 1)[1]
return False
def _clean(f, value, db, *, strict: bool):
"""The value as stored, or raise (strict) / return the default (not strict)."""
def bad():
if strict:
raise _bad(f.key)
return f.default
if f.type == "bool":
return value if isinstance(value, bool) else bad()
if f.type == "int":
if isinstance(value, bool) or not isinstance(value, int):
return bad()
if (f.choices and value not in f.choices) or (f.min is not None and value < f.min) \
or (f.max is not None and value > f.max):
return bad()
return value
if f.type == "str":
return value.strip() if isinstance(value, str) and len(value) <= MAX_STR else bad()
if f.type == "enum":
return value if value in f.choices else bad()
if f.type == "color":
return value.lower() if isinstance(value, str) and _COLOR.match(value) else bad()
if f.type == "ref":
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int):
return bad()
if db is not None and not _ref_exists(f.choices_from or "", value, db):
return bad()
return value
return bad()
def validate(fields, config, db) -> dict | None:
if config is None:
return None
if not isinstance(config, dict):
raise _bad("config")
by_key = {f.key: f for f in fields}
out = {}
for key, value in config.items():
f = by_key.get(key)
if f is None:
raise _bad(key)
out[key] = _clean(f, value, db, strict=True)
merged = {f.key: out.get(f.key, f.default) for f in fields}
for f in fields:
if f.after and not _ordered(f, merged):
raise _bad(f.key)
return out or None
def _ordered(f, values: dict) -> bool:
a, b = values.get(f.key), values.get(f.after)
return not (isinstance(a, int) and isinstance(b, int)) or a > b
def effective(fields, stored, db=None) -> dict:
stored = stored if isinstance(stored, dict) else {}
out = {f.key: (_clean(f, stored[f.key], db, strict=False) if f.key in stored else f.default) for f in fields}
ordered = [f for f in fields if f.after]
if any(not _ordered(f, out) for f in ordered):
for f in ordered:
out[f.key] = f.default
out[f.after] = next((g.default for g in fields if g.key == f.after), out[f.after])
return out
def describe(fields) -> list[dict]:
"""The fields for the manager (module catalogue)."""
return [{"key": f.key, "type": f.type, "default": f.default, "choices": list(f.choices),
"min": f.min, "max": f.max, "choices_from": f.choices_from, "group": f.group, "after": f.after}
for f in fields]
+178
View File
@@ -0,0 +1,178 @@
"""Which modules this site may use, and with which limits (APPS_PLATFORM D-3..D-6, §5.1).
effective = (entitled ∪ free tier) ∩ enabled (state.py adds "enabled" and deps)
Sources, decided by compute():
- LICENSE_MODE=off (config; dev and test machines only): every module, no limits.
- a valid v2 token and the global license says "licensed" (services/license.py::evaluate,
which already defers expiry/lock to the end of an open workday): the token's
`modules` map. A module with its own `exp` gets the same 5-day grace and is never
cut off while a workday is open. Plus the free tier for modules the token lacks.
- anything else (no token, bad token, expired after grace, inactive, locked, clock
tampering): the free tier only (core/modules/free_tier.py).
Core modules are always entitled.
Limits (D-6): limit(module, name) -> int | None (None = unlimited).
module from the token: token's limits[name], else the manifest's licensed_default
module only from the free tier: FREE_TIER[module]["limits"][name], else Limit.free
Limits restrict what is shown or used, never what is stored.
The current result is held in memory (set by cloud_sync.apply_license at startup, after
every heartbeat and at workday close). Tests call set_current(compute(...)) or set_dev().
"""
from __future__ import annotations
import logging
import threading
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from core.modules.free_tier import FREE_TIER
from core.timeutil import utcnow
from core.modules.registry import registry
logger = logging.getLogger("xenia.license")
MODULE_EXPIRY_GRACE = timedelta(days=5) # same as services/license.py EXPIRY_GRACE
@dataclass(frozen=True)
class Grant:
source: str # "license" | "free" | "dev" | "core"
limits: dict = field(default_factory=dict)
exp: str | None = None
exp_deferred: bool = False # past exp + grace, kept until the open workday closes
@dataclass(frozen=True)
class Entitlements:
mode: str # "dev" | "licensed" | "free"
grants: dict # {module key: Grant}
reason: str | None = None # why "free": unverified | expired | inactive | locked | clock
def entitled(self, key: str) -> bool:
return key in self.grants
def limit(self, module: str, name: str) -> int | None:
g = self.grants.get(module)
m = registry().get(module)
decl = next((lim for lim in m.limits if lim.key == name), None) if m else None
if g is None:
return 0
if g.source == "dev":
return None
if name in g.limits:
return g.limits[name]
if decl is None:
return None
return decl.free if g.source == "free" else decl.licensed_default
def _parse(dt):
from services.license import parse_dt
return parse_dt(dt)
def compute(payload: dict | None, licensed: bool, locked: bool, now: datetime, workday_open: bool,
problem: str | None = None) -> Entitlements:
reg = registry()
grants: dict[str, Grant] = {k: Grant("core") for k, m in reg.items() if m.kind == "core"}
def add_free():
for k, spec in FREE_TIER.items():
if k in reg and k not in grants:
grants[k] = Grant("free", dict(spec.get("limits", {})))
if payload is None or not licensed or locked:
add_free()
reason = "locked" if locked else (problem or ("unverified" if payload is None else "expired"))
return Entitlements("free", grants, reason)
for k, spec in (payload.get("modules") or {}).items():
if k not in reg:
logger.info("license.unknown_module key=%s (newer cloud catalogue?)", k)
continue
spec = spec or {}
exp = _parse(spec.get("exp"))
deferred = False
if exp is not None and now > exp + MODULE_EXPIRY_GRACE:
if not workday_open:
continue # this module's own license ran out
deferred = True # never cut off mid-service
if reg[k].kind == "core":
grants[k] = Grant("core", dict(spec.get("limits") or {}))
continue
grants[k] = Grant("license", dict(spec.get("limits") or {}),
exp.isoformat() if exp else None, deferred)
add_free()
return Entitlements("licensed", grants)
def dev() -> Entitlements:
return Entitlements("dev", {k: Grant("dev") for k in registry()})
# ── current state ────────────────────────────────────────────────────────────
_lock = threading.Lock()
_current: Entitlements | None = None
def current() -> Entitlements:
with _lock:
cur = _current
if cur is None:
# Before the first apply_license(): dev mode if configured, else the free tier.
from config import settings
cur = dev() if settings.LICENSE_MODE == "off" else compute(None, False, False, utcnow(), False)
return cur
def set_current(ent: Entitlements, notify: bool = True) -> None:
"""Install a new result; modules and workers follow at once if anything changed.
notify=False is for tests that have no database to re-read."""
global _current
with _lock:
changed = _current is None or _current.grants != ent.grants
_current = ent
if changed and notify:
logger.info("license.entitlements mode=%s modules=%d reason=%s", ent.mode, len(ent.grants), ent.reason)
from core.modules import state
state.notify()
def set_dev() -> None:
set_current(dev())
def reset() -> None:
global _current
with _lock:
_current = None
def limit(module: str, name: str) -> int | None:
return current().limit(module, name)
def history_floor(module: str) -> datetime | None:
"""Earliest moment `module` may show, from its `history_days` limit (D-6). None = no limit."""
days = limit(module, "history_days")
if days is None:
return None
return utcnow() - timedelta(days=days)
def clamp_start(start: datetime | None, module: str) -> datetime | None:
"""A lower time bound moved forward to the module's history floor (D-6)."""
floor = history_floor(module)
if floor is None:
return start
return floor if start is None or start < floor else start
def history_since(value, module: str) -> datetime | None:
"""API "from" value -> UTC lower bound, never older than the module allows (D-6).
No value and no limit -> None (no bound)."""
from core.timeutil import parse_api_datetime
return clamp_start(parse_api_datetime(value) if value else None, module)
+11
View File
@@ -0,0 +1,11 @@
"""The free tier (APPS_PLATFORM D-5): what a site gets with no valid license.
THE ONE PLACE to change what is free. Same shape as the license token's `modules` map:
{module key: {"limits": {...}}}. Core modules are always included.
Used from step 1.4 (entitlements): effective = (entitled ∪ FREE_TIER) ∩ enabled.
"""
FREE_TIER: dict[str, dict] = {
"core": {},
"catalog": {},
"history": {"limits": {"history_days": 31}},
}
+110
View File
@@ -0,0 +1,110 @@
"""What a module manifest is made of (APPS_PLATFORM §4.1, D-19).
A module = one thing the venue can have or not: a manager feature (tabs, CRM...), an
app a device runs (KDS, POS...), or an integration (caller ID, fiscal...). Everything
is a module, including `core`. Each one is described by modules/<key>/manifest.py,
which exports MODULE = Module(...).
Agent notes:
- Display text (name, descriptions) is the English source. The i18n key is derived:
module.<key>.name, perm.<perm key>, limit.<key>.<limit>, setting.<setting key>.
- `routers` lists Mounts: the module's existing router objects and their URL prefix.
main.py mounts every Mount from the registry; non-core mounts get
Depends(module_required(key)) so a disabled module answers `module.disabled`.
- `workers` are "package.module:function" strings naming async functions that run
forever. The supervisor imports and starts them while the module is effective and
cancels them when it isn't. Strings keep manifests cheap to import.
- `Perm(..., overridable=True)`: a user without the key gets access.override_possible
and can retry with a manager's one-time approval (core/access/override.py, D-10).
- Permission keys are "<module>.<area>.<action>" (or "<module>.<action>"). Role lists
are the default role template (superadmin always has every key, D-7, so it's
never listed).
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal, Optional
Kind = Literal["core", "feature", "app", "integration"]
SettingType = Literal["bool", "int", "str", "json", "enum"]
@dataclass(frozen=True)
class Perm:
key: str
description: str
roles: tuple[str, ...] = ()
overridable: bool = False # a manager may approve it once with their PIN (D-10)
@dataclass(frozen=True)
class Limit:
key: str
description: str
free: Optional[int] = 0 # value in the free tier (D-5); None = unlimited
licensed_default: Optional[int] = None # value when licensed but the token sets none; None = unlimited
@dataclass(frozen=True)
class SettingDef:
key: str
default: str # stored as text in pos_settings, like every setting
description: str
type: SettingType = "str"
choices: tuple[str, ...] = () # for type "enum"
ConfigType = Literal["bool", "int", "str", "enum", "ref", "color"]
@dataclass(frozen=True)
class ConfigField:
"""One setting of a device running an app (plan step 3.1a). Stored in devices.config,
validated by core/modules/device_config.py, edited in the manager's pair/edit dialogs.
Texts: modules:<app>.config.<key>.label (+ .hint optional, + .choices.<value> for each
choice, + .none for a ref's empty choice; groups: modules:<app>.config_groups.<group>),
checked by tests/test_module_texts.py."""
key: str
type: ConfigType
default: object = None
choices: tuple = () # enum, or int limited to these values
min: Optional[int] = None # int
max: Optional[int] = None # int
choices_from: Optional[str] = None # ref: "prep_zones" | "categories" | "printers" | "devices:<app_key>"; value = id or None
group: Optional[str] = None # section in the manager's dialogs (3.2a)
after: Optional[str] = None # int: must be greater than this other field (age thresholds)
@dataclass(frozen=True)
class DeviceApp:
"""For kind="app" modules that run on a paired device (step 1.8, D-8)."""
login_modes: tuple[str, ...] = ("pin", "tap", "password")
scope: tuple[str, ...] = () # permission-key patterns the device token may use
config: tuple[ConfigField, ...] = () # per-device settings (3.1a)
@dataclass(frozen=True)
class Mount:
module: str # python import path, e.g. "routers.tabs"
prefix: str # URL prefix, e.g. "/api/tabs"
attr: str = "router" # attribute holding the APIRouter
tags: tuple[str, ...] = ()
@dataclass(frozen=True)
class Module:
key: str
kind: Kind
name: str
description: str = ""
depends: tuple[str, ...] = ()
permissions: tuple[Perm, ...] = ()
limits: tuple[Limit, ...] = ()
settings: tuple[SettingDef, ...] = ()
device_app: Optional[DeviceApp] = None
routers: tuple[Mount, ...] = ()
workers: tuple[str, ...] = () # "package.module:async_function", imported when started
@property
def can_disable(self) -> bool:
return self.kind != "core"
+144
View File
@@ -0,0 +1,144 @@
"""Loads and validates every module manifest (APPS_PLATFORM §4.1).
registry() returns the validated, immutable catalogue, built once per process from
local_backend/modules/<key>/manifest.py. Any problem raises ManifestError at startup,
so a broken manifest never reaches a running site.
Checks: key format and folder name, kind, unique keys, dependencies exist and have no
cycles, permission keys prefixed by their module and unique, roles exist, limit keys
unique per module, setting keys unique across modules, every Mount importable and
claimed by exactly one module, device_app only on apps, workers given as "mod:func".
"""
from __future__ import annotations
import importlib
import pkgutil
import re
from functools import lru_cache
from pathlib import Path
from core.modules.model import Module
MODULES_DIR = Path(__file__).resolve().parents[2] / "modules"
_KEY = re.compile(r"^[a-z][a-z0-9_]*$")
_KINDS = {"core", "feature", "app", "integration"}
_LOGIN_MODES = {"pin", "password", "tap", "none"}
class ManifestError(ValueError):
pass
def _discover() -> list[Module]:
found = []
for info in pkgutil.iter_modules([str(MODULES_DIR)]):
if not info.ispkg:
continue
mod = importlib.import_module(f"modules.{info.name}.manifest")
m = getattr(mod, "MODULE", None)
if not isinstance(m, Module):
raise ManifestError(f"modules/{info.name}/manifest.py must define MODULE = Module(...)")
if m.key != info.name:
raise ManifestError(f"modules/{info.name}: MODULE.key is {m.key!r}, must equal the folder name")
found.append(m)
return found
def validate(modules: list[Module], check_imports: bool = True) -> dict[str, Module]:
from roles import VALID_ROLES
by_key: dict[str, Module] = {}
perm_keys: set[str] = set()
setting_keys: dict[str, str] = {}
mounts: dict[tuple[str, str], str] = {}
for m in modules:
where = f"module {m.key!r}"
if not _KEY.match(m.key):
raise ManifestError(f"{where}: key must match {_KEY.pattern}")
if m.key in by_key:
raise ManifestError(f"{where}: duplicate key")
if m.kind not in _KINDS:
raise ManifestError(f"{where}: kind {m.kind!r} not in {sorted(_KINDS)}")
if m.device_app and m.kind != "app":
raise ManifestError(f"{where}: device_app is only for kind='app'")
if m.device_app:
bad_modes = set(m.device_app.login_modes) - _LOGIN_MODES
if not m.device_app.login_modes or bad_modes:
raise ManifestError(f"{where}: device_app.login_modes must be a non-empty subset of {sorted(_LOGIN_MODES)}")
if set(m.device_app.login_modes) - {"none"} and f"{m.key}.access" not in {p.key for p in m.permissions}:
raise ManifestError(f"{where}: a device app with user logins must declare the permission "
f"'{m.key}.access' (who may log in on its devices)")
for p in m.permissions:
if not p.key.startswith(m.key + "."):
raise ManifestError(f"{where}: permission {p.key!r} must start with {m.key + '.'!r}")
if p.key in perm_keys:
raise ManifestError(f"{where}: duplicate permission {p.key!r}")
perm_keys.add(p.key)
bad = set(p.roles) - (set(VALID_ROLES) - {"superadmin"})
if bad:
raise ManifestError(f"{where}: permission {p.key!r} has unknown roles {sorted(bad)} "
"(superadmin is implicit and never listed)")
limit_keys = [lim.key for lim in m.limits]
if len(limit_keys) != len(set(limit_keys)):
raise ManifestError(f"{where}: duplicate limit keys")
for sd in m.settings:
if sd.key in setting_keys:
raise ManifestError(f"{where}: setting {sd.key!r} already declared by {setting_keys[sd.key]!r}")
if sd.type == "enum" and sd.default not in sd.choices:
raise ManifestError(f"{where}: setting {sd.key!r} default not in choices")
setting_keys[sd.key] = m.key
for mt in m.routers:
ident = (mt.module, mt.attr)
if ident in mounts:
raise ManifestError(f"{where}: router {mt.module}.{mt.attr} already mounted by {mounts[ident]!r}")
mounts[ident] = m.key
if check_imports:
try:
obj = getattr(importlib.import_module(mt.module), mt.attr)
except (ImportError, AttributeError) as e:
raise ManifestError(f"{where}: cannot import router {mt.module}.{mt.attr}: {e}") from e
if not hasattr(obj, "routes"):
raise ManifestError(f"{where}: {mt.module}.{mt.attr} is not an APIRouter")
for w in m.workers:
if ":" not in w:
raise ManifestError(f"{where}: worker {w!r} must be 'package.module:function'")
by_key[m.key] = m
for m in modules:
for d in m.depends:
if d not in by_key:
raise ManifestError(f"module {m.key!r}: depends on unknown module {d!r}")
# cycles
state: dict[str, int] = {}
def visit(k, path):
if state.get(k) == 1:
raise ManifestError(f"dependency cycle: {' -> '.join(path + [k])}")
if state.get(k) == 2:
return
state[k] = 1
for d in by_key[k].depends:
visit(d, path + [k])
state[k] = 2
for k in by_key:
visit(k, [])
return by_key
@lru_cache(maxsize=1)
def registry() -> dict[str, Module]:
"""The validated catalogue: {key: Module}, in discovery (alphabetical) order."""
return validate(_discover())
def setting_defs() -> dict:
"""{setting key: (SettingDef, module key)} across all modules."""
return {sd.key: (sd, m.key) for m in registry().values() for sd in m.settings}
def all_permissions() -> dict:
"""{permission key: (Perm, module key)} across all modules."""
return {p.key: (p, m.key) for m in registry().values() for p in m.permissions}
+168
View File
@@ -0,0 +1,168 @@
"""Which modules are on, right now (APPS_PLATFORM D-4, D-19, §5.3).
effective(m) = entitled(m) and enabled(m) and every dependency of m is effective
- enabled: the site_modules table (no row = enabled). Core modules are always enabled.
- entitled: from the license (step 1.4). Until then every module is entitled.
- The enabled map is cached in memory; set_enabled() updates the cache in the same
request, so a change applies at once, with no restart. Listeners (the worker
supervisor) are told about every change.
module_required(key) is the FastAPI dependency main.py adds to each non-core router.
Agent notes:
- Always change enablement through set_enabled(), never by writing SiteModule rows,
or the cache and the workers won't follow.
- Entitlement comes from core/modules/entitlements.py (license ∪ free tier, step 1.4).
A blocked request says why: module.not_licensed (402) before module.disabled (403).
"""
from __future__ import annotations
import logging
import threading
from typing import Callable
from fastapi import Depends, Request
from sqlalchemy.orm import Session
from core.errors import XeniaError
from core.modules.registry import registry
from database import get_db
logger = logging.getLogger("xenia.modules")
_lock = threading.Lock()
_enabled_cache: dict[str, bool] | None = None
_listeners: list[Callable[[frozenset[str]], None]] = []
def invalidate() -> None:
global _enabled_cache
with _lock:
_enabled_cache = None
def add_listener(fn: Callable[[frozenset[str]], None]) -> None:
"""fn(effective_keys) is called after every enablement change."""
_listeners.append(fn)
def _load(db: Session) -> dict[str, bool]:
from models.site_module import SiteModule
rows = {r.key: bool(r.enabled) for r in db.query(SiteModule).all()}
return {k: (True if m.kind == "core" else rows.get(k, True)) for k, m in registry().items()}
def enabled_map(db: Session | None = None) -> dict[str, bool]:
global _enabled_cache
with _lock:
cached = _enabled_cache
if cached is not None:
return cached
if db is None:
from database import SessionLocal
own = SessionLocal()
try:
loaded = _load(own)
finally:
own.close()
else:
loaded = _load(db)
with _lock:
_enabled_cache = loaded
return loaded
def _entitled(key: str) -> bool:
from core.modules import entitlements
return entitlements.current().entitled(key)
def notify() -> None:
"""Tell listeners (the worker supervisor) the effective set may have changed,
e.g. after the license was re-evaluated."""
eff = effective_set()
for fn in list(_listeners):
try:
fn(eff)
except Exception:
logger.exception("module listener failed")
def effective_set(db: Session | None = None) -> frozenset[str]:
reg = registry()
enabled = enabled_map(db)
memo: dict[str, bool] = {}
def eff(k: str) -> bool:
if k not in memo:
memo[k] = _entitled(k) and enabled.get(k, True) and all(eff(d) for d in reg[k].depends)
return memo[k]
return frozenset(k for k in reg if eff(k))
def is_effective(key: str, db: Session | None = None) -> bool:
return key in effective_set(db)
def set_enabled(db: Session, key: str, enabled: bool, user_id: int | None = None) -> frozenset[str]:
"""Enable/disable a module (commits). Returns the new effective set."""
from models.site_module import SiteModule
global _enabled_cache
reg = registry()
if key not in reg:
raise XeniaError("module.unknown", module=key)
if not reg[key].can_disable and not enabled:
raise XeniaError("module.cannot_disable", module=key)
row = db.get(SiteModule, key)
if row is None:
row = SiteModule(key=key)
db.add(row)
row.enabled = enabled
row.updated_by = user_id if user_id else None
db.commit()
loaded = _load(db)
with _lock:
_enabled_cache = loaded
eff = effective_set(db)
logger.info("module.%s key=%s by_user=%s effective=%d", "enabled" if enabled else "disabled", key, user_id, len(eff))
for fn in list(_listeners):
try:
fn(eff)
except Exception:
logger.exception("module listener failed")
return eff
def blocked_error(key: str, db: Session | None = None) -> XeniaError:
"""Why `key` isn't effective: not licensed (itself or a dependency) beats turned off."""
reg = registry()
seen, stack = set(), [key]
while stack:
k = stack.pop()
if k in seen:
continue
seen.add(k)
if not _entitled(k):
return XeniaError("module.not_licensed", module=k)
stack.extend(reg[k].depends)
enabled = enabled_map(db)
off = next((k for k in [key, *sorted(seen - {key})] if not enabled.get(k, True)), key)
return XeniaError("module.disabled", module=off)
def module_required(key: str):
"""FastAPI dependency: the endpoint answers `module.disabled` unless the module is effective."""
if key not in registry():
raise ValueError(f"module_required: unknown module {key!r}")
def _check(request: Request, db: Session = Depends(get_db)) -> None:
if not is_effective(key, db):
raise blocked_error(key, db)
# A paired device may only reach its own app's routes and its scope's (D-8)
from core.access.context import check_device_scope, current_device
check_device_scope(current_device(request, db), key)
_check.__name__ = f"module_required_{key}"
return _check
+85
View File
@@ -0,0 +1,85 @@
"""Starts and stops module workers as modules turn on and off (D-19).
A worker is an async function named in a manifest ("package.module:function") that runs
forever. While its module is effective it runs as an asyncio task; when the module stops
being effective the task is cancelled. Enablement changes arrive from request threads,
so reconcile() is scheduled onto the event loop thread-safely.
Agent notes:
- start(loop) is called once from main.py's lifespan, after the schema is ready.
- A worker that crashes is logged and restarted after a short pause (it must never take
the backend down, Rule 8).
"""
from __future__ import annotations
import asyncio
import importlib
import logging
from core.modules import state
from core.modules.registry import registry
logger = logging.getLogger("xenia.workers")
_loop: asyncio.AbstractEventLoop | None = None
_tasks: dict[str, asyncio.Task] = {} # "module:worker" -> task
RESTART_DELAY_S = 30
def _resolve(spec: str):
mod, func = spec.split(":", 1)
return getattr(importlib.import_module(mod), func)
async def _guarded(name: str, fn):
while True:
try:
await fn()
logger.warning("worker.exited name=%s (restarting in %ss)", name, RESTART_DELAY_S)
except asyncio.CancelledError:
raise
except Exception:
logger.exception("worker.crashed name=%s (restarting in %ss)", name, RESTART_DELAY_S)
await asyncio.sleep(RESTART_DELAY_S)
def _reconcile(effective: frozenset[str]) -> None:
wanted = {f"{m.key}:{w}": w for m in registry().values() if m.key in effective for w in m.workers}
for name in list(_tasks):
if name not in wanted:
_tasks.pop(name).cancel()
logger.info("worker.stopped name=%s", name)
for name, spec in wanted.items():
if name not in _tasks or _tasks[name].done():
_tasks[name] = asyncio.get_running_loop().create_task(_guarded(name, _resolve(spec)))
logger.info("worker.started name=%s", name)
def _on_change(effective: frozenset[str]) -> None:
if _loop is None or _loop.is_closed():
return
try:
running = asyncio.get_running_loop()
except RuntimeError:
running = None
if running is _loop:
_reconcile(effective)
else:
_loop.call_soon_threadsafe(_reconcile, effective)
def start(loop: asyncio.AbstractEventLoop) -> None:
global _loop
_loop = loop
state.add_listener(_on_change)
_reconcile(state.effective_set())
def running() -> list[str]:
return sorted(n for n, t in _tasks.items() if not t.done())
def stop_all() -> None:
for t in _tasks.values():
t.cancel()
_tasks.clear()
+139
View File
@@ -0,0 +1,139 @@
"""Platform notifications service (APPS_PLATFORM §10, plan step 1.11).
notify("license.limit_reached", "warning", "perm:core.modules.manage",
params={"module": "kds", "limit": "devices", "max": 2},
dedupe_key="license.limit_reached:kds:devices", ttl=timedelta(days=1))
- Text: i18n key `notification.<key>` + params (core/i18n/en.json, el.json). Add both.
- Audience: "all_managers" | "perm:<permission key>" | "user:<id>". Superadmins see every
perm/all_managers notification (they hold every key).
- Dedupe: while a row with the same dedupe_key is live (not expired), a repeat only
bumps its count / last_at (fold=True) or does nothing (fold=False). Repeats don't
mark it unread again and send no event, so a refusal on every request can't spam.
- After a NEW notification, WS event `platform_notification` {id} goes to the audience (ids only,
CS-2). The current waiter app and manager ignore it on purpose; the phase 2 manager
shell shows it.
- Safe to call from background threads: pass db=None and it uses its own session.
It never raises: a notification must not break the action that produced it.
"""
from __future__ import annotations
import logging
from datetime import datetime, timedelta
from core.timeutil import utcnow
logger = logging.getLogger("xenia.notifications")
SEVERITIES = ("info", "warning", "critical")
EVENT = "platform_notification"
def _audience_ok(audience: str) -> bool:
if audience == "all_managers":
return True
kind, _, value = audience.partition(":")
if kind == "user":
return value.isdigit()
if kind == "perm":
from core.modules.registry import all_permissions
return value in all_permissions()
return False
def recipients(db, audience: str) -> list[int]:
"""User ids (active) the audience currently means."""
from core.access.queries import users_with_key
if audience.startswith("user:"):
return [int(audience[5:])]
key = "core.dashboard.access" if audience == "all_managers" else audience[5:]
return [u.id for u in users_with_key(db, key)]
def visible_filter(user):
"""SQLAlchemy filter: notifications this user may see (audience only, not expiry)."""
from sqlalchemy import or_
from core.access.check import holds, user_keys
from core.modules.registry import all_permissions
from models.notification import Notification
if getattr(user, "role", None) == "superadmin":
keys = set(all_permissions())
else:
keys = set(user_keys(user))
conds = [Notification.audience == f"user:{user.id}"]
if keys:
conds.append(Notification.audience.in_([f"perm:{k}" for k in keys]))
if holds(user, "core.dashboard.access"):
conds.append(Notification.audience == "all_managers")
return or_(*conds)
def notify(key: str, severity: str, audience: str, params: dict | None = None, *, dedupe_key: str | None = None,
ttl: timedelta | None = None, expires_at: datetime | None = None, fold: bool = True, db=None):
"""Create (or fold into a live duplicate) a notification. Returns its id, or None on error."""
from models.notification import Notification
own = db is None
if own:
from database import SessionLocal
db = SessionLocal()
try:
if severity not in SEVERITIES or not _audience_ok(audience):
raise ValueError(f"bad notification severity/audience: {severity!r} {audience!r}")
now = utcnow()
row = None
if dedupe_key:
row = db.query(Notification).filter(
Notification.dedupe_key == dedupe_key,
(Notification.expires_at.is_(None)) | (Notification.expires_at > now),
).order_by(Notification.id.desc()).first()
if row is not None:
if not fold:
return row.id
row.count += 1
row.last_at = now
row.params = params or row.params
db.commit()
return row.id
else:
row = Notification(key=key, severity=severity, audience=audience, params=params or {},
dedupe_key=dedupe_key, created_at=now, last_at=now,
expires_at=expires_at or (now + ttl if ttl else None))
db.add(row)
db.commit()
logger.info("notification.created id=%s key=%s audience=%s", row.id, key, audience)
try:
from services.ws_bus import broadcast_sync
broadcast_sync(EVENT, {"id": row.id}, user_ids=recipients(db, audience))
except Exception:
logger.exception("notification.event_failed id=%s", row.id)
return row.id
except Exception:
logger.exception("notification.failed key=%s audience=%s", key, audience)
try:
db.rollback()
except Exception:
pass
return None
finally:
if own:
db.close()
# ── producers that need a little logic ───────────────────────────────────────
EXPIRY_WARN_DAYS = (14, 7, 3, 1)
def check_license_expiry(expires_at: str | None, days_until: int | None, licensed: bool, db=None) -> None:
"""license.expiring at 14/7/3/1 days before the license's expiry, once per step."""
if not licensed or days_until is None or days_until < 0 or days_until > EXPIRY_WARN_DAYS[0] or not expires_at:
return
step = min(d for d in EXPIRY_WARN_DAYS if d >= max(days_until, 1))
from core.timeutil import parse_api_datetime
try:
end = parse_api_datetime(expires_at)
except Exception:
end = None
notify("license.expiring", "critical" if step <= 3 else "warning", "perm:core.modules.manage",
{"days": days_until, "expires_at": expires_at},
dedupe_key=f"license.expiring:{expires_at[:10]}:{step}", expires_at=end, fold=False, db=db)
+87
View File
@@ -0,0 +1,87 @@
"""Sales points (plan phase 3S, step S.1): where an order is sold. A fixed list in code.
Every order records its sales point (`orders.sales_point`); a product says where it's sold
(`products.sold_at`); prices for a sales point are price modifiers with the condition
`order_channel` (its `channels` param holds sales points). Labels live in the i18n packages
(`common:salesPoints.<key>`).
in_store the counter and the waiters, eating in
in_store_takeaway the counter, to take away (and phone orders delivered by the venue)
qr_table the QR menu, ordering at the table
online_takeaway online ordering, collected at the venue
online_delivery online ordering, delivered
online_preorder online reservation with food ready on arrival
"""
from __future__ import annotations
import json
IN_STORE = "in_store"
IN_STORE_TAKEAWAY = "in_store_takeaway"
QR_TABLE = "qr_table"
ONLINE_TAKEAWAY = "online_takeaway"
ONLINE_DELIVERY = "online_delivery"
ONLINE_PREORDER = "online_preorder"
ALL: tuple[str, ...] = (IN_STORE, IN_STORE_TAKEAWAY, QR_TABLE, ONLINE_TAKEAWAY, ONLINE_DELIVERY, ONLINE_PREORDER)
IN_PERSON: tuple[str, ...] = (IN_STORE, IN_STORE_TAKEAWAY)
ONLINE: tuple[str, ...] = (ONLINE_TAKEAWAY, ONLINE_DELIVERY, ONLINE_PREORDER)
DIGITAL: tuple[str, ...] = (QR_TABLE,) + ONLINE # what the cloud's customer apps sell
# the order_channel condition's values before S.1 → sales points
LEGACY_CHANNELS: dict[str, tuple[str, ...]] = {
"pos": (IN_STORE,),
"takeaway": (IN_STORE_TAKEAWAY,),
"online": ONLINE,
"qr": (QR_TABLE,),
}
def normalize(values) -> list[str]:
"""Sales points from a list that may hold old channel names; unknown values dropped,
order kept, no duplicates."""
out: list[str] = []
for v in values or []:
for sp in (v,) if v in ALL else LEGACY_CHANNELS.get(v, ()):
if sp not in out:
out.append(sp)
return out
def for_order(order_type: str | None, source: str | None = None, online_order_type: str | None = None) -> str:
"""The sales point of an order from what older code records (type, source)."""
if source == "online":
if online_order_type == "delivery":
return ONLINE_DELIVERY
if online_order_type == "takeaway":
return ONLINE_TAKEAWAY
if online_order_type == "preorder":
return ONLINE_PREORDER
return QR_TABLE # the QR menu's table orders arrive as online "dine_in"
return IN_STORE_TAKEAWAY if order_type in ("takeaway", "delivery") else IN_STORE
def of_order(order) -> str:
return getattr(order, "sales_point", None) or for_order(order.order_type, order.source, order.online_order_type)
def sold_at(product) -> list[str]:
"""Where a product is sold (`products.sold_at`, JSON); missing or unreadable = everywhere."""
raw = getattr(product, "sold_at", None)
if raw is None:
return list(ALL)
try:
values = json.loads(raw) if isinstance(raw, str) else raw
except ValueError:
return list(ALL)
return normalize(values)
def is_sold_at(product, point: str) -> bool:
return point in sold_at(product)
def dump(values) -> str:
"""For `products.sold_at`: the sales points in the fixed order."""
chosen = set(normalize(values))
return json.dumps([sp for sp in ALL if sp in chosen])
+64
View File
@@ -0,0 +1,64 @@
"""The one way the local database schema is created and upgraded: Alembic (APPS_PLATFORM D-13).
v1 used SQLAlchemy create_all + a list of ALTER TABLE statements in
main.py::_run_migrations(). That list is gone on platform-v2. Every schema
change is now an Alembic revision in local_backend/migrations/versions/, and the
guard test tests/guards/test_migrations.py fails if models and revisions drift.
Agent notes:
- Call upgrade_to_head() at startup (main.py lifespan), in seed/wipe scripts and
in tests. Never use SQLAlchemy create_all (a guard test fails on it).
- A v1 database (tables but no alembic_version) is refused with a clear error:
v2 never reads v1 databases; history comes over via tools/migrate_v1.py (D-21).
"""
from __future__ import annotations
import logging
from pathlib import Path
from alembic import command
from alembic.config import Config
from sqlalchemy import inspect
logger = logging.getLogger("xenia.schema")
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
class V1DatabaseError(RuntimeError):
pass
def alembic_config(connection=None) -> Config:
cfg = Config()
cfg.set_main_option("script_location", str(MIGRATIONS_DIR))
cfg.set_main_option("file_template", "%%(rev)s") # same as alembic.ini: file name = revision id
if connection is not None:
cfg.attributes["connection"] = connection
return cfg
def _refuse_v1(connection) -> None:
tables = set(inspect(connection).get_table_names())
if tables and "alembic_version" not in tables:
raise V1DatabaseError(
"This database was created by Xenia v1 (it has tables but no alembic_version). "
"Platform v2 does not open v1 databases. Start with an empty data folder and "
"import the history with tools/migrate_v1.py (APPS_PLATFORM D-21, section 11)."
)
def upgrade_to_head(engine=None) -> None:
"""Create or upgrade the schema to the newest revision."""
if engine is None:
from database import engine as app_engine
engine = app_engine
with engine.begin() as conn:
_refuse_v1(conn)
command.upgrade(alembic_config(conn), "head")
logger.info("schema.upgraded head=%s", current_head())
def current_head() -> str:
from alembic.script import ScriptDirectory
return ScriptDirectory.from_config(alembic_config()).get_current_head()
+235
View File
@@ -0,0 +1,235 @@
"""Login sessions and login modes (APPS_PLATFORM D-8, D-9, §6.2, §6.4).
Sessions
- start(db, user, client, request) creates a row and applies the client's single-session
rule (setting auth.single_session_<client>: off | refuse_new | end_old).
- validate(sid) is called on every authenticated request (routers.deps.decode_token).
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.
- 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)
- auth.manager_login_mode: password | pin (manager in a browser: never tap/none, D-8)
- auth.waiter_login_mode: pin | password | tap (tap needs a paired device: step 1.8)
- auth.waiter_require_username: the waiter must type their username, not just pick a name
Agent notes:
- Clients: "manager", "waiter", "terminal" (a user on a paired device, step 1.8; the row's
device_id binds it to that device, and a new login on the device replaces the old one),
"support" (1.10).
- Never trust a JWT alone: always go through validate().
- Ending a session also closes its live sockets (services.ws_bus.end_session, plan 3.1a).
"""
from __future__ import annotations
import logging
import threading
import time
import uuid
from datetime import timedelta
from typing import NamedTuple, Optional
from core.errors import XeniaError
from core.timeutil import utcnow
logger = logging.getLogger("xenia.sessions")
CLIENTS = ("manager", "waiter", "terminal", "support")
CACHE_TTL_S = 10
LAST_SEEN_EVERY_S = 60
_lock = threading.Lock()
class Active(NamedTuple):
"""What validate() knows about an active session."""
user_id: Optional[int] # None = the support account
device_id: Optional[int] # set for terminal sessions: the device they belong to
expires_at: Optional[object] = None # hard end (support sessions); None = none
_cache: dict[str, tuple[float, Active]] = {} # sid -> (checked_at monotonic, info) for ACTIVE sessions
def _setting(db, key: str, default: str) -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row and row.value else default
def single_session_rule(db, client: str) -> str:
return _setting(db, f"auth.single_session_{client}", "off") if client in ("manager", "waiter") else "off"
# ── lifecycle ────────────────────────────────────────────────────────────────
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.
`device`: the paired device of a terminal login; its previous sessions are replaced
(a shared screen shows one user at a time)."""
from models.session import LoginSession
if client not in CLIENTS:
raise ValueError(f"unknown client {client!r}")
user_id = getattr(user, "id", None) or None
rule = single_session_rule(db, client)
if user_id is not None and rule != "off":
active = db.query(LoginSession).filter(LoginSession.user_id == user_id, LoginSession.client == client,
LoginSession.ended_at.is_(None)).all()
if active and rule == "refuse_new":
raise XeniaError("auth.session_exists", client=client)
for s in active:
_end_row(s, "replaced")
if device is not None:
for s in db.query(LoginSession).filter(LoginSession.device_id == device.id, LoginSession.ended_at.is_(None)):
_end_row(s, "replaced")
now = utcnow()
row = LoginSession(id=uuid.uuid4().hex, user_id=user_id, client=client, created_at=now, last_seen_at=now,
device_id=(device.id if device is not None else None), expires_at=expires_at,
ip=(request.client.host if request is not None and request.client else None),
user_agent=(request.headers.get("user-agent", "")[:300] if request is not None else None))
db.add(row)
db.commit()
logger.info("session.started sid=%s user=%s client=%s rule=%s", row.id[:8], user_id, client, rule)
return row
def _end_row(row, reason: str) -> None:
row.ended_at = utcnow()
row.end_reason = reason
with _lock:
_cache.pop(row.id, None)
from services import ws_bus
ws_bus.end_session(row.id, reason) # its open sockets get session.ended and close (3.1a)
logger.info("session.ended sid=%s user=%s client=%s reason=%s", row.id[:8], row.user_id, row.client, reason)
def end(db, sid: str, reason: str) -> bool:
from models.session import LoginSession
row = db.get(LoginSession, sid)
if row is None or row.ended_at is not None:
return False
_end_row(row, reason)
db.commit()
return True
def end_for_user(db, user_id: int, reason: str) -> int:
from models.session import LoginSession
rows = db.query(LoginSession).filter(LoginSession.user_id == user_id, LoginSession.ended_at.is_(None)).all()
for r in rows:
_end_row(r, reason)
db.commit()
return len(rows)
def end_for_device(db, device_id: int, reason: str) -> int:
from models.session import LoginSession
rows = db.query(LoginSession).filter(LoginSession.device_id == device_id, LoginSession.ended_at.is_(None)).all()
for r in rows:
_end_row(r, reason)
db.commit()
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:
"""(user_id, device_id) of an active session. Raises auth.session_ended."""
if not sid:
raise XeniaError("auth.session_ended")
now_m = time.monotonic()
with _lock:
hit = _cache.get(sid)
if hit and now_m - hit[0] < CACHE_TTL_S and not (hit[1].expires_at and hit[1].expires_at <= utcnow()):
return hit[1]
from models.session import LoginSession
own = db is None
if own:
from database import SessionLocal
db = SessionLocal()
try:
row = db.get(LoginSession, sid)
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")
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:
with _lock:
_cache.pop(sid, None)
raise XeniaError("auth.session_ended")
info = Active(row.user_id, row.device_id, row.expires_at)
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
finally:
if own:
db.close()
if stale:
_touch(sid)
with _lock:
_cache[sid] = (now_m, info)
return info
def _touch(sid: str) -> None:
from database import SessionLocal
from models.session import LoginSession
s = SessionLocal()
try:
row = s.get(LoginSession, sid)
if row is not None and row.ended_at is None:
row.last_seen_at = utcnow()
s.commit()
except Exception:
logger.debug("session.touch_failed sid=%s", sid[:8], exc_info=True)
finally:
s.close()
def clear_cache() -> None:
with _lock:
_cache.clear()
# ── login modes ──────────────────────────────────────────────────────────────
def manager_login_mode(db) -> str:
v = _setting(db, "auth.manager_login_mode", "password")
return v if v in ("password", "pin") else "password"
def waiter_login_mode(db) -> str:
v = _setting(db, "auth.waiter_login_mode", "pin")
return v if v in ("pin", "password", "tap") else "pin"
def waiter_requires_username(db) -> bool:
return _setting(db, "auth.waiter_require_username", "false") == "true"
+55
View File
@@ -0,0 +1,55 @@
"""Support access codes (APPS_PLATFORM D-16, plan step 1.10). Standard library only.
Used by the backend (routers/auth.py) AND by the builder's tool tools/support_code.py,
which loads this file by path, so keep it free of backend imports.
master key (builder only, %USERPROFILE%\\.xenia\\support_master_key.txt)
└─ site secret = HMAC-SHA256(master, "xenia-support-site:" + site_id) -> hex, in the site .env as SUPPORT_SECRET
└─ code = base32(HMAC-SHA256(site secret, "xenia-support:" + site_id + ":" + challenge))[:10]
The site shows a random 8-character challenge (stored server-side for 15 min, single use);
the builder runs the tool with the site id and the challenge and reads back the code.
Works offline at the site: nothing but the two HMACs is needed. A code made for another
site never verifies (different secret, and the site id is in the message).
The test suite and tests/e2e (JS) re-implement these two functions; tests/test_support.py
pins a known vector so the implementations can't drift apart.
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import secrets
CHALLENGE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # read aloud / typed: no 0/O, 1/I
CHALLENGE_LEN = 8
CODE_LEN = 10
def site_secret(master_key: str, site_id: str) -> str:
return hmac.new(master_key.strip().encode(), f"xenia-support-site:{site_id}".encode(), hashlib.sha256).hexdigest()
def normalize_challenge(challenge: str) -> str:
return "".join(ch for ch in challenge.upper() if ch.isalnum())
def normalize_code(code: str) -> str:
# base32 (A-Z, 2-7): people read 0 as O, 1 as I and 8 as B
s = "".join(ch for ch in code.upper() if ch.isalnum())
return s.translate(str.maketrans({"0": "O", "1": "I", "8": "B"}))
def code_for(secret: str, site_id: str, challenge: str) -> str:
msg = f"xenia-support:{site_id}:{normalize_challenge(challenge)}".encode()
digest = hmac.new(secret.strip().encode(), msg, hashlib.sha256).digest()
return base64.b32encode(digest).decode()[:CODE_LEN]
def new_challenge() -> str:
return "".join(secrets.choice(CHALLENGE_ALPHABET) for _ in range(CHALLENGE_LEN))
def group(s: str, size: int) -> str:
""""ABCDEFGH" -> "ABCD-EFGH" (for display; input is normalized anyway)."""
return "-".join(s[i:i + size] for i in range(0, len(s), size))
+268
View File
@@ -0,0 +1,268 @@
"""The time model (APPS_PLATFORM D-11, §7). The ONLY place backend code gets "now" or converts zones.
Rules (a guard test enforces the mechanical ones, tests/guards/test_no_naive_time.py):
- A moment is an aware UTC datetime. Get "now" with utcnow(). Never datetime.now(),
datetime.utcnow(), date.today() or an argument-less .astimezone().
- Every datetime column is UTCDateTime: writing a naive datetime raises; reads come
back aware UTC. Pydantic then serialises them with "Z".
- The venue's zone is an IANA name in the `venue.timezone` setting (default
Europe/Athens). DST comes from the tz database (`tzdata` package).
- Clock rules (happy hour 17:00-19:00, schedules) are local wall-clock times,
evaluated in the venue zone: is_within(LocalClock(...), at_utc).
- A business day has a business_date, fixed when the day opens:
business_date_of(opened_at). A day opened before `business_day.rollover_hour`
(default 6) belongs to the previous date. Reports group by it.
- Durations are computed in UTC (end - start), never in local time.
- API input: parse_api_datetime(). A value WITH an offset is converted to UTC; a
naive value means venue-local wall time (that's what the manager's date pickers
send); a date-only value means venue midnight.
Agent notes:
- Settings are cached. The settings router calls invalidate() when venue.timezone
or business_day.rollover_hour changes, so a change applies live.
- Tests set the zone without a database: configure(tz="Europe/Athens", rollover_hour=6).
"""
from __future__ import annotations
import threading
from dataclasses import dataclass
from datetime import date, datetime, time, timedelta, timezone
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from sqlalchemy.types import DateTime, TypeDecorator
UTC = timezone.utc
DEFAULT_TZ = "Europe/Athens"
DEFAULT_ROLLOVER_HOUR = 6
DB_FORMAT = "%Y-%m-%d %H:%M:%S.%f" # how UTCDateTime values look in SQLite (and raw-SQL writers must match)
# ── now ──────────────────────────────────────────────────────────────────────
def utcnow() -> datetime:
"""The current moment, aware UTC. The only way to get "now"."""
return datetime.now(UTC)
def ensure_utc(dt: datetime | None) -> datetime | None:
"""Aware datetime -> same moment in UTC. Naive -> ValueError (we never guess)."""
if dt is None:
return None
if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:
raise ValueError(f"naive datetime refused (D-11): {dt!r}")
return dt.astimezone(UTC)
def iso_z(dt: datetime | None) -> str | None:
"""ISO-8601 in UTC with a Z, for hand-built JSON payloads."""
if dt is None:
return None
return ensure_utc(dt).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
def to_db_str(dt: datetime) -> str:
"""The storage text of a moment, for code that writes datetime columns with raw SQL."""
return ensure_utc(dt).strftime(DB_FORMAT)
# ── venue settings (cached) ──────────────────────────────────────────────────
_lock = threading.Lock()
_cache: dict = {}
def configure(tz: str | None = None, rollover_hour: int | None = None) -> None:
"""Set the cached values directly (tests, or a caller that already read the settings)."""
with _lock:
if tz is not None:
_cache["tz"] = ZoneInfo(tz)
if rollover_hour is not None:
_cache["rollover"] = int(rollover_hour)
def invalidate() -> None:
"""Forget cached settings; the next call re-reads them. Called when the settings change."""
with _lock:
_cache.clear()
def _read_setting(key: str) -> str | None:
try:
from database import SessionLocal
from models.settings import PosSettings
db = SessionLocal()
try:
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row and row.value else None
finally:
db.close()
except Exception:
return None
def validate_tz(name: str) -> ZoneInfo:
"""ZoneInfo for an IANA name, or ValueError."""
try:
return ZoneInfo(name)
except (ZoneInfoNotFoundError, ValueError, TypeError) as e:
raise ValueError(f"unknown time zone: {name!r}") from e
def venue_tz() -> ZoneInfo:
with _lock:
tz = _cache.get("tz")
if tz is None:
name = _read_setting("venue.timezone") or DEFAULT_TZ
try:
tz = validate_tz(name)
except ValueError:
tz = ZoneInfo(DEFAULT_TZ)
with _lock:
_cache["tz"] = tz
return tz
def rollover_hour() -> int:
with _lock:
h = _cache.get("rollover")
if h is None:
raw = _read_setting("business_day.rollover_hour")
try:
h = int(raw) if raw is not None else DEFAULT_ROLLOVER_HOUR
if not 0 <= h <= 23:
h = DEFAULT_ROLLOVER_HOUR
except ValueError:
h = DEFAULT_ROLLOVER_HOUR
with _lock:
_cache["rollover"] = h
return h
# ── conversions ──────────────────────────────────────────────────────────────
def to_venue(dt: datetime | None) -> datetime | None:
"""A moment in venue wall-clock time (aware, venue zone)."""
if dt is None:
return None
return ensure_utc(dt).astimezone(venue_tz())
def venue_now() -> datetime:
return utcnow().astimezone(venue_tz())
def venue_date(dt: datetime | None = None) -> date:
"""The venue's calendar date of a moment (default: now)."""
return to_venue(dt or utcnow()).date()
def venue_strftime(dt: datetime | None, fmt: str, empty: str = "—") -> str:
"""Format a moment in venue time (tickets, labels)."""
if dt is None:
return empty
return to_venue(dt).strftime(fmt)
def venue_local_to_utc(local: datetime) -> datetime:
"""Venue wall-clock time (naive) -> UTC. In the repeated autumn hour the first
occurrence is chosen (fold=0); a time skipped in spring maps forward."""
if local.tzinfo is not None:
return ensure_utc(local)
return local.replace(tzinfo=venue_tz()).astimezone(UTC)
def venue_day_window(d: date) -> tuple[datetime, datetime]:
"""[start, end) in UTC of venue calendar day d (23 h or 25 h on DST days)."""
return (venue_local_to_utc(datetime.combine(d, time.min)),
venue_local_to_utc(datetime.combine(d + timedelta(days=1), time.min)))
def parse_api_datetime(value: str | datetime | date | None) -> datetime | None:
"""API input -> aware UTC. With offset/Z: converted. Naive: venue-local. Date only: venue midnight."""
if value is None or value == "":
return None
if isinstance(value, datetime):
dt = value
elif isinstance(value, date):
dt = datetime.combine(value, time.min)
else:
s = str(value).strip().replace("Z", "+00:00").replace("z", "+00:00")
dt = datetime.fromisoformat(s)
if dt.tzinfo is None:
return venue_local_to_utc(dt)
return ensure_utc(dt)
# ── business date ────────────────────────────────────────────────────────────
def business_date_of(dt: datetime | None = None, rollover: int | None = None) -> date:
"""The business date a moment belongs to: venue date, minus one day before the rollover hour."""
local = to_venue(dt or utcnow())
h = rollover_hour() if rollover is None else rollover
d = local.date()
return d - timedelta(days=1) if local.hour < h else d
def business_date_window(d: date, rollover: int | None = None) -> tuple[datetime, datetime]:
"""[start, end) in UTC of business date d: venue d at rollover hour -> d+1 at rollover hour."""
h = rollover_hour() if rollover is None else rollover
return (venue_local_to_utc(datetime.combine(d, time(h))),
venue_local_to_utc(datetime.combine(d + timedelta(days=1), time(h))))
# ── clock rules ──────────────────────────────────────────────────────────────
@dataclass(frozen=True)
class LocalClock:
"""A wall-clock window in venue time, e.g. LocalClock("17:00", "19:00").
days: weekdays it applies to (Mon=0 ... Sun=6); None = every day. The day is the
one the window STARTS on, so 22:00-02:00 on Friday covers Saturday 01:00.
end <= start means the window crosses midnight. start == end means all day.
"""
start: str
end: str
days: frozenset[int] | None = None
def _t(self, s: str) -> time:
return time.fromisoformat(s)
def is_within(rule: LocalClock, at: datetime | None = None) -> bool:
"""True if moment `at` (default now) falls inside the venue-time window."""
local = to_venue(at or utcnow())
t, start, end = local.time().replace(tzinfo=None), rule._t(rule.start), rule._t(rule.end)
if start == end:
return rule.days is None or local.weekday() in rule.days
if start < end:
return start <= t < end and (rule.days is None or local.weekday() in rule.days)
# crosses midnight: evening part belongs to today, early part to yesterday's window
if t >= start:
return rule.days is None or local.weekday() in rule.days
if t < end:
return rule.days is None or (local.weekday() - 1) % 7 in rule.days
return False
# ── SQLAlchemy type ──────────────────────────────────────────────────────────
class UTCDateTime(TypeDecorator):
"""Every datetime column. Write: aware only (naive raises), stored as UTC text
'YYYY-MM-DD HH:MM:SS.ffffff'. Read: aware UTC."""
impl = DateTime
cache_ok = True
def process_bind_param(self, value, dialect):
if value is None:
return None
if not isinstance(value, datetime):
raise TypeError(f"UTCDateTime needs a datetime, got {type(value).__name__}")
return ensure_utc(value).replace(tzinfo=None)
def process_result_value(self, value, dialect):
if value is None:
return None
if value.tzinfo is None:
return value.replace(tzinfo=UTC)
return value.astimezone(UTC)
+16 -8
View File
@@ -28,6 +28,9 @@ import sys
from datetime import datetime, timedelta, date, timezone
import bcrypt
from core.timeutil import business_date_of, utcnow
from core.access.templates import apply_role_template
from sqlalchemy import text
from database import engine, Base, SessionLocal
@@ -56,7 +59,7 @@ import models.recovery_code # noqa: F401
from models.user import User, WaiterZone
from models.table import TableGroup, Table
from models.product import Category, Product
from models.product import Category, Product, ProductCategory
from models.order import Order, OrderItem, OrderWaiter, OrderAuditLog
from models.business_day import BusinessDay
from models.shift import WaiterShift
@@ -66,7 +69,8 @@ from models.customers import Customer
from models.tabs import Tab, TabEntry, TabPayment
from models.schedule import ScheduledShift
Base.metadata.create_all(bind=engine)
from core.schema import upgrade_to_head # noqa: E402
upgrade_to_head()
# ── Config ────────────────────────────────────────────────────────────────────
@@ -200,10 +204,11 @@ try:
username="manager",
pin_hash=_hash_pin("1234"),
password_hash=_hash_password("password"),
role="manager",
role="owner", # the demo "manager" can do everything, as in v1
full_name="Manager",
is_active=True,
)
apply_role_template(manager)
db.add(manager)
db.flush()
print(" created manager (username: manager / PIN: 1234 / password: password)")
@@ -226,6 +231,7 @@ try:
nickname=nickname,
is_active=True,
)
apply_role_template(w)
db.add(w)
db.flush()
waiters.append(w)
@@ -276,17 +282,18 @@ try:
cat_products = []
for prod_sort, (prod_name, prod_price, prod_cost) in enumerate(items):
p = db.query(Product).filter(Product.name == prod_name, Product.category_id == cat.id).first()
p = db.query(Product).filter(Product.name == prod_name, Product.primary_category_id == cat.id).first()
if not p:
p = Product(
name=prod_name,
category_id=cat.id,
primary_category_id=cat.id,
base_price=prod_price,
cost_simple=prod_cost,
is_available=True,
lifecycle_status="active",
sort_order=prod_sort,
)
p.memberships.append(ProductCategory(category_id=cat.id, sort_order=prod_sort))
db.add(p)
db.flush()
else:
@@ -355,7 +362,7 @@ try:
db.commit()
# ── Historical days ───────────────────────────────────────────────────────
today = datetime.now(timezone.utc).date()
today = utcnow().date()
total_orders = 0
total_revenue = 0.0
@@ -377,6 +384,7 @@ try:
bday = BusinessDay(
status="closed",
opened_at=open_time,
business_date=business_date_of(open_time),
opened_by_id=manager.id,
closed_at=close_time,
closed_by_id=manager.id,
@@ -716,7 +724,7 @@ try:
def _add_tab(customer, entries_desc, payments, is_closed=False):
"""entries_desc: list of (amount, description). payments: list of amounts."""
tab_opened = _utc(datetime.now(timezone.utc) - timedelta(days=random.randint(5, 30)))
tab_opened = _utc(utcnow() - timedelta(days=random.randint(5, 30)))
tab = Tab(
customer_id=customer.id,
status="closed" if is_closed else "open",
@@ -814,7 +822,7 @@ try:
is_done=is_done,
created_by_id=manager.id,
done_by_id=manager.id if is_done else None,
done_at=_utc(datetime.now(timezone.utc) - timedelta(days=2)) if is_done else None,
done_at=_utc(utcnow() - timedelta(days=2)) if is_done else None,
)
db.add(todo)
+70 -779
View File
@@ -1,747 +1,28 @@
"""Local backend entry point: logging, app, middleware, routers, startup.
Schema is created/upgraded only by Alembic (core/schema.py::upgrade_to_head, D-13).
The v1 create_all + _run_migrations() ALTER list was deleted in platform-v2 step 1.0.
"""
import os
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from database import engine, Base
from middleware.license_check import LicenseCheckMiddleware
from core.logging import setup_logging, apply_retention_setting, RequestContextMiddleware
# First thing: every logger below (and uvicorn's) writes through these handlers.
setup_logging()
logger = logging.getLogger("xenia.main")
from config import settings
from database import SessionLocal
from services.cloud_sync import start_cloud_sync
# Import all models so SQLAlchemy can create their tables
import models.user # noqa: F401 — also registers WaiterZone
import models.table # noqa: F401
import models.printer # noqa: F401
import models.product # noqa: F401
import models.order # noqa: F401 — also registers OrderAuditLog, OrderDiscount, PrintJob
import models.business_day # noqa: F401
import models.shift # noqa: F401 — registers WaiterShift, ShiftBreak
import models.settings # noqa: F401
import models.flag # noqa: F401 — registers TableFlagDef, TableFlagAssignment
import models.message # noqa: F401 — registers StaffMessage, StaffMessageAck, QuickMessageTemplate
import models.reservation # noqa: F401
import models.notes # noqa: F401 — registers SiteNote, SiteTodo
import models.expenses # noqa: F401 — registers Contact, Expense, ExpensePayment
import models.customers # noqa: F401 — registers Customer
import models.tabs # noqa: F401 — registers Tab, TabEntry, TabPayment
import models.waste # noqa: F401 — registers WasteLog
import models.schedule # noqa: F401 — registers ScheduledShift
import models.chat # noqa: F401 — registers Conversation, ConversationParticipant, ChatMessage
import models.prep_zone # noqa: F401 — registers PrepZone, prep_zone_printers, product_prep_zones
import models.pricing # noqa: F401 — registers PriceGroup, PriceModifier, Deal, PriceEventLog, WaiterDiscountSettings
import models.recovery_code # noqa: F401 — registers RecoveryCode
# Every model must be registered before the routers import them (see models/all.py).
import models.all # noqa: F401
from routers import auth, tables, products, orders, waiters, reports, system, setup as setup_router
from routers import business_day as business_day_router
from routers import shifts as shifts_router
from routers import settings as settings_router
from routers import flags as flags_router
from routers import messages as messages_router
from routers import sse as sse_router
from routers import ws as ws_router
from routers import data_transfer as data_transfer_router
from routers import connect_orders as connect_orders_router
from routers import reservations as reservations_router
from routers import notes as notes_router
from routers.expenses import contacts_router, expenses_router
from routers import customers as customers_router
from routers import tabs as tabs_router
from routers import waste as waste_router
from routers import kds as kds_router
from routers import schedule as schedule_router
from routers import chat as chat_router
from routers import prep_zones as prep_zones_router
from routers import pricing as pricing_router
from routers import fiscal as fiscal_router
from routers import phone as phone_router
from routers import recovery as recovery_router
def _run_migrations():
"""Apply additive schema changes that create_all won't handle.
Each migration gets its own connection so a no-op (column already exists)
doesn't leave a dirty transaction that blocks subsequent migrations."""
from sqlalchemy import text
migrations = [
"ALTER TABLE product_ingredients ADD COLUMN extra_cost REAL NOT NULL DEFAULT 0.0",
"ALTER TABLE products ADD COLUMN image_url VARCHAR",
"ALTER TABLE tables ADD COLUMN group_id INTEGER REFERENCES table_groups(id)",
"ALTER TABLE table_groups ADD COLUMN prefix VARCHAR",
"ALTER TABLE table_groups ADD COLUMN color VARCHAR",
"ALTER TABLE products ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_preference_sets ADD COLUMN default_choice_id INTEGER",
"ALTER TABLE product_preference_choices ADD COLUMN sub_choices TEXT",
"ALTER TABLE product_preference_choices ADD COLUMN disables_subset INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_preference_sets ADD COLUMN shared_subset TEXT",
"ALTER TABLE product_options ADD COLUMN sub_choices TEXT",
# Zone-based access control
"""CREATE TABLE IF NOT EXISTS waiter_zones (
id INTEGER PRIMARY KEY AUTOINCREMENT,
waiter_id INTEGER NOT NULL REFERENCES users(id),
group_id INTEGER REFERENCES table_groups(id),
assigned_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
# Payment tracking on items
"ALTER TABLE order_items ADD COLUMN paid_by INTEGER REFERENCES users(id)",
"ALTER TABLE order_items ADD COLUMN paid_at DATETIME",
"ALTER TABLE order_items ADD COLUMN payment_method VARCHAR",
# Full audit log
"""CREATE TABLE IF NOT EXISTS order_audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
order_id INTEGER NOT NULL REFERENCES orders(id),
event_type VARCHAR NOT NULL,
waiter_id INTEGER REFERENCES users(id),
item_ids TEXT,
amount REAL,
payment_method VARCHAR,
note TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
# Waiter profile fields
"ALTER TABLE users ADD COLUMN full_name VARCHAR",
"ALTER TABLE users ADD COLUMN nickname VARCHAR",
"ALTER TABLE users ADD COLUMN mobile_phone VARCHAR",
"ALTER TABLE users ADD COLUMN avatar_url VARCHAR",
# Quick options (flat, allow_multiple)
"""CREATE TABLE IF NOT EXISTS product_quick_options (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER NOT NULL REFERENCES products(id),
name VARCHAR NOT NULL,
price REAL NOT NULL DEFAULT 0.0,
allow_multiple INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0
)""",
# allow_multiple flag on extras (product_options)
"ALTER TABLE product_options ADD COLUMN allow_multiple INTEGER NOT NULL DEFAULT 0",
# Discounts table (future-proofed, schema ready now)
"""CREATE TABLE IF NOT EXISTS order_discounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
order_id INTEGER NOT NULL REFERENCES orders(id),
item_id INTEGER REFERENCES order_items(id),
discount_type VARCHAR NOT NULL,
discount_value REAL NOT NULL,
applied_by INTEGER NOT NULL REFERENCES users(id),
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP,
reason TEXT
)""",
# Business day scoping on orders
"ALTER TABLE orders ADD COLUMN business_day_id INTEGER REFERENCES business_days(id)",
# Shift attribution on paid items
"ALTER TABLE order_items ADD COLUMN paid_in_shift_id INTEGER REFERENCES waiter_shifts(id)",
# Seed default POS settings (INSERT OR IGNORE = no-op if already exists)
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('shifts.waiter_self_start', 'true', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('shifts.waiter_self_end', 'true', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('business_day.force_close_allowed', 'true', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('flags.display_mode', 'both', CURRENT_TIMESTAMP)",
# Table flags
"""CREATE TABLE IF NOT EXISTS table_flag_defs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR NOT NULL,
emoji VARCHAR,
color VARCHAR DEFAULT '#6b7280',
text_color VARCHAR DEFAULT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
is_active INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
# Migration: add text_color if upgrading from older schema
"ALTER TABLE table_flag_defs ADD COLUMN text_color VARCHAR DEFAULT NULL",
"""CREATE TABLE IF NOT EXISTS table_flag_assignments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
table_id INTEGER NOT NULL REFERENCES tables(id),
flag_id INTEGER NOT NULL REFERENCES table_flag_defs(id),
assigned_at DATETIME DEFAULT CURRENT_TIMESTAMP,
assigned_by INTEGER REFERENCES users(id)
)""",
# Staff messaging
"""CREATE TABLE IF NOT EXISTS quick_message_templates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
body VARCHAR NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
is_active INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
"""CREATE TABLE IF NOT EXISTS staff_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sender_id INTEGER NOT NULL REFERENCES users(id),
body TEXT NOT NULL,
target_waiter_ids TEXT NOT NULL DEFAULT '[]',
table_ids TEXT NOT NULL DEFAULT '[]',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
"""CREATE TABLE IF NOT EXISTS staff_message_acks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message_id INTEGER NOT NULL REFERENCES staff_messages(id),
waiter_id INTEGER NOT NULL REFERENCES users(id),
acked_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
# Seed default flag definitions
"INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (1, 'Χρειάζεται καθάρισμα', '🧹', '#ef4444', 1)",
"INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (2, 'Χρειάζεται Βοήθεια', '🆘', '#f97316', 2)",
"INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (3, 'Χρειάζεται Σερβιτόρο', '🔔', '#eab308', 3)",
"INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (4, 'Περιμένει να πληρώσει', '💳', '#3b82f6', 4)",
"INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (5, 'VIP', '⭐', '#8b5cf6', 5)",
"INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (6, 'Ευγενικός Πελάτης', '😊', '#22c55e', 6)",
"INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (7, 'Αγενής Πελάτης', '😤', '#dc2626', 7)",
"INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (8, 'Αλλεργίες', '⚠️', '#f59e0b', 8)",
"INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (9, 'Παιδιά στο τραπέζι', '👶', '#06b6d4', 9)",
"INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (10, 'Επέτειος / Γενέθλια', '🎂', '#ec4899', 10)",
# Seed default quick message templates
"INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (1, 'Σε χρειάζομαι τώρα', 1)",
"INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (2, 'Πάρε διάλειμμα', 2)",
"INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (3, 'Ετοιμάσου για κλείσιμο', 3)",
"INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (4, 'Ήρθε νέος πελάτης', 4)",
"INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (5, 'Ο πελάτης περιμένει να πληρώσει', 5)",
# Product lifecycle status (active / archived)
"ALTER TABLE products ADD COLUMN lifecycle_status VARCHAR NOT NULL DEFAULT 'active'",
# Favorite flags + ordering on all product sub-item types
"ALTER TABLE product_quick_options ADD COLUMN is_favorite INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_quick_options ADD COLUMN favorite_sort_order INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_options ADD COLUMN is_favorite INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_options ADD COLUMN favorite_sort_order INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_ingredients ADD COLUMN is_favorite INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_ingredients ADD COLUMN favorite_sort_order INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_preference_sets ADD COLUMN is_favorite INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_preference_sets ADD COLUMN favorite_sort_order INTEGER NOT NULL DEFAULT 0",
# Sub-category support
"ALTER TABLE categories ADD COLUMN parent_id INTEGER REFERENCES categories(id)",
"ALTER TABLE categories ADD COLUMN general_sort_order INTEGER NOT NULL DEFAULT 0",
# Auto-expand flag for sub-categories on the PWA accordion
"ALTER TABLE categories ADD COLUMN auto_expanded INTEGER NOT NULL DEFAULT 0",
# Printer protocol field
"ALTER TABLE printers ADD COLUMN protocol VARCHAR NOT NULL DEFAULT 'escpos_tcp'",
# Compact (half-width) display flag for quick options
"ALTER TABLE product_quick_options ADD COLUMN is_compact INTEGER NOT NULL DEFAULT 0",
# Print layout + per-type font settings
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.ticket_mode', 'detailed', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_order_number', '48:1:0', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_meta', '0:0:0', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_item_name', '16:1:0', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_quick', '0:0:0', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_pref', '0:0:0', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_extra', '0:0:0', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_ingredient', '0:0:0', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_item_note', '0:0:0', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_order_note', '0:1:0', CURRENT_TIMESTAMP)",
# Offline/emergency payment tracking
"ALTER TABLE order_audit_log ADD COLUMN offline_uuid VARCHAR",
"ALTER TABLE order_audit_log ADD COLUMN offline_at VARCHAR",
"ALTER TABLE order_audit_log ADD COLUMN is_duplicate INTEGER NOT NULL DEFAULT 0",
# Cancellation tracking on order items (for reports)
"ALTER TABLE order_items ADD COLUMN cancelled_by INTEGER REFERENCES users(id)",
"ALTER TABLE order_items ADD COLUMN cancel_reason TEXT",
"ALTER TABLE order_items ADD COLUMN cancelled_at DATETIME",
# Manager account fields (added for setup wizard / future password login)
"ALTER TABLE users ADD COLUMN password_hash VARCHAR",
"ALTER TABLE users ADD COLUMN email VARCHAR",
# Venue identity settings
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('venue.name', '', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('venue.type', '', CURRENT_TIMESTAMP)",
# Security settings
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.login_method', 'password', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.autofill_username', 'true', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_lock', 'false', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_lock_seconds', '300', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_logout', 'false', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_logout_seconds', '1800', CURRENT_TIMESTAMP)",
# Xenia Connect — online order fields on orders table
"ALTER TABLE orders ADD COLUMN source VARCHAR NOT NULL DEFAULT 'pos'",
"ALTER TABLE orders ADD COLUMN online_order_ref VARCHAR",
"ALTER TABLE orders ADD COLUMN online_order_cloud_id INTEGER",
"ALTER TABLE orders ADD COLUMN online_status VARCHAR",
"ALTER TABLE orders ADD COLUMN online_customer_name VARCHAR",
"ALTER TABLE orders ADD COLUMN online_customer_phone VARCHAR",
"ALTER TABLE orders ADD COLUMN online_customer_address TEXT",
"ALTER TABLE orders ADD COLUMN online_customer_notes TEXT",
"ALTER TABLE orders ADD COLUMN online_order_type VARCHAR",
# Xenia Connect — digital menu fields on products
"ALTER TABLE products ADD COLUMN digital_visible INTEGER NOT NULL DEFAULT 1",
"ALTER TABLE products ADD COLUMN digital_available INTEGER NOT NULL DEFAULT 1",
"ALTER TABLE products ADD COLUMN digital_name VARCHAR",
"ALTER TABLE products ADD COLUMN digital_description VARCHAR",
"ALTER TABLE products ADD COLUMN digital_price REAL",
"ALTER TABLE products ADD COLUMN digital_discount REAL NOT NULL DEFAULT 0.0",
"ALTER TABLE products ADD COLUMN digital_image_url VARCHAR",
# Per-printer line width (chars per line) — default 48 for 80mm Jolimark
"ALTER TABLE printers ADD COLUMN line_width INTEGER NOT NULL DEFAULT 48",
# Product description (plain-text, for menu display)
"ALTER TABLE products ADD COLUMN description TEXT",
# Staff note (internal memo on a waiter's profile)
"ALTER TABLE users ADD COLUMN note VARCHAR",
# Reservations table
"""CREATE TABLE IF NOT EXISTS reservations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guest_name VARCHAR NOT NULL,
party_size INTEGER NOT NULL,
phone VARCHAR,
email VARCHAR,
note TEXT,
reserved_for DATETIME NOT NULL,
table_id INTEGER REFERENCES tables(id),
status VARCHAR NOT NULL DEFAULT 'pending',
source VARCHAR NOT NULL DEFAULT 'manager_app',
created_by_user_id INTEGER REFERENCES users(id),
online_customer_id VARCHAR,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
# Product unit of measure (piece / portion / kg / liter / gram / ml)
"ALTER TABLE products ADD COLUMN unit_type VARCHAR NOT NULL DEFAULT 'piece'",
# Phase 2A — product cost tracking
"ALTER TABLE products ADD COLUMN cost_simple REAL",
"ALTER TABLE products ADD COLUMN cost_breakdown TEXT",
"ALTER TABLE order_items ADD COLUMN unit_cost REAL",
# Phase 2B — staff payroll
"ALTER TABLE users ADD COLUMN hourly_rate REAL",
"ALTER TABLE waiter_shifts ADD COLUMN hourly_rate_snapshot REAL",
# Phase 2J — staff shift scheduling
"""CREATE TABLE IF NOT EXISTS scheduled_shifts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id),
scheduled_date DATE NOT NULL,
start_time VARCHAR NOT NULL,
end_time VARCHAR NOT NULL,
notes TEXT,
created_by_id INTEGER NOT NULL REFERENCES users(id),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
# Phase 2H — void/waste log
"""CREATE TABLE IF NOT EXISTS waste_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER NOT NULL REFERENCES products(id),
quantity REAL NOT NULL,
unit_cost_snapshot REAL,
total_cost REAL,
reason VARCHAR NOT NULL,
reason_notes TEXT,
logged_by_id INTEGER NOT NULL REFERENCES users(id),
business_day_id INTEGER REFERENCES business_days(id),
logged_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
# Phase 2G — pay-later tab system
"""CREATE TABLE IF NOT EXISTS tabs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_id INTEGER NOT NULL REFERENCES customers(id),
status VARCHAR NOT NULL DEFAULT 'open',
opened_at DATETIME DEFAULT CURRENT_TIMESTAMP,
closed_at DATETIME,
closed_by_id INTEGER REFERENCES users(id),
notes TEXT
)""",
"""CREATE TABLE IF NOT EXISTS tab_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tab_id INTEGER NOT NULL REFERENCES tabs(id),
order_id INTEGER REFERENCES orders(id),
order_item_id INTEGER REFERENCES order_items(id),
amount REAL NOT NULL,
description TEXT,
created_by_id INTEGER NOT NULL REFERENCES users(id),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
"""CREATE TABLE IF NOT EXISTS tab_payments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tab_id INTEGER NOT NULL REFERENCES tabs(id),
amount REAL NOT NULL,
payment_method VARCHAR,
received_by_id INTEGER NOT NULL REFERENCES users(id),
notes TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
# Phase 2F — customer CRM
"""CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR NOT NULL,
nickname VARCHAR,
phone VARCHAR,
email VARCHAR,
notes TEXT,
is_active INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
created_by_id INTEGER NOT NULL REFERENCES users(id)
)""",
"ALTER TABLE orders ADD COLUMN customer_id INTEGER REFERENCES customers(id)",
# Phase 2E — cash drawer reconciliation
"ALTER TABLE waiter_shifts ADD COLUMN counted_cash_end REAL",
"ALTER TABLE waiter_shifts ADD COLUMN cash_discrepancy REAL",
"ALTER TABLE business_days ADD COLUMN store_opening_cash REAL",
"ALTER TABLE business_days ADD COLUMN store_closing_cash REAL",
"ALTER TABLE business_days ADD COLUMN store_cash_discrepancy REAL",
# Phase 2D — expense tracking + supplier contacts
"""CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR NOT NULL,
type VARCHAR NOT NULL DEFAULT 'supplier',
phone VARCHAR,
email VARCHAR,
address TEXT,
notes TEXT,
is_active INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
"""CREATE TABLE IF NOT EXISTS expenses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
description VARCHAR NOT NULL,
category VARCHAR NOT NULL,
contact_id INTEGER REFERENCES contacts(id),
total_amount REAL NOT NULL,
paid_amount REAL NOT NULL DEFAULT 0.0,
due_date DATETIME,
business_day_id INTEGER REFERENCES business_days(id),
created_by_id INTEGER NOT NULL REFERENCES users(id),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
notes TEXT
)""",
"""CREATE TABLE IF NOT EXISTS expense_payments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
expense_id INTEGER NOT NULL REFERENCES expenses(id),
amount REAL NOT NULL,
paid_at DATETIME DEFAULT CURRENT_TIMESTAMP,
paid_by_id INTEGER NOT NULL REFERENCES users(id),
notes TEXT
)""",
# Phase 2C — notes & todos
"""CREATE TABLE IF NOT EXISTS site_notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
body TEXT NOT NULL,
created_by_id INTEGER NOT NULL REFERENCES users(id),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
is_pinned INTEGER NOT NULL DEFAULT 0
)""",
"""CREATE TABLE IF NOT EXISTS site_todos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
body TEXT NOT NULL,
is_done INTEGER NOT NULL DEFAULT 0,
done_at DATETIME,
done_by_id INTEGER REFERENCES users(id),
created_by_id INTEGER NOT NULL REFERENCES users(id),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
priority VARCHAR NOT NULL DEFAULT 'normal'
)""",
# Printer duplicate copies (0 = print once, 1 = print twice, etc.)
"ALTER TABLE printers ADD COLUMN duplicates INTEGER NOT NULL DEFAULT 0",
# Waiter cancellation permissions
"ALTER TABLE users ADD COLUMN can_cancel_orders INTEGER NOT NULL DEFAULT 0",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.waiter_cancellations_allowed', 'false', CURRENT_TIMESTAMP)",
# KDS — kitchen display system status tracking
"ALTER TABLE orders ADD COLUMN kds_status VARCHAR NOT NULL DEFAULT 'pending'",
"ALTER TABLE orders ADD COLUMN order_type VARCHAR NOT NULL DEFAULT 'here'",
"ALTER TABLE order_items ADD COLUMN kds_status VARCHAR NOT NULL DEFAULT 'pending'",
# KDS notifications — message type + zone tagging on staff messages
"ALTER TABLE staff_messages ADD COLUMN message_type VARCHAR NOT NULL DEFAULT 'manager'",
"ALTER TABLE staff_messages ADD COLUMN kds_zone VARCHAR",
# Chat system
"""CREATE TABLE IF NOT EXISTS conversations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type VARCHAR NOT NULL DEFAULT 'direct',
name VARCHAR,
is_system INTEGER NOT NULL DEFAULT 0,
created_by INTEGER REFERENCES users(id),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
"""CREATE TABLE IF NOT EXISTS conversation_participants (
id INTEGER PRIMARY KEY AUTOINCREMENT,
conversation_id INTEGER NOT NULL REFERENCES conversations(id),
user_id INTEGER NOT NULL REFERENCES users(id),
joined_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_read_at DATETIME
)""",
"""CREATE TABLE IF NOT EXISTS chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
conversation_id INTEGER NOT NULL REFERENCES conversations(id),
sender_id INTEGER NOT NULL REFERENCES users(id),
body TEXT NOT NULL,
sent_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME
)""",
# Prep Zones — replaces per-product printer assignment
"""CREATE TABLE IF NOT EXISTS prep_zones (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR NOT NULL,
description VARCHAR
)""",
"""CREATE TABLE IF NOT EXISTS prep_zone_printers (
prep_zone_id INTEGER NOT NULL REFERENCES prep_zones(id),
printer_id INTEGER NOT NULL REFERENCES printers(id),
PRIMARY KEY (prep_zone_id, printer_id)
)""",
"""CREATE TABLE IF NOT EXISTS product_prep_zones (
product_id INTEGER NOT NULL REFERENCES products(id),
prep_zone_id INTEGER NOT NULL REFERENCES prep_zones(id),
PRIMARY KEY (product_id, prep_zone_id)
)""",
# KDS decline tracking on items
"ALTER TABLE order_items ADD COLUMN decline_note TEXT",
# Prep zone notification name
"ALTER TABLE prep_zones ADD COLUMN notification_name VARCHAR",
# KDS status change timestamp on orders (for "latest change" sorting in PWA)
"ALTER TABLE orders ADD COLUMN kds_status_changed_at DATETIME",
# Auto-close table after full payment setting
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.auto_close_on_full_payment', 'false', CURRENT_TIMESTAMP)",
# Quick Add: allow direct 1-unit add from product list without opening config modal
"ALTER TABLE products ADD COLUMN quick_add_enabled INTEGER NOT NULL DEFAULT 1",
# Per-waiter settings + favorites sync (JSON blob)
"ALTER TABLE users ADD COLUMN waiter_settings TEXT",
# Prep zone print settings — synced with KDS auto-print controls
"ALTER TABLE prep_zones ADD COLUMN auto_print VARCHAR NOT NULL DEFAULT 'none'",
"ALTER TABLE prep_zones ADD COLUMN print_copies INTEGER NOT NULL DEFAULT 1",
# Bypass KDS/serve flow: new orders immediately start as served
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.bypass_kds_serve', 'false', CURRENT_TIMESTAMP)",
# Prep zone: rename auto_print value 'primary' → 'master' for existing rows
"UPDATE prep_zones SET auto_print = 'master' WHERE auto_print = 'primary'",
# Prep zone: master printer (single FK) + per-role copy counts
"ALTER TABLE prep_zones ADD COLUMN master_printer_id INTEGER REFERENCES printers(id)",
"ALTER TABLE prep_zones ADD COLUMN master_copies INTEGER NOT NULL DEFAULT 1",
"ALTER TABLE prep_zones ADD COLUMN secondary_copies INTEGER NOT NULL DEFAULT 1",
# Prep zone: item sort / category grouping options
"ALTER TABLE prep_zones ADD COLUMN sort_items_by VARCHAR NOT NULL DEFAULT 'order_time'",
"ALTER TABLE prep_zones ADD COLUMN group_by_category INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE prep_zones ADD COLUMN category_order TEXT NOT NULL DEFAULT '[]'",
# Prep zone: ticket formatting option
"ALTER TABLE prep_zones ADD COLUMN print_checkboxes INTEGER NOT NULL DEFAULT 0",
# Prep zone: KDS bypass options
"ALTER TABLE prep_zones ADD COLUMN bypass_pending INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE prep_zones ADD COLUMN bypass_kds INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE prep_zones ADD COLUMN auto_ready_to_served INTEGER NOT NULL DEFAULT 0",
# Prep zone: migrate existing master_printer_id from first printer in zone (best-effort)
# (handled in Python at runtime, not SQL — no-op SQL here)
# Product tags (JSON array of strings)
"ALTER TABLE products ADD COLUMN tags TEXT",
# Hide revenue from waiters on shift overview
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('shifts.hide_revenue_from_waiters', 'false', CURRENT_TIMESTAMP)",
# WebSocket event log — append-only, pruned to 24h on startup
"""CREATE TABLE IF NOT EXISTS sync_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_type VARCHAR NOT NULL,
payload TEXT NOT NULL,
target_user_ids TEXT,
created_at VARCHAR NOT NULL
)""",
"CREATE INDEX IF NOT EXISTS ix_sync_events_created_at ON sync_events (created_at)",
# Migrate from legacy per-product printer to prep zones: clear old printer_zone_id
"UPDATE products SET printer_zone_id = NULL WHERE printer_zone_id IS NOT NULL",
# Per-printer ESC/POS code page index (n in ESC t n) — default 29 = CP737 on Jolimark
"ALTER TABLE printers ADD COLUMN codepage_n INTEGER NOT NULL DEFAULT 29",
# Price adjustment: per-item on-the-fly price delta (positive or negative)
"ALTER TABLE order_items ADD COLUMN price_adjustment REAL NOT NULL DEFAULT 0.0",
# Customer count: how many people are at the table for this order
"ALTER TABLE orders ADD COLUMN customer_count INTEGER",
# Service items: flag on products, these are non-inventoried table-service items
"ALTER TABLE products ADD COLUMN is_service_item INTEGER NOT NULL DEFAULT 0",
# Table seat count — physical seats at each table (foundation for per-seat dish assignment)
"ALTER TABLE tables ADD COLUMN seat_count INTEGER",
# Courses — optional course assignment for sequenced firing
"ALTER TABLE order_items ADD COLUMN course_id INTEGER",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.courses_enabled', 'false', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.courses', '[]', CURRENT_TIMESTAMP)",
# Print job lifecycle tracking — auto-retry system
"""CREATE TABLE IF NOT EXISTS print_jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
order_id INTEGER NOT NULL REFERENCES orders(id),
printer_id INTEGER NOT NULL REFERENCES printers(id),
zone_id INTEGER,
item_ids TEXT NOT NULL,
copies INTEGER NOT NULL DEFAULT 1,
status VARCHAR NOT NULL DEFAULT 'pending',
retry_count INTEGER NOT NULL DEFAULT 0,
first_attempted_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_attempted_at DATETIME,
succeeded_at DATETIME,
cancelled_at DATETIME,
cancel_reason VARCHAR
)""",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.waiter_price_adjust_allowed', 'false', CURRENT_TIMESTAMP)",
# Pricing system — Phase 2 pricing overhaul
"""CREATE TABLE IF NOT EXISTS price_groups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR NOT NULL,
description TEXT,
color VARCHAR,
is_active INTEGER NOT NULL DEFAULT 0,
auto_enable_time VARCHAR,
auto_disable_time VARCHAR,
auto_days TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
created_by INTEGER REFERENCES users(id)
)""",
"""CREATE TABLE IF NOT EXISTS price_modifiers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR NOT NULL,
description TEXT,
color VARCHAR,
is_active INTEGER NOT NULL DEFAULT 1,
is_favorite INTEGER NOT NULL DEFAULT 0,
allow_stack INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
scope VARCHAR NOT NULL DEFAULT 'global',
item_id INTEGER REFERENCES products(id),
action_type VARCHAR NOT NULL,
action_value REAL NOT NULL,
round_to VARCHAR,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
created_by INTEGER REFERENCES users(id),
updated_at DATETIME,
updated_by INTEGER REFERENCES users(id)
)""",
"""CREATE TABLE IF NOT EXISTS price_modifier_conditions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
modifier_id INTEGER NOT NULL REFERENCES price_modifiers(id) ON DELETE CASCADE,
condition_type VARCHAR NOT NULL,
params TEXT NOT NULL DEFAULT '{}'
)""",
"""CREATE TABLE IF NOT EXISTS price_modifier_targets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
modifier_id INTEGER NOT NULL REFERENCES price_modifiers(id) ON DELETE CASCADE,
target_type VARCHAR NOT NULL,
target_id INTEGER,
target_tag VARCHAR
)""",
"""CREATE TABLE IF NOT EXISTS deals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR NOT NULL,
description TEXT,
color VARCHAR,
is_active INTEGER NOT NULL DEFAULT 1,
sort_order INTEGER NOT NULL DEFAULT 0,
action_type VARCHAR NOT NULL,
action_modifier_id INTEGER REFERENCES price_modifiers(id),
action_value REAL,
action_free_item_id INTEGER REFERENCES products(id),
action_free_target_type VARCHAR,
action_free_target_ids TEXT,
action_free_quantity INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
created_by INTEGER REFERENCES users(id)
)""",
"""CREATE TABLE IF NOT EXISTS deal_conditions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
deal_id INTEGER NOT NULL REFERENCES deals(id) ON DELETE CASCADE,
condition_type VARCHAR NOT NULL,
params TEXT NOT NULL DEFAULT '{}'
)""",
"""CREATE TABLE IF NOT EXISTS deal_targets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
deal_id INTEGER NOT NULL REFERENCES deals(id) ON DELETE CASCADE,
target_type VARCHAR NOT NULL,
target_id INTEGER,
target_tag VARCHAR
)""",
"""CREATE TABLE IF NOT EXISTS price_event_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
order_id INTEGER NOT NULL REFERENCES orders(id),
order_item_id INTEGER REFERENCES order_items(id),
event_type VARCHAR NOT NULL,
modifier_id INTEGER REFERENCES price_modifiers(id),
deal_id INTEGER REFERENCES deals(id),
price_before REAL,
price_after REAL,
delta_amount REAL,
applied_by_user_id INTEGER REFERENCES users(id),
waiter_note TEXT,
conditions_snapshot TEXT,
selected_item_ids TEXT,
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
)""",
"CREATE INDEX IF NOT EXISTS ix_price_event_log_order_id ON price_event_log (order_id)",
"CREATE INDEX IF NOT EXISTS ix_price_event_log_order_item_id ON price_event_log (order_item_id)",
"""CREATE TABLE IF NOT EXISTS waiter_discount_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
can_apply_discounts INTEGER NOT NULL DEFAULT 0,
max_discount_percent REAL,
max_discount_amount REAL,
max_total_value_shift REAL,
max_total_value_workday REAL,
max_items_per_shift INTEGER,
max_items_per_workday INTEGER,
max_items_per_order INTEGER
)""",
# Extend order_discounts with price snapshot columns for clean audit trail
"ALTER TABLE order_discounts ADD COLUMN price_before REAL",
"ALTER TABLE order_discounts ADD COLUMN price_after REAL",
# Global discount settings in pos_settings
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('discounts.enabled', 'true', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('discounts.max_total_value_workday', '', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('discounts.max_total_value_shift', '', CURRENT_TIMESTAMP)",
"INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('discounts.max_items_per_shift', '', CURRENT_TIMESTAMP)",
# Deal item binding — which deal created this item, and which item it's linked to
"ALTER TABLE order_items ADD COLUMN deal_id INTEGER REFERENCES deals(id)",
"ALTER TABLE order_items ADD COLUMN linked_item_id INTEGER REFERENCES order_items(id)",
# Multi-select targets: JSON arrays of IDs/tags per target row
"ALTER TABLE price_modifier_targets ADD COLUMN target_ids TEXT",
"ALTER TABLE price_modifier_targets ADD COLUMN target_tags TEXT",
"ALTER TABLE deal_targets ADD COLUMN target_ids TEXT",
"ALTER TABLE deal_targets ADD COLUMN target_tags TEXT",
# Role & permissions overhaul — granular per-user permission flags
# Access permissions
"ALTER TABLE users ADD COLUMN perm_access_dashboard INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE users ADD COLUMN perm_access_waiter_app INTEGER NOT NULL DEFAULT 1",
"ALTER TABLE users ADD COLUMN perm_access_kds INTEGER NOT NULL DEFAULT 0",
# Order action permissions
"ALTER TABLE users ADD COLUMN perm_cancel_orders INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE users ADD COLUMN perm_apply_discounts INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE users ADD COLUMN perm_modify_prices INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE users ADD COLUMN perm_open_orders INTEGER NOT NULL DEFAULT 1",
"ALTER TABLE users ADD COLUMN perm_close_orders INTEGER NOT NULL DEFAULT 1",
# Management permissions
"ALTER TABLE users ADD COLUMN perm_view_reports INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE users ADD COLUMN perm_manage_staff INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE users ADD COLUMN perm_manage_tables INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE users ADD COLUMN perm_manage_menu INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE users ADD COLUMN perm_manage_settings INTEGER NOT NULL DEFAULT 0",
# Migrate existing managers/sysadmins to have dashboard access + all management perms
"UPDATE users SET perm_access_dashboard=1, perm_access_waiter_app=1, perm_access_kds=1, perm_cancel_orders=1, perm_apply_discounts=1, perm_modify_prices=1, perm_open_orders=1, perm_close_orders=1, perm_view_reports=1, perm_manage_staff=1, perm_manage_tables=1, perm_manage_menu=1, perm_manage_settings=1 WHERE role IN ('manager', 'sysadmin')",
# Migrate existing waiters: update can_cancel_orders → perm_cancel_orders
"UPDATE users SET perm_cancel_orders = can_cancel_orders WHERE role = 'waiter'",
# Rename legacy roles: manager → store_manager, sysadmin → superadmin
"UPDATE users SET role = 'superadmin' WHERE role = 'sysadmin'",
"UPDATE users SET role = 'store_manager' WHERE role = 'manager'",
# Feature: modifier groups (folders), multi-select extras, compact mode
"""CREATE TABLE IF NOT EXISTS product_modifier_groups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER NOT NULL REFERENCES products(id),
modifier_type VARCHAR NOT NULL,
name VARCHAR NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0
)""",
"ALTER TABLE product_options ADD COLUMN multi_select INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_options ADD COLUMN is_compact INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_options ADD COLUMN group_id INTEGER REFERENCES product_modifier_groups(id)",
"ALTER TABLE product_ingredients ADD COLUMN is_compact INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_ingredients ADD COLUMN group_id INTEGER REFERENCES product_modifier_groups(id)",
"ALTER TABLE product_preference_choices ADD COLUMN is_compact INTEGER NOT NULL DEFAULT 0",
"ALTER TABLE product_preference_sets ADD COLUMN group_id INTEGER REFERENCES product_modifier_groups(id)",
# Fiscal printer (ΦΗΜ) — product fields
"ALTER TABLE products ADD COLUMN fiscal_name VARCHAR",
"ALTER TABLE products ADD COLUMN fiscal_vat_group_id INTEGER",
# Fiscal status on orders (NULL=fiscal off, pending/success/failed)
"ALTER TABLE orders ADD COLUMN fiscal_status VARCHAR",
# Drop legacy can_cancel_orders column — data already migrated to perm_cancel_orders
"ALTER TABLE users DROP COLUMN can_cancel_orders",
# Recovery codes for account self-recovery
"""CREATE TABLE IF NOT EXISTS recovery_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
code_hash VARCHAR NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
used_at DATETIME
)""",
"CREATE INDEX IF NOT EXISTS ix_recovery_codes_user_id ON recovery_codes (user_id)",
# Multi-select preference sets
"ALTER TABLE product_preference_sets ADD COLUMN allow_multi_select INTEGER NOT NULL DEFAULT 0",
# Per-choice quantity on multi-select preference sets (x2, x3, …)
"ALTER TABLE product_preference_sets ADD COLUMN allow_choice_quantity INTEGER NOT NULL DEFAULT 0",
# Tracks the hash of the product image last pushed to the cloud (Xenia Connect)
"ALTER TABLE products ADD COLUMN cloud_image_hash VARCHAR",
]
for sql in migrations:
try:
with engine.connect() as conn:
conn.execute(text(sql))
conn.commit()
except Exception:
pass
def _init_chat():
@@ -762,80 +43,90 @@ def _init_chat():
@asynccontextmanager
async def lifespan(app: FastAPI):
import asyncio
from services.sse_bus import init_loop as sse_init_loop
from services.ws_bus import init_loop as ws_init_loop, prune_old_events
from services.reservation_tasks import start_reservation_tasks
from services.printer_service import start_print_retry_thread
loop = asyncio.get_running_loop()
sse_init_loop(loop)
ws_init_loop(loop)
Base.metadata.create_all(bind=engine)
_run_migrations()
# Schema = Alembic revisions only (core/schema.py, APPS_PLATFORM D-13). Refuses v1 databases.
from core.schema import upgrade_to_head
upgrade_to_head()
_db = SessionLocal()
try:
apply_retention_setting(_db)
finally:
_db.close()
logger.info("startup version=%s", settings.VERSION)
# Before the app reports healthy: the proxy's :8443 needs these files to start
from services.tls_identity import ensure_tls_identity
ensure_tls_identity()
start_print_retry_thread()
pruned = prune_old_events(hours=24)
if pruned:
import logging
logging.getLogger(__name__).info("ws_bus: pruned %d old sync_events", pruned)
logger.info("ws_bus: pruned %d old sync_events", pruned)
_init_chat()
sync_task = await start_cloud_sync()
from services.cloud_sync import load_license_at_startup
load_license_at_startup() # entitlements from the stored token (or free tier / dev)
sync_task = await start_cloud_sync() # license heartbeat (core, always on)
# Module workers (connect_* pushes/pulls...) run only while their module is effective
from core.modules import supervisor
supervisor.start(loop)
reservation_task = await start_reservation_tasks()
yield
supervisor.stop_all()
sync_task.cancel()
reservation_task.cancel()
app = FastAPI(title="POS Local Backend", lifespan=lifespan)
# Error responses: {"error": {code, params, message}, "detail"} (core/errors.py, §3.2)
from core.errors import install_error_handlers # noqa: E402
install_error_handlers(app)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(LicenseCheckMiddleware)
# (v1's LicenseCheckMiddleware is gone: an unlicensed site gets the free tier, module by module, D-5.)
# Serve product images as static files
IMAGE_DIR = "/app/data/product_images"
os.makedirs(IMAGE_DIR, exist_ok=True)
app.mount("/static/product_images", StaticFiles(directory=IMAGE_DIR), name="product_images")
@app.middleware("http")
async def _menu_change_push(request, call_next):
"""A successful change to products, price rules or fees pushes the customer apps' menu
soon (phase 3S; services/cloud_sync.request_menu_push)."""
response = await call_next(request)
from services.cloud_sync import menu_changed, request_menu_push
if menu_changed(request.method, request.url.path, response.status_code):
request_menu_push()
return response
# Added last = outermost: the request id exists before any other middleware runs.
app.add_middleware(RequestContextMiddleware)
# Product photos live in the media library (/api/media/file/..., step 5.2); the old
# data/product_images folder is left on disk untouched after Alembic 0027 copied it in.
# Serve waiter avatars as static files
AVATAR_DIR = "/app/data/avatars"
os.makedirs(AVATAR_DIR, exist_ok=True)
app.mount("/static/avatars", StaticFiles(directory=AVATAR_DIR), name="avatars")
app.include_router(setup_router.router, prefix="/api/setup", tags=["setup"])
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
app.include_router(tables.router, prefix="/api/tables", tags=["tables"])
app.include_router(products.router, prefix="/api/products", tags=["products"])
app.include_router(orders.router, prefix="/api/orders", tags=["orders"])
app.include_router(waiters.router, prefix="/api/waiters", tags=["waiters"])
app.include_router(reports.router, prefix="/api/reports", tags=["reports"])
app.include_router(system.router, prefix="/api/system", tags=["system"])
app.include_router(business_day_router.router, prefix="/api/business-day", tags=["business-day"])
app.include_router(shifts_router.router, prefix="/api/shifts", tags=["shifts"])
app.include_router(settings_router.router, prefix="/api/settings", tags=["settings"])
app.include_router(flags_router.router, prefix="/api/flags", tags=["flags"])
app.include_router(messages_router.router, prefix="/api/notifications", tags=["messages"])
app.include_router(sse_router.router, prefix="/api/sse", tags=["sse"])
app.include_router(ws_router.router, prefix="/api/ws", tags=["ws"])
app.include_router(data_transfer_router.router, prefix="/api/data-transfer", tags=["data-transfer"])
app.include_router(connect_orders_router.router, prefix="/api/connect", tags=["connect"])
app.include_router(reservations_router.router, prefix="/api/reservations", tags=["reservations"])
app.include_router(notes_router.router, prefix="/api/notes", tags=["notes"])
app.include_router(contacts_router, prefix="/api/contacts", tags=["contacts"])
app.include_router(expenses_router, prefix="/api/expenses", tags=["expenses"])
app.include_router(customers_router.router, prefix="/api/customers", tags=["customers"])
app.include_router(tabs_router.router, prefix="/api/tabs", tags=["tabs"])
app.include_router(waste_router.router, prefix="/api/waste", tags=["waste"])
app.include_router(kds_router.router, prefix="/api/kds", tags=["kds"])
app.include_router(schedule_router.router, prefix="/api/schedule", tags=["schedule"])
app.include_router(chat_router.router, prefix="/api/chat", tags=["chat"])
app.include_router(prep_zones_router.router, prefix="/api/prep-zones", tags=["prep-zones"])
app.include_router(pricing_router.router, prefix="/api/pricing", tags=["pricing"])
app.include_router(fiscal_router.router, prefix="/api/fiscal", tags=["fiscal"])
app.include_router(phone_router.router, prefix="/api/phone", tags=["phone"])
app.include_router(recovery_router.router, prefix="/api/recovery", tags=["recovery"])
# Routers come from the module manifests (modules/<key>/manifest.py, APPS_PLATFORM D-19).
# All are always mounted; non-core ones answer `module.disabled` while their module is off.
def _mount_module_routers(app: FastAPI) -> None:
import importlib
from fastapi import Depends
from core.modules.registry import registry
from core.modules.state import module_required
for m in registry().values():
deps = [] if m.kind == "core" else [Depends(module_required(m.key))]
for mt in m.routers:
r = getattr(importlib.import_module(mt.module), mt.attr)
app.include_router(r, prefix=mt.prefix, tags=list(mt.tags) or [m.key], dependencies=deps)
_mount_module_routers(app)
-69
View File
@@ -1,69 +0,0 @@
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
# Shared mutable state — updated by cloud_sync.py
# Fields:
# licensed bool — False only after 72h offline OR after expiry grace passes
# locked bool — True once lock_pending is enforced at workday close
# lock_pending bool — Cloud requested lock; waiting for workday to close
# expires_at str|None — ISO timestamp from cloud
# days_until_expiry int|None — negative when expired
# grace_expires_at str|None — ISO timestamp of expiry + 5 days
# last_sync str|None — ISO timestamp of last successful heartbeat
# sync_failed bool
# latest_version str|None
license_state: dict = {
"licensed": True,
"locked": False,
"lock_pending": False,
"expires_at": None,
"days_until_expiry": None,
"grace_expires_at": None,
"last_sync": None,
"sync_failed": False,
"latest_version": None,
}
# Paths that bypass all license checks (health probe, venue identity for pairing)
EXEMPT_PATHS = {"/api/system/health", "/api/system/identity"}
# Paths that are always allowed so the frontend can read license status
# and managers can still log in / close the workday when restricted
STATUS_ALLOWED_PATHS = {
"/api/system/status",
"/api/system/sync-license",
"/api/auth/login",
"/api/auth/me",
"/api/business-day/current",
"/api/business-day/close",
}
class LicenseCheckMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
path = request.url.path
if path in EXEMPT_PATHS or path in STATUS_ALLOWED_PATHS:
return await call_next(request)
# Hard block: licensed=False means either 72h offline grace expired
# OR expiry grace period (5 days) has passed. In both cases the
# business_day router already prevented opening a new workday, so
# existing operations can still complete — we only block new ones.
# The business_day /open endpoint has its own detailed error message.
if not license_state.get("licensed", True):
return Response(
content='{"detail":"license_expired","code":"LICENSE_EXPIRED"}',
status_code=402,
media_type="application/json",
)
# Hard block: locked=True (lock_pending was enforced at workday close)
if license_state.get("locked"):
return Response(
content='{"detail":"system_locked","code":"SYSTEM_LOCKED"}',
status_code=423,
media_type="application/json",
)
return await call_next(request)
+63
View File
@@ -0,0 +1,63 @@
"""Alembic environment for local_backend.
Agent notes:
- Target metadata = every model (models/all.py). Add new model modules there.
- render_as_batch=True: SQLite can't ALTER most things, so Alembic rebuilds the
table (copy → drop → rename) for column changes. Review batch ops carefully.
- No logging.fileConfig() here on purpose: it would replace core/logging.py's
handlers when migrations run at app startup.
- A caller may pass an open connection in config.attributes["connection"]
(core/schema.py, tests); otherwise we connect to config.settings.DATABASE_URL.
- Only "online" mode is supported; offline SQL generation is not needed for SQLite.
"""
import sys
from pathlib import Path
from alembic import context
from sqlalchemy import create_engine
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from database import Base # noqa: E402
import models.all # noqa: E402,F401
target_metadata = Base.metadata
def _render_item(type_, obj, autogen_context):
"""Render our UTCDateTime as `UTCDateTime()` with its import, instead of a module path."""
from core.timeutil import UTCDateTime
if type_ == "type" and isinstance(obj, UTCDateTime):
autogen_context.imports.add("from core.timeutil import UTCDateTime")
return "UTCDateTime()"
return False
def _configure_and_run(connection):
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=True,
render_item=_render_item,
compare_type=True,
compare_server_default=True,
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connection = context.config.attributes.get("connection")
if connection is not None:
_configure_and_run(connection)
return
from config import settings
engine = create_engine(settings.DATABASE_URL)
with engine.connect() as conn:
_configure_and_run(conn)
engine.dispose()
if context.is_offline_mode():
raise SystemExit("Offline (--sql) mode is not supported for local_backend.")
run_migrations_online()
+22
View File
@@ -0,0 +1,22 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,77 @@
"""time model: business_days.business_date, sync_events.created_at as UTCDateTime (D-11, step 1.1)
Revision ID: 0002_time_model
Revises: 0001_v2_baseline
Create Date: 2026-11-12
Every other datetime column moved from DateTime to UTCDateTime in the same step. That
needs no DDL: UTCDateTime's storage type is the same DATETIME text; it only adds the
"aware UTC in, aware UTC out" rules in Python.
Hand-edited after autogenerate:
- business_date is added nullable, backfilled from opened_at in the venue zone with the
rollover hour (same rule as core.timeutil.business_date_of, re-implemented here so the
revision doesn't depend on app code that may change), then made NOT NULL.
- sync_events rows are deleted: they're a 24 h WebSocket replay buffer whose created_at
was ISO text with "T" and an offset, which doesn't compare with the new storage text.
sqlite_autoincrement keeps ids increasing, so client cursors stay valid. The batch
rebuild must restate it (table_kwargs), or SQLite drops AUTOINCREMENT silently.
"""
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0002_time_model'
down_revision = '0001_v2_baseline'
branch_labels = None
depends_on = None
def _setting(conn, key, default):
row = conn.execute(sa.text("select value from pos_settings where key = :k"), {"k": key}).fetchone()
return row[0] if row and row[0] else default
def upgrade() -> None:
conn = op.get_bind()
with op.batch_alter_table('business_days', schema=None) as batch_op:
batch_op.add_column(sa.Column('business_date', sa.Date(), nullable=True))
tz = ZoneInfo(_setting(conn, "venue.timezone", "Europe/Athens"))
rollover = int(_setting(conn, "business_day.rollover_hour", "6"))
for bid, opened_at in conn.execute(sa.text("select id, opened_at from business_days")).fetchall():
dt = datetime.fromisoformat(str(opened_at).replace("Z", "+00:00"))
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
local = dt.astimezone(tz)
bdate = local.date() - timedelta(days=1) if local.hour < rollover else local.date()
conn.execute(sa.text("update business_days set business_date = :d where id = :i"),
{"d": bdate.isoformat(), "i": bid})
with op.batch_alter_table('business_days', schema=None) as batch_op:
batch_op.alter_column('business_date', existing_type=sa.Date(), nullable=False)
batch_op.create_index(batch_op.f('ix_business_days_business_date'), ['business_date'], unique=False)
conn.execute(sa.text("delete from sync_events"))
# Batch mode rebuilds the table from reflection, which loses AUTOINCREMENT unless restated.
with op.batch_alter_table('sync_events', schema=None, table_kwargs={"sqlite_autoincrement": True}) as batch_op:
batch_op.alter_column('created_at',
existing_type=sa.VARCHAR(),
type_=UTCDateTime(),
existing_nullable=False)
def downgrade() -> None:
with op.batch_alter_table('sync_events', schema=None, table_kwargs={"sqlite_autoincrement": True}) as batch_op:
batch_op.alter_column('created_at',
existing_type=UTCDateTime(),
type_=sa.VARCHAR(),
existing_nullable=False)
with op.batch_alter_table('business_days', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_business_days_business_date'))
batch_op.drop_column('business_date')
@@ -0,0 +1,36 @@
"""language fields: users.language, prep_zones.language
Revision ID: 0003_language_fields
Revises: 0002_time_model
Create Date: 2026-11-12 17:22:43.607338
"""
from alembic import op
import sqlalchemy as sa
revision = '0003_language_fields'
down_revision = '0002_time_model'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('prep_zones', schema=None) as batch_op:
batch_op.add_column(sa.Column('language', sa.String(), nullable=True))
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('language', sa.String(), nullable=True))
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_column('language')
with op.batch_alter_table('prep_zones', schema=None) as batch_op:
batch_op.drop_column('language')
# ### end Alembic commands ###
@@ -0,0 +1,33 @@
"""site_modules: module enablement
Revision ID: 0004_site_modules
Revises: 0003_language_fields
Create Date: 2026-11-12 17:44:07.029884
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0004_site_modules'
down_revision = '0003_language_fields'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('site_modules',
sa.Column('key', sa.String(), nullable=False),
sa.Column('enabled', sa.Boolean(), nullable=False),
sa.Column('updated_at', UTCDateTime(), nullable=False),
sa.Column('updated_by', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['updated_by'], ['users.id'], ),
sa.PrimaryKeyConstraint('key')
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('site_modules')
# ### end Alembic commands ###
@@ -0,0 +1,97 @@
"""permission keys: user_permissions, drop perm_* columns (D-7, step 1.5)
Hand-edited: existing grants are copied from the 13 v1 boolean columns into keys
before the columns are dropped. The mapping is frozen here on purpose (same as
core/access/legacy.py on 2026-11-12), so later changes to that file can't change
what this revision did. Superadmins get no rows (they hold every key implicitly).
Revision ID: 0005_permission_keys
Revises: 0004_site_modules
Create Date: 2026-11-12 18:45:11.255266
"""
from alembic import op
import sqlalchemy as sa
FROZEN_MAP = {
"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",),
}
revision = '0005_permission_keys'
down_revision = '0004_site_modules'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user_permissions',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('key', sa.String(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('user_id', 'key')
)
conn = op.get_bind()
cols = ", ".join(FROZEN_MAP)
rows = conn.execute(sa.text(f"select id, role, {cols} from users")).fetchall()
grants = []
for row in rows:
if row[1] == "superadmin":
continue
keys = set()
for i, field in enumerate(FROZEN_MAP, start=2):
if row[i]:
keys.update(FROZEN_MAP[field])
grants += [{"u": row[0], "k": k} for k in sorted(keys)]
if grants:
conn.execute(sa.text("insert into user_permissions (user_id, key) values (:u, :k)"), grants)
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_column('perm_access_kds')
batch_op.drop_column('perm_modify_prices')
batch_op.drop_column('perm_cancel_orders')
batch_op.drop_column('perm_apply_discounts')
batch_op.drop_column('perm_close_orders')
batch_op.drop_column('perm_view_reports')
batch_op.drop_column('perm_manage_settings')
batch_op.drop_column('perm_manage_menu')
batch_op.drop_column('perm_access_dashboard')
batch_op.drop_column('perm_open_orders')
batch_op.drop_column('perm_manage_staff')
batch_op.drop_column('perm_manage_tables')
batch_op.drop_column('perm_access_waiter_app')
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('perm_access_waiter_app', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_manage_tables', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_manage_staff', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_open_orders', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_access_dashboard', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_manage_menu', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_manage_settings', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_view_reports', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_close_orders', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_apply_discounts', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_cancel_orders', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_modify_prices', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
batch_op.add_column(sa.Column('perm_access_kds', sa.BOOLEAN(), nullable=False, server_default=sa.text('0')))
op.drop_table('user_permissions')
# ### end Alembic commands ###
@@ -0,0 +1,58 @@
"""sessions table + manager login mode setting (D-8, D-9, step 1.6)
Hand-edited: the v1 setting security.login_method (password | pin | none) becomes
auth.manager_login_mode; "none" (username-only manager login) no longer exists and
becomes "password".
Revision ID: 0006_sessions
Revises: 0005_permission_keys
Create Date: 2026-11-12 19:10:25.448749
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0006_sessions'
down_revision = '0005_permission_keys'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('sessions',
sa.Column('id', sa.String(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('device_id', sa.Integer(), nullable=True),
sa.Column('client', sa.String(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('last_seen_at', UTCDateTime(), nullable=False),
sa.Column('ended_at', UTCDateTime(), nullable=True),
sa.Column('end_reason', sa.String(), nullable=True),
sa.Column('ip', sa.String(), nullable=True),
sa.Column('user_agent', sa.String(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('sessions', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_sessions_ended_at'), ['ended_at'], unique=False)
batch_op.create_index(batch_op.f('ix_sessions_user_id'), ['user_id'], unique=False)
# ### end Alembic commands ###
conn = op.get_bind()
old = conn.execute(sa.text("select value from pos_settings where key = 'security.login_method'")).scalar()
if old is not None:
mode = old if old in ("password", "pin") else "password"
conn.execute(sa.text("delete from pos_settings where key = 'security.login_method'"))
conn.execute(sa.text("insert or replace into pos_settings (key, value, updated_at) "
"values ('auth.manager_login_mode', :v, CURRENT_TIMESTAMP)"), {"v": mode})
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('sessions', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_sessions_user_id'))
batch_op.drop_index(batch_op.f('ix_sessions_ended_at'))
op.drop_table('sessions')
# ### end Alembic commands ###
@@ -0,0 +1,86 @@
"""devices, pairing requests, session device FK (D-8, §6.3, step 1.8)
Hand-edited: the sessions FK gets a name (SQLite batch mode can't create or drop an
unnamed constraint). No data moves: sessions.device_id was always NULL before this.
Revision ID: 0007_devices
Revises: 0006_sessions
Create Date: 2026-11-13 09:33:18.938342
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0007_devices'
down_revision = '0006_sessions'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('devices',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('uuid', sa.String(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('app_key', sa.String(), nullable=False),
sa.Column('config', sa.JSON(), nullable=True),
sa.Column('login_mode', sa.String(), nullable=True),
sa.Column('token_hash', sa.String(), nullable=True),
sa.Column('linked_device_id', sa.Integer(), nullable=True),
sa.Column('user_agent', sa.String(), nullable=True),
sa.Column('paired_at', UTCDateTime(), nullable=False),
sa.Column('paired_by', sa.Integer(), nullable=True),
sa.Column('claimed_at', UTCDateTime(), nullable=True),
sa.Column('last_seen_at', UTCDateTime(), nullable=True),
sa.Column('revoked_at', UTCDateTime(), nullable=True),
sa.Column('revoked_by', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['linked_device_id'], ['devices.id'], ondelete='SET NULL'),
sa.ForeignKeyConstraint(['paired_by'], ['users.id'], ondelete='SET NULL'),
sa.ForeignKeyConstraint(['revoked_by'], ['users.id'], ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('token_hash'),
sa.UniqueConstraint('uuid'),
sqlite_autoincrement=True
)
with op.batch_alter_table('devices', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_devices_app_key'), ['app_key'], unique=False)
batch_op.create_index(batch_op.f('ix_devices_revoked_at'), ['revoked_at'], unique=False)
op.create_table('device_pair_requests',
sa.Column('code', sa.String(), nullable=False),
sa.Column('secret_hash', sa.String(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('expires_at', UTCDateTime(), nullable=False),
sa.Column('device_id', sa.Integer(), nullable=True),
sa.Column('ip', sa.String(), nullable=True),
sa.Column('user_agent', sa.String(), nullable=True),
sa.ForeignKeyConstraint(['device_id'], ['devices.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('code')
)
with op.batch_alter_table('device_pair_requests', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_device_pair_requests_expires_at'), ['expires_at'], unique=False)
with op.batch_alter_table('sessions', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_sessions_device_id'), ['device_id'], unique=False)
batch_op.create_foreign_key('fk_sessions_device_id_devices', 'devices', ['device_id'], ['id'])
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('sessions', schema=None) as batch_op:
batch_op.drop_constraint('fk_sessions_device_id_devices', type_='foreignkey')
batch_op.drop_index(batch_op.f('ix_sessions_device_id'))
with op.batch_alter_table('device_pair_requests', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_device_pair_requests_expires_at'))
op.drop_table('device_pair_requests')
with op.batch_alter_table('devices', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_devices_revoked_at'))
batch_op.drop_index(batch_op.f('ix_devices_app_key'))
op.drop_table('devices')
# ### end Alembic commands ###
@@ -0,0 +1,61 @@
"""access_overrides (manager override audit + tokens) (D-10, step 1.9)
Hand-edited: existing users whose role template now includes a key added since their
grants were written get it (role templates are only copied at user creation):
core.devices.manage (step 1.8) and pricing.discounts.over_limit (this step), for
owner and store_manager. The role lists are frozen here on purpose.
Revision ID: 0008_access_overrides
Revises: 0007_devices
Create Date: 2026-11-13 09:49:51.024839
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0008_access_overrides'
down_revision = '0007_devices'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('access_overrides',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('key', sa.String(), nullable=False),
sa.Column('token_hash', sa.String(), nullable=False),
sa.Column('requested_by', sa.Integer(), nullable=True),
sa.Column('requested_session', sa.String(), nullable=True),
sa.Column('approved_by', sa.Integer(), nullable=True),
sa.Column('device_id', sa.Integer(), nullable=True),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('expires_at', UTCDateTime(), nullable=False),
sa.Column('used_at', UTCDateTime(), nullable=True),
sa.Column('target', sa.String(), nullable=True),
sa.ForeignKeyConstraint(['approved_by'], ['users.id'], ondelete='SET NULL'),
sa.ForeignKeyConstraint(['device_id'], ['devices.id'], ondelete='SET NULL'),
sa.ForeignKeyConstraint(['requested_by'], ['users.id'], ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('token_hash'),
sqlite_autoincrement=True
)
with op.batch_alter_table('access_overrides', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_access_overrides_created_at'), ['created_at'], unique=False)
batch_op.create_index(batch_op.f('ix_access_overrides_key'), ['key'], unique=False)
# ### end Alembic commands ###
conn = op.get_bind()
for key in ("core.devices.manage", "pricing.discounts.over_limit"):
conn.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, :k from users where role in ('owner', 'store_manager')"), {"k": key})
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('access_overrides', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_access_overrides_key'))
batch_op.drop_index(batch_op.f('ix_access_overrides_created_at'))
op.drop_table('access_overrides')
# ### end Alembic commands ###
@@ -0,0 +1,51 @@
"""support_challenges + sessions.expires_at (support access)
Revision ID: 0009_support_access
Revises: 0008_access_overrides
Create Date: 2026-11-13 10:47:20.516800
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0009_support_access'
down_revision = '0008_access_overrides'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('support_challenges',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('challenge', sa.String(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('expires_at', UTCDateTime(), nullable=False),
sa.Column('attempts', sa.Integer(), nullable=False),
sa.Column('used_at', UTCDateTime(), nullable=True),
sa.Column('session_id', sa.String(), nullable=True),
sa.Column('ip', sa.String(), nullable=True),
sa.Column('user_agent', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('challenge'),
sqlite_autoincrement=True
)
with op.batch_alter_table('support_challenges', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_support_challenges_expires_at'), ['expires_at'], unique=False)
with op.batch_alter_table('sessions', schema=None) as batch_op:
batch_op.add_column(sa.Column('expires_at', UTCDateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('sessions', schema=None) as batch_op:
batch_op.drop_column('expires_at')
with op.batch_alter_table('support_challenges', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_support_challenges_expires_at'))
op.drop_table('support_challenges')
# ### end Alembic commands ###
@@ -0,0 +1,59 @@
"""notifications + notification_reads (platform notifications)
Revision ID: 0010_notifications
Revises: 0009_support_access
Create Date: 2026-11-13 11:06:59.999254
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0010_notifications'
down_revision = '0009_support_access'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('notifications',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('key', sa.String(), nullable=False),
sa.Column('severity', sa.String(), nullable=False),
sa.Column('audience', sa.String(), nullable=False),
sa.Column('params', sa.JSON(), nullable=True),
sa.Column('dedupe_key', sa.String(), nullable=True),
sa.Column('count', sa.Integer(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('last_at', UTCDateTime(), nullable=False),
sa.Column('expires_at', UTCDateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sqlite_autoincrement=True
)
with op.batch_alter_table('notifications', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_notifications_audience'), ['audience'], unique=False)
batch_op.create_index(batch_op.f('ix_notifications_created_at'), ['created_at'], unique=False)
batch_op.create_index(batch_op.f('ix_notifications_dedupe_key'), ['dedupe_key'], unique=False)
batch_op.create_index(batch_op.f('ix_notifications_key'), ['key'], unique=False)
op.create_table('notification_reads',
sa.Column('notification_id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('read_at', UTCDateTime(), nullable=False),
sa.ForeignKeyConstraint(['notification_id'], ['notifications.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('notification_id', 'user_id')
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('notification_reads')
with op.batch_alter_table('notifications', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_notifications_key'))
batch_op.drop_index(batch_op.f('ix_notifications_dedupe_key'))
batch_op.drop_index(batch_op.f('ix_notifications_created_at'))
batch_op.drop_index(batch_op.f('ix_notifications_audience'))
op.drop_table('notifications')
# ### end Alembic commands ###
@@ -0,0 +1,52 @@
"""order_items name snapshots (product_name, category_id, category_name) (D-18, step 1.12)
Hand-edited: product_name is added nullable, back-filled from the CURRENT catalogue
(the best a v2 DB can know; v1 history comes through the migration tool, plan 7.1),
then made NOT NULL. Items of deleted products get "#<product_id>".
Revision ID: 0011_order_item_names
Revises: 0010_notifications
Create Date: 2026-11-13 11:29:59.346931
"""
from alembic import op
import sqlalchemy as sa
revision = '0011_order_item_names'
down_revision = '0010_notifications'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('order_items', schema=None) as batch_op:
batch_op.add_column(sa.Column('product_name', sa.String(), nullable=True))
batch_op.add_column(sa.Column('category_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('category_name', sa.String(), nullable=True))
batch_op.create_index(batch_op.f('ix_order_items_category_id'), ['category_id'], unique=False)
# ### end Alembic commands ###
op.execute("""
UPDATE order_items SET
product_name = COALESCE((SELECT p.name FROM products p WHERE p.id = order_items.product_id),
'#' || order_items.product_id),
category_id = (SELECT p.category_id FROM products p WHERE p.id = order_items.product_id)
""")
op.execute("""
UPDATE order_items SET category_name = (SELECT c.name FROM categories c WHERE c.id = order_items.category_id)
WHERE category_id IS NOT NULL
""")
with op.batch_alter_table('order_items', schema=None) as batch_op:
batch_op.alter_column('product_name', existing_type=sa.String(), nullable=False)
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('order_items', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_order_items_category_id'))
batch_op.drop_column('category_name')
batch_op.drop_column('category_id')
batch_op.drop_column('product_name')
# ### end Alembic commands ###
@@ -0,0 +1,35 @@
"""drop legacy products.printer_zone_id (plan step 1.13; noted in 1.0)
Hand-edited: the FK is unnamed, so it can't be dropped by name in SQLite batch mode; the
batch rebuild of `products` drops it together with the column. Routing has been by prep
zone only since v1 (v1 nulled this column on every start), so no data is lost.
Revision ID: 0012_drop_product_printer_zone
Revises: 0011_order_item_names
Create Date: 2026-11-13 12:27:34.824101
"""
from alembic import op
import sqlalchemy as sa
revision = '0012_drop_product_printer_zone'
down_revision = '0011_order_item_names'
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.drop_column('printer_zone_id')
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('printer_zone_id', sa.INTEGER(), nullable=True))
batch_op.create_foreign_key('fk_products_printer_zone_id', 'printers', ['printer_zone_id'], ['id'])
# ### end Alembic commands ###
@@ -0,0 +1,63 @@
"""product_categories + products.primary_category_id (multi-category) (D-23, step 1.13)
Hand-written data move: products.category_id becomes products.primary_category_id (new
column with a named FK, copied, old column dropped by the batch rebuild, which also drops
its unnamed FK), and every product with a category gets one listing in it, at its old
products.sort_order position. products.sort_order stays (global order for the current
screens).
Revision ID: 0013_product_categories
Revises: 0012_drop_product_printer_zone
Create Date: 2026-11-13 12:30:55.936976
"""
from alembic import op
import sqlalchemy as sa
revision = '0013_product_categories'
down_revision = '0012_drop_product_printer_zone'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('product_categories',
sa.Column('product_id', sa.Integer(), nullable=False),
sa.Column('category_id', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['product_id'], ['products.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('product_id', 'category_id')
)
with op.batch_alter_table('product_categories', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_product_categories_category_id'), ['category_id'], unique=False)
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('primary_category_id', sa.Integer(), nullable=True))
batch_op.create_index(batch_op.f('ix_products_primary_category_id'), ['primary_category_id'], unique=False)
batch_op.create_foreign_key('fk_products_primary_category_id', 'categories', ['primary_category_id'], ['id'])
# only ids of categories that still exist (v1 never enforced the FK)
op.execute("""UPDATE products SET primary_category_id = category_id
WHERE category_id IN (SELECT id FROM categories)""")
op.execute("""INSERT INTO product_categories (product_id, category_id, sort_order)
SELECT id, primary_category_id, COALESCE(sort_order, 0) FROM products
WHERE primary_category_id IS NOT NULL""")
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.drop_column('category_id')
def downgrade() -> None:
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('category_id', sa.INTEGER(), nullable=True))
op.execute("UPDATE products SET category_id = primary_category_id")
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.drop_constraint('fk_products_primary_category_id', type_='foreignkey')
batch_op.drop_index(batch_op.f('ix_products_primary_category_id'))
batch_op.drop_column('primary_category_id')
with op.batch_alter_table('product_categories', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_product_categories_category_id'))
op.drop_table('product_categories')
@@ -0,0 +1,24 @@
"""sync_events.target_device_ids: live events addressed to paired devices (plan step 3.1a)
Revision ID: 0014_sync_event_devices
Revises: 0013_product_categories
Create Date: 2026-11-14 18:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0014_sync_event_devices'
down_revision = '0013_product_categories'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('sync_events', schema=None) as batch_op:
batch_op.add_column(sa.Column('target_device_ids', sa.Text(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('sync_events', schema=None) as batch_op:
batch_op.drop_column('target_device_ids')
@@ -0,0 +1,30 @@
"""order_items.claimed_by / claimed_at: a cook claims a KDS item (plan step 3.2c)
Revision ID: 0015_item_claims
Revises: 0014_sync_event_devices
Create Date: 2026-11-14 21:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0015_item_claims'
down_revision = '0014_sync_event_devices'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('order_items', schema=None) as batch_op:
batch_op.add_column(sa.Column('claimed_by', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('claimed_at', UTCDateTime(), nullable=True))
batch_op.create_foreign_key('fk_order_items_claimed_by_users', 'users', ['claimed_by'], ['id'])
def downgrade() -> None:
with op.batch_alter_table('order_items', schema=None) as batch_op:
batch_op.drop_constraint('fk_order_items_claimed_by_users', type_='foreignkey')
batch_op.drop_column('claimed_at')
batch_op.drop_column('claimed_by')
@@ -0,0 +1,72 @@
"""refunds + refund_items: money given back for paid items; key ordering.refunds for owners and managers (plan step 3.3e)
Revision ID: 0016_refunds
Revises: 0015_item_claims
Create Date: 2026-11-15 18:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0016_refunds'
down_revision = '0015_item_claims'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('refunds',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('order_id', sa.Integer(), nullable=False),
sa.Column('business_day_id', sa.Integer(), nullable=True),
sa.Column('shift_id', sa.Integer(), nullable=True),
sa.Column('refunded_by', sa.Integer(), nullable=False),
sa.Column('approved_by', sa.Integer(), nullable=True),
sa.Column('device_id', sa.Integer(), nullable=True),
sa.Column('method', sa.String(), nullable=False),
sa.Column('amount', sa.Float(), nullable=False),
sa.Column('reason', sa.Text(), nullable=True),
sa.Column('fiscal_status', sa.String(), nullable=True),
sa.Column('fiscal_reference', sa.String(), nullable=True),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.ForeignKeyConstraint(['order_id'], ['orders.id']),
sa.ForeignKeyConstraint(['business_day_id'], ['business_days.id']),
sa.ForeignKeyConstraint(['shift_id'], ['waiter_shifts.id']),
sa.ForeignKeyConstraint(['refunded_by'], ['users.id']),
sa.ForeignKeyConstraint(['approved_by'], ['users.id']),
sa.ForeignKeyConstraint(['device_id'], ['devices.id']),
sa.PrimaryKeyConstraint('id'),
)
with op.batch_alter_table('refunds', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_refunds_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_refunds_order_id'), ['order_id'], unique=False)
batch_op.create_index(batch_op.f('ix_refunds_business_day_id'), ['business_day_id'], unique=False)
batch_op.create_index(batch_op.f('ix_refunds_shift_id'), ['shift_id'], unique=False)
op.create_table('refund_items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('refund_id', sa.Integer(), nullable=False),
sa.Column('order_item_id', sa.Integer(), nullable=False),
sa.Column('quantity', sa.Float(), nullable=False),
sa.Column('amount', sa.Float(), nullable=False),
sa.ForeignKeyConstraint(['refund_id'], ['refunds.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['order_item_id'], ['order_items.id']),
sa.PrimaryKeyConstraint('id'),
)
with op.batch_alter_table('refund_items', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_refund_items_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_refund_items_refund_id'), ['refund_id'], unique=False)
batch_op.create_index(batch_op.f('ix_refund_items_order_item_id'), ['order_item_id'], unique=False)
# the new key `ordering.refunds` for the roles whose template has it (new users get it from
# the template; existing owners and managers here)
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, 'ordering.refunds' from users where role in ('owner', 'store_manager')"))
def downgrade() -> None:
op.get_bind().execute(sa.text("delete from user_permissions where key = 'ordering.refunds'"))
op.drop_table('refund_items')
op.drop_table('refunds')
@@ -0,0 +1,113 @@
"""sales points: orders.sales_point, products.sold_at; digital prices become price modifiers (plan phase 3S, step S.1)
- orders.sales_point, from source / online_order_type / order_type (core/sales_points.for_order)
- products.sold_at (JSON list), from digital_visible (hidden online → sold in the venue only)
- digital_price / digital_discount → item price modifiers with the condition "sales point is
the QR menu or online" (a price difference, then a stackable % discount), so every place
that prices asks the same engine
- the order_channel condition's old values (pos, takeaway, online, qr) → sales points, in
price modifiers and deals
- drops products.digital_visible, digital_price, digital_discount
Revision ID: 0017_sales_points
Revises: 0016_refunds
Create Date: 2026-11-15 21:00:00
"""
import json
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime, utcnow
revision = '0017_sales_points'
down_revision = '0016_refunds'
branch_labels = None
depends_on = None
ALL = ["in_store", "in_store_takeaway", "qr_table", "online_takeaway", "online_delivery", "online_preorder"]
IN_PERSON = ["in_store", "in_store_takeaway"]
DIGITAL = ["qr_table", "online_takeaway", "online_delivery", "online_preorder"]
LEGACY = {"pos": ["in_store"], "takeaway": ["in_store_takeaway"],
"online": ["online_takeaway", "online_delivery", "online_preorder"], "qr": ["qr_table"]}
def _remap(params: str) -> str:
try:
p = json.loads(params or "{}")
except ValueError:
return params
out = []
for v in p.get("channels") or []:
for sp in ([v] if v in ALL else LEGACY.get(v, [])):
if sp not in out:
out.append(sp)
p["channels"] = out
return json.dumps(p)
def upgrade() -> None:
conn = op.get_bind()
with op.batch_alter_table('orders', schema=None) as batch_op:
batch_op.add_column(sa.Column('sales_point', sa.String(), nullable=False, server_default='in_store'))
conn.execute(sa.text("""
update orders set sales_point = case
when source = 'online' then case online_order_type
when 'delivery' then 'online_delivery' when 'takeaway' then 'online_takeaway'
when 'preorder' then 'online_preorder' else 'qr_table' end
when order_type in ('takeaway', 'delivery') then 'in_store_takeaway'
else 'in_store' end"""))
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('sold_at', sa.Text(), nullable=False, server_default=json.dumps(ALL)))
conn.execute(sa.text("update products set sold_at = :v where digital_visible = 0"), {"v": json.dumps(IN_PERSON)})
modifiers = sa.table('price_modifiers',
sa.column('id', sa.Integer), sa.column('name', sa.String), sa.column('description', sa.Text),
sa.column('is_active', sa.Integer), sa.column('is_favorite', sa.Integer),
sa.column('allow_stack', sa.Integer), sa.column('sort_order', sa.Integer),
sa.column('scope', sa.String), sa.column('item_id', sa.Integer),
sa.column('action_type', sa.String), sa.column('action_value', sa.Float),
sa.column('created_at', UTCDateTime()))
conditions = sa.table('price_modifier_conditions', sa.column('modifier_id', sa.Integer),
sa.column('condition_type', sa.String), sa.column('params', sa.Text))
now = utcnow()
rows = conn.execute(sa.text("select id, name, base_price, digital_price, digital_discount from products "
"where digital_price is not null or coalesce(digital_discount, 0) > 0")).fetchall()
for pid, name, base, price, discount in rows:
made = []
if price is not None and abs(price - (base or 0.0)) > 0.0001:
made.append((f"Online price · {name}", "add_amount", round(price - (base or 0.0), 4), 0))
if discount and discount > 0:
made.append((f"Online discount · {name}", "add_percent", -float(discount), 1))
for label, action, value, stack in made:
mid = conn.execute(modifiers.insert().values(
name=label, description="From the product's digital menu price (moved in phase 3S)",
is_active=1, is_favorite=0, allow_stack=stack, sort_order=0, scope="item", item_id=pid,
action_type=action, action_value=value, created_at=now)).lastrowid
conn.execute(conditions.insert().values(modifier_id=mid, condition_type="order_channel",
params=json.dumps({"channels": DIGITAL})))
for table in ("price_modifier_conditions", "deal_conditions"):
for cid, params in conn.execute(sa.text(f"select id, params from {table} where condition_type = 'order_channel'")).fetchall():
conn.execute(sa.text(f"update {table} set params = :p where id = :i"), {"p": _remap(params), "i": cid})
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.drop_column('digital_visible')
batch_op.drop_column('digital_price')
batch_op.drop_column('digital_discount')
def downgrade() -> None:
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('digital_discount', sa.Float(), nullable=False, server_default='0'))
batch_op.add_column(sa.Column('digital_price', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('digital_visible', sa.Integer(), nullable=False, server_default='1'))
op.get_bind().execute(sa.text("update products set digital_visible = 0 where sold_at not like '%qr_table%' "
"and sold_at not like '%online_%'"))
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.drop_column('sold_at')
with op.batch_alter_table('orders', schema=None) as batch_op:
batch_op.drop_column('sales_point')
@@ -0,0 +1,62 @@
"""delivery_areas + fee_rules; key connect_orders.fees for owners and managers (plan phase 3S, S.3)
Revision ID: 0018_fee_rules
Revises: 0017_sales_points
Create Date: 2026-11-16 10:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0018_fee_rules'
down_revision = '0017_sales_points'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('delivery_areas',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('postcodes', sa.Text(), nullable=False),
sa.Column('is_active', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
)
with op.batch_alter_table('delivery_areas', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_delivery_areas_id'), ['id'], unique=False)
op.create_table('fee_rules',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('is_active', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('sales_points', sa.Text(), nullable=False),
sa.Column('area_ids', sa.Text(), nullable=False),
sa.Column('subtotal_min', sa.Float(), nullable=True),
sa.Column('subtotal_max', sa.Float(), nullable=True),
sa.Column('items_min', sa.Integer(), nullable=True),
sa.Column('items_max', sa.Integer(), nullable=True),
sa.Column('days', sa.Text(), nullable=False),
sa.Column('time_from', sa.String(), nullable=True),
sa.Column('time_to', sa.String(), nullable=True),
sa.Column('action', sa.String(), nullable=False),
sa.Column('value', sa.Float(), nullable=False),
sa.Column('stop', sa.Integer(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
)
with op.batch_alter_table('fee_rules', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_fee_rules_id'), ['id'], unique=False)
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, 'connect_orders.fees' from users where role in ('owner', 'store_manager')"))
def downgrade() -> None:
op.get_bind().execute(sa.text("delete from user_permissions where key = 'connect_orders.fees'"))
op.drop_table('fee_rules')
op.drop_table('delivery_areas')
@@ -0,0 +1,36 @@
"""system products (the delivery fee line); online orders keep their time, area and the site's price check (plan phase 3S, S.5)
Revision ID: 0019_online_order_site_side
Revises: 0018_fee_rules
Create Date: 2026-11-16 18:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0019_online_order_site_side'
down_revision = '0018_fee_rules'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('system_key', sa.String(), nullable=True))
batch_op.create_index(batch_op.f('ix_products_system_key'), ['system_key'], unique=True)
with op.batch_alter_table('orders', schema=None) as batch_op:
batch_op.add_column(sa.Column('online_delivery_area', sa.String(), nullable=True))
batch_op.add_column(sa.Column('online_price_diff', sa.Text(), nullable=True))
batch_op.add_column(sa.Column('requested_for', UTCDateTime(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('orders', schema=None) as batch_op:
batch_op.drop_column('requested_for')
batch_op.drop_column('online_price_diff')
batch_op.drop_column('online_delivery_area')
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_products_system_key'))
batch_op.drop_column('system_key')
@@ -0,0 +1,38 @@
"""reservations: online bookings with food ordered ahead (plan phase 3S, S.6)
Revision ID: 0020_online_reservations
Revises: 0019_online_order_site_side
Create Date: 2026-11-16 21:30:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0020_online_reservations'
down_revision = '0019_online_order_site_side'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('reservations', schema=None) as batch_op:
batch_op.add_column(sa.Column('online_order_cloud_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('online_ref', sa.String(), nullable=True))
batch_op.add_column(sa.Column('items_json', sa.Text(), nullable=True))
batch_op.add_column(sa.Column('total', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('online_price_diff', sa.Text(), nullable=True))
batch_op.add_column(sa.Column('fire_at', UTCDateTime(), nullable=True))
batch_op.add_column(sa.Column('order_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('response_note', sa.Text(), nullable=True))
batch_op.create_index(batch_op.f('ix_reservations_online_order_cloud_id'), ['online_order_cloud_id'], unique=False)
batch_op.create_foreign_key('fk_reservations_order_id_orders', 'orders', ['order_id'], ['id'])
def downgrade() -> None:
with op.batch_alter_table('reservations', schema=None) as batch_op:
batch_op.drop_constraint('fk_reservations_order_id_orders', type_='foreignkey')
batch_op.drop_index(batch_op.f('ix_reservations_online_order_cloud_id'))
for c in ('response_note', 'order_id', 'fire_at', 'online_price_diff', 'total', 'items_json', 'online_ref', 'online_order_cloud_id'):
batch_op.drop_column(c)
@@ -0,0 +1,26 @@
"""tables: qr_token (the QR menu at the table, plan phase 3S, S.7)
Revision ID: 0021_table_qr_token
Revises: 0020_online_reservations
Create Date: 2026-11-16 23:30:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0021_table_qr_token'
down_revision = '0020_online_reservations'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('tables', schema=None) as batch_op:
batch_op.add_column(sa.Column('qr_token', sa.String(), nullable=True))
batch_op.create_unique_constraint('uq_tables_qr_token', ['qr_token'])
def downgrade() -> None:
with op.batch_alter_table('tables', schema=None) as batch_op:
batch_op.drop_constraint('uq_tables_qr_token', type_='unique')
batch_op.drop_column('qr_token')
@@ -0,0 +1,25 @@
"""key customer_display.manage for owners and store managers (plan step 3.4)
The idle screen is a setting (customer_display.idle) and its images are files, so no table.
Revision ID: 0022_customer_display_key
Revises: 0021_table_qr_token
Create Date: 2026-11-17 10:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0022_customer_display_key'
down_revision = '0021_table_qr_token'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, 'customer_display.manage' from users where role in ('owner', 'store_manager')"))
def downgrade() -> None:
op.get_bind().execute(sa.text("delete from user_permissions where key = 'customer_display.manage'"))
@@ -0,0 +1,35 @@
"""phone_calls: the caller ID call log (plan step 3.5)
Revision ID: 0023_phone_calls
Revises: 0022_customer_display_key
Create Date: 2026-11-17 12:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0023_phone_calls'
down_revision = '0022_customer_display_key'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('phone_calls',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('at', UTCDateTime(), nullable=False),
sa.Column('number', sa.String(), nullable=False),
sa.Column('ext', sa.String(), nullable=True),
sa.Column('customer_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['customer_id'], ['customers.id'], ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id'),
)
with op.batch_alter_table('phone_calls', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_phone_calls_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_phone_calls_at'), ['at'], unique=False)
def downgrade() -> None:
op.drop_table('phone_calls')
@@ -0,0 +1,44 @@
"""role_permissions (venue role defaults) and the waiter permission settings moved to keys
(plan step 4.3)
orders.waiter_cancellations_allowed, orders.waiter_price_adjust_allowed and
payments.waiter_revert_allowed are gone: the keys ordering.orders.cancel,
ordering.prices.modify and ordering.payments.revert decide (per person, per role).
The new key ordering.payments.revert is given to existing owners and store managers.
Revision ID: 0024_role_permissions
Revises: 0023_phone_calls
Create Date: 2026-11-17 18:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0024_role_permissions'
down_revision = '0023_phone_calls'
branch_labels = None
depends_on = None
GONE = ('orders.waiter_cancellations_allowed', 'orders.waiter_price_adjust_allowed', 'payments.waiter_revert_allowed')
def upgrade() -> None:
op.create_table('role_permissions',
sa.Column('role', sa.String(), nullable=False),
sa.Column('key', sa.String(), nullable=False),
sa.Column('granted', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('role', 'key'),
)
settings = sa.table('pos_settings', sa.column('key', sa.String))
op.execute(settings.delete().where(settings.c.key.in_(GONE)))
# the new key goes to the people whose role has it (keys are copied at creation, so
# existing owners and store managers would otherwise never get it)
op.execute(
"INSERT INTO user_permissions (user_id, key) "
"SELECT id, 'ordering.payments.revert' FROM users WHERE role IN ('owner', 'store_manager') "
"AND id NOT IN (SELECT user_id FROM user_permissions WHERE key = 'ordering.payments.revert')"
)
def downgrade() -> None:
op.drop_table('role_permissions')
@@ -0,0 +1,28 @@
"""order_items.source: where a line came from (plan step 4.8): waiter | counter | qr | online.
The waiter's phone marks the lines the guests sent themselves (QR menu) and online orders.
Lines of online orders get 'online'; older lines stay NULL (unknown).
Revision ID: 0025_order_item_source
Revises: 0024_role_permissions
Create Date: 2026-11-18 10:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0025_order_item_source'
down_revision = '0024_role_permissions'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('order_items', schema=None) as batch_op:
batch_op.add_column(sa.Column('source', sa.String(), nullable=True))
op.execute("UPDATE order_items SET source = 'online' WHERE order_id IN (SELECT id FROM orders WHERE source = 'online')")
def downgrade() -> None:
with op.batch_alter_table('order_items', schema=None) as batch_op:
batch_op.drop_column('source')
@@ -0,0 +1,47 @@
"""media: the media library (plan step 5.1).
One row per file (unique sha256); the bytes live under data/media (services/media.py).
Products, the customer display and signage point at these rows from steps 5.2-5.4.
Revision ID: 0026_media
Revises: 0025_order_item_source
Create Date: 2026-11-18 12:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0026_media'
down_revision = '0025_order_item_source'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('media',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('kind', sa.String(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('original_name', sa.String(), nullable=True),
sa.Column('content_type', sa.String(), nullable=False),
sa.Column('sha256', sa.String(length=64), nullable=False),
sa.Column('bytes', sa.Integer(), nullable=False),
sa.Column('width', sa.Integer(), nullable=True),
sa.Column('height', sa.Integer(), nullable=True),
sa.Column('duration_ms', sa.Integer(), nullable=True),
sa.Column('uploaded_by', sa.Integer(), nullable=True),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.ForeignKeyConstraint(['uploaded_by'], ['users.id'], ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('sha256')
)
with op.batch_alter_table('media', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_media_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_media_kind'), ['kind'], unique=False)
def downgrade() -> None:
with op.batch_alter_table('media', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_media_kind'))
batch_op.drop_index(batch_op.f('ix_media_id'))
op.drop_table('media')
@@ -0,0 +1,90 @@
"""Products and categories point at the media library (plan step 5.2).
products.media_id and categories.media_id (a picture in `media`). The old product photos
(products.image_url = /static/product_images/<file>) are copied into the library: each file
is processed like an upload (sizes made, kept once by hash, display name = the product's
name) and the product points at it. The old folder is left on disk untouched. A file that is
missing or unreadable is logged and skipped (the product just has no photo). Then
products.image_url goes; apps read `image` / `image_url` (the card size) from the API.
Revision ID: 0027_product_media
Revises: 0026_media
Create Date: 2026-11-17 15:00:00
"""
import logging
import os
from alembic import op
import sqlalchemy as sa
revision = '0027_product_media'
down_revision = '0026_media'
branch_labels = None
depends_on = None
log = logging.getLogger("alembic.0027")
OLD_DIR = os.environ.get("XENIA_PRODUCT_IMAGE_DIR", "/app/data/product_images")
def upgrade() -> None:
with op.batch_alter_table('categories', schema=None) as batch_op:
batch_op.add_column(sa.Column('media_id', sa.Integer(), nullable=True))
batch_op.create_index(batch_op.f('ix_categories_media_id'), ['media_id'], unique=False)
batch_op.create_foreign_key('fk_categories_media_id_media', 'media', ['media_id'], ['id'], ondelete='SET NULL')
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('media_id', sa.Integer(), nullable=True))
batch_op.create_index(batch_op.f('ix_products_media_id'), ['media_id'], unique=False)
batch_op.create_foreign_key('fk_products_media_id_media', 'media', ['media_id'], ['id'], ondelete='SET NULL')
_move_photos(op.get_bind())
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.drop_column('image_url')
def _move_photos(conn) -> None:
rows = conn.execute(sa.text("SELECT id, name, image_url FROM products WHERE image_url IS NOT NULL AND image_url != ''")).fetchall()
if not rows:
return
from core.timeutil import DB_FORMAT, utcnow
from services import media as store
moved = 0
for pid, name, url in rows:
path = os.path.join(OLD_DIR, os.path.basename(url))
if not os.path.isfile(path):
log.warning("product %s: photo %s not found, skipped", pid, path)
continue
try:
sha, size, info = store.ingest_path(path)
except Exception as e: # refused (type, size) or unreadable
log.warning("product %s: photo %s not moved (%s)", pid, path, getattr(e, "code", e))
continue
mid = conn.execute(sa.text("SELECT id FROM media WHERE sha256 = :s"), {"s": sha}).scalar()
if mid is None:
if not info: # files there from an earlier try, no row
store.delete_files(sha)
sha, size, info = store.ingest_path(path)
conn.execute(sa.text(
"INSERT INTO media (kind, name, original_name, content_type, sha256, bytes, width, height, duration_ms, created_at) "
"VALUES (:kind, :name, :orig, :ctype, :sha, :bytes, :w, :h, :d, :at)"),
{"kind": info["kind"], "name": (name or "photo")[:120], "orig": os.path.basename(path),
"ctype": info["content_type"], "sha": sha, "bytes": size, "w": info.get("width"),
"h": info.get("height"), "d": info.get("duration_ms"), "at": utcnow().strftime(DB_FORMAT)})
mid = conn.execute(sa.text("SELECT id FROM media WHERE sha256 = :s"), {"s": sha}).scalar()
conn.execute(sa.text("UPDATE products SET media_id = :m WHERE id = :p"), {"m": mid, "p": pid})
moved += 1
log.info("product photos moved into the media library: %d of %d", moved, len(rows))
def downgrade() -> None:
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('image_url', sa.VARCHAR(), nullable=True))
batch_op.drop_constraint('fk_products_media_id_media', type_='foreignkey')
batch_op.drop_index(batch_op.f('ix_products_media_id'))
batch_op.drop_column('media_id')
with op.batch_alter_table('categories', schema=None) as batch_op:
batch_op.drop_constraint('fk_categories_media_id_media', type_='foreignkey')
batch_op.drop_index(batch_op.f('ix_categories_media_id'))
batch_op.drop_column('media_id')
@@ -0,0 +1,99 @@
"""display_looks: the customer display's idle screens, named, one per display (plan step 5.3).
The venue's one idle screen (setting customer_display.idle) becomes the look "Main", the
default; its pictures (files in data/display_media, by name) are processed into the media
library and the look points at them by id. Missing or unreadable files are logged and left
out. The old folder stays on disk. The setting row goes (its SettingDef is gone too).
Revision ID: 0028_display_looks
Revises: 0027_product_media
Create Date: 2026-11-17 18:00:00
"""
import json
import logging
import os
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0028_display_looks'
down_revision = '0027_product_media'
branch_labels = None
depends_on = None
log = logging.getLogger("alembic.0028")
OLD_DIR = os.environ.get("XENIA_DISPLAY_MEDIA_DIR", "/app/data/display_media")
def upgrade() -> None:
op.create_table('display_looks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('is_default', sa.Boolean(), nullable=False),
sa.Column('config', sa.JSON(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('updated_at', UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('display_looks', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_display_looks_id'), ['id'], unique=False)
conn = op.get_bind()
raw = conn.execute(sa.text("SELECT value FROM pos_settings WHERE key = 'customer_display.idle'")).scalar()
try:
cfg = json.loads(raw or "{}") or {}
except ValueError:
cfg = {}
if not isinstance(cfg, dict):
cfg = {}
names = [n for n in [cfg.get("logo"), cfg.get("image"), *(cfg.get("slides") or [])] if isinstance(n, str) and n]
ids = _move_pictures(conn, names)
cfg["logo"] = ids.get(cfg.get("logo"))
cfg["image"] = ids.get(cfg.get("image"))
cfg["slides"] = [ids[n] for n in (cfg.get("slides") or []) if n in ids]
from core.timeutil import DB_FORMAT, utcnow
now = utcnow().strftime(DB_FORMAT)
conn.execute(sa.text("INSERT INTO display_looks (name, is_default, config, created_at, updated_at) VALUES ('Main', 1, :c, :t, :t)"),
{"c": json.dumps(cfg), "t": now})
conn.execute(sa.text("DELETE FROM pos_settings WHERE key = 'customer_display.idle'"))
def _move_pictures(conn, names) -> dict:
"""{old file name: media id} for the pictures that made it into the library."""
if not names:
return {}
from core.timeutil import DB_FORMAT, utcnow
from services import media as store
out = {}
for i, name in enumerate(dict.fromkeys(names), 1):
path = os.path.join(OLD_DIR, os.path.basename(name))
if not os.path.isfile(path):
log.warning("customer display picture %s not found, left out", path)
continue
try:
sha, size, info = store.ingest_path(path)
except Exception as e:
log.warning("customer display picture %s not moved (%s)", path, getattr(e, "code", e))
continue
mid = conn.execute(sa.text("SELECT id FROM media WHERE sha256 = :s"), {"s": sha}).scalar()
if mid is None:
if not info:
store.delete_files(sha)
sha, size, info = store.ingest_path(path)
conn.execute(sa.text(
"INSERT INTO media (kind, name, original_name, content_type, sha256, bytes, width, height, duration_ms, created_at) "
"VALUES (:kind, :name, :orig, :ctype, :sha, :bytes, :w, :h, :d, :at)"),
{"kind": info["kind"], "name": f"Customer display {i}", "orig": os.path.basename(path), "ctype": info["content_type"],
"sha": sha, "bytes": size, "w": info.get("width"), "h": info.get("height"), "d": info.get("duration_ms"),
"at": utcnow().strftime(DB_FORMAT)})
mid = conn.execute(sa.text("SELECT id FROM media WHERE sha256 = :s"), {"s": sha}).scalar()
out[name] = mid
return out
def downgrade() -> None:
with op.batch_alter_table('display_looks', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_display_looks_id'))
op.drop_table('display_looks')
+30
View File
@@ -0,0 +1,30 @@
"""Manager overrides (APPS_PLATFORM D-10, plan step 1.9): audit + single-use tokens.
A user who lacks an overridable permission gets `access.override_possible`; a manager
types their username + PIN on the same screen (POST /api/access/override) and the client
retries with header X-Xenia-Override. One row per approval: who asked (user + session),
who approved, which key, when it was used and on what (`target`). The token is valid for
60 s, once, for that key and that session only; only its sha256 is stored.
Written through core/access/override.py only. Rows are never deleted (audit).
"""
from sqlalchemy import Column, ForeignKey, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class AccessOverride(Base):
__tablename__ = "access_overrides"
__table_args__ = {"sqlite_autoincrement": True}
id = Column(Integer, primary_key=True, autoincrement=True)
key = Column(String, nullable=False, index=True)
token_hash = Column(String, nullable=False, unique=True)
requested_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
requested_session = Column(String, nullable=True) # sessions.id the token is bound to
approved_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True)
created_at = Column(UTCDateTime, nullable=False, default=utcnow, index=True)
expires_at = Column(UTCDateTime, nullable=False)
used_at = Column(UTCDateTime, nullable=True)
target = Column(String, nullable=True) # e.g. "order:12", or "DELETE /api/x/3"
+42
View File
@@ -0,0 +1,42 @@
"""Import every model module so Base.metadata knows the whole schema.
Used by main.py (app startup), migrations/env.py (Alembic autogenerate) and
the tests. Agent note: a new model module MUST be added here, or Alembic
autogenerate will not see it and the drift guard (tests/guards) will not
catch it either.
"""
import models.user # noqa: F401 also registers WaiterZone
import models.table # noqa: F401
import models.printer # noqa: F401
import models.product # noqa: F401
import models.customers # noqa: F401
import models.phone_call # noqa: F401
import models.order # noqa: F401 also registers OrderAuditLog, OrderDiscount, PrintJob
import models.business_day # noqa: F401
import models.shift # noqa: F401 WaiterShift, ShiftBreak
import models.settings # noqa: F401
import models.flag # noqa: F401 TableFlagDef, TableFlagAssignment
import models.message # noqa: F401 StaffMessage, StaffMessageAck, QuickMessageTemplate
import models.reservation # noqa: F401
import models.notes # noqa: F401 SiteNote, SiteTodo
import models.expenses # noqa: F401 Contact, Expense, ExpensePayment
import models.tabs # noqa: F401 Tab, TabEntry, TabPayment
import models.waste # noqa: F401 WasteLog
import models.schedule # noqa: F401 ScheduledShift
import models.chat # noqa: F401 Conversation, ConversationParticipant, ChatMessage
import models.prep_zone # noqa: F401 PrepZone, prep_zone_printers, product_prep_zones
import models.pricing # noqa: F401 PriceGroup, PriceModifier, Deal, PriceEventLog, WaiterDiscountSettings
import models.recovery_code # noqa: F401
import models.sync_event # noqa: F401
import models.site_module # noqa: F401 SiteModule (module enablement, step 1.3)
import models.user_permission # noqa: F401 UserPermission (permission keys, step 1.5)
import models.role_permission # noqa: F401 RolePermission (venue role defaults, step 4.3)
import models.session # noqa: F401 LoginSession (step 1.6)
import models.device # noqa: F401 Device, DevicePairRequest (step 1.8)
import models.access_override # noqa: F401 AccessOverride (manager override, step 1.9)
import models.support_challenge # noqa: F401 SupportChallenge (support access, step 1.10)
import models.notification # noqa: F401 Notification, NotificationRead (step 1.11)
import models.fees # noqa: F401 DeliveryArea, FeeRule (phase 3S, S.3)
import models.refund # noqa: F401 Refund, RefundItem (step 3.3e)
import models.media # noqa: F401 Media (media library, step 5.1)
import models.display_look # noqa: F401 DisplayLook (customer display looks, step 5.3)
+7 -6
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, DateTime, Float, ForeignKey, Text
from sqlalchemy import Column, Date, Integer, String, Float, ForeignKey, Text
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class BusinessDay(Base):
@@ -13,9 +11,12 @@ class BusinessDay(Base):
id = Column(Integer, primary_key=True, index=True)
status = Column(String, default="open", nullable=False) # 'open' | 'closed'
opened_at = Column(DateTime(timezone=True), default=_utcnow, nullable=False)
opened_at = Column(UTCDateTime, default=utcnow, nullable=False)
# The date this day counts as (D-11): set once when the day opens with
# core.timeutil.business_date_of(opened_at), never recalculated. Reports group by it.
business_date = Column(Date, nullable=False, index=True)
opened_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
closed_at = Column(DateTime(timezone=True), nullable=True)
closed_at = Column(UTCDateTime, nullable=True)
closed_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
notes = Column(Text, nullable=True)
# Phase 2E — store-level cash reconciliation
+7 -9
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text, Boolean
from sqlalchemy import Column, Integer, String, ForeignKey, Text, Boolean
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class Conversation(Base):
@@ -16,7 +14,7 @@ class Conversation(Base):
name = Column(String, nullable=True) # required for group
is_system = Column(Boolean, nullable=False, default=False)
created_by = Column(Integer, ForeignKey("users.id"), nullable=True)
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
participants = relationship(
"ConversationParticipant",
@@ -36,8 +34,8 @@ class ConversationParticipant(Base):
id = Column(Integer, primary_key=True, index=True)
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
joined_at = Column(DateTime(timezone=True), default=_utcnow)
last_read_at = Column(DateTime(timezone=True), nullable=True)
joined_at = Column(UTCDateTime, default=utcnow)
last_read_at = Column(UTCDateTime, nullable=True)
conversation = relationship("Conversation", back_populates="participants")
user = relationship("User")
@@ -50,8 +48,8 @@ class ChatMessage(Base):
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False)
sender_id = Column(Integer, ForeignKey("users.id"), nullable=False)
body = Column(Text, nullable=False)
sent_at = Column(DateTime(timezone=True), default=_utcnow)
deleted_at = Column(DateTime(timezone=True), nullable=True)
sent_at = Column(UTCDateTime, default=utcnow)
deleted_at = Column(UTCDateTime, nullable=True)
conversation = relationship("Conversation", back_populates="messages")
sender = relationship("User")
+3 -5
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, ForeignKey
from sqlalchemy import Column, Integer, String, Boolean, Text, ForeignKey
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class Customer(Base):
@@ -18,7 +16,7 @@ class Customer(Base):
email = Column(String, nullable=True)
notes = Column(Text, nullable=True)
is_active = Column(Boolean, default=True, nullable=False)
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
created_by = relationship("User", foreign_keys=[created_by_id])
+52
View File
@@ -0,0 +1,52 @@
"""Paired devices and pairing requests (APPS_PLATFORM D-8, §6.3, plan step 1.8).
A device is shared or unattended hardware (counter PC, KDS screen, TV, tablet) that runs
exactly one app module (`app_key`). It proves itself with a long random token, sent as
header `X-Xenia-Device`; only its sha256 is stored. Personal phones and the manager's
browser are NOT devices (they are user sessions).
Pairing: the device asks for a code (device_pair_requests row, 10 min), a manager enters
the code and creates the Device row, the device's next poll generates the token, stores
its hash and deletes the request. So the plain token is never stored anywhere.
Devices are never deleted: revoked rows keep their token hash so the device is told
`device.revoked` (not "unknown"), and old sessions/audit rows keep a valid device_id.
Read and written through routers/devices.py and core/access/context.py.
"""
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class Device(Base):
__tablename__ = "devices"
__table_args__ = {"sqlite_autoincrement": True} # ids are never reused (sessions point at them)
id = Column(Integer, primary_key=True, autoincrement=True)
uuid = Column(String, nullable=False, unique=True) # public identifier
name = Column(String, nullable=False)
app_key = Column(String, nullable=False, index=True) # a kind="app" module with device_app
config = Column(JSON, nullable=True) # app-specific (e.g. KDS prep zone)
login_mode = Column(String, nullable=True) # NULL = site default auth.default_login_mode
token_hash = Column(String, nullable=True, unique=True) # sha256 hex; NULL until the device picks it up
linked_device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True)
user_agent = Column(String, nullable=True) # from the pairing request
paired_at = Column(UTCDateTime, nullable=False, default=utcnow)
paired_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
claimed_at = Column(UTCDateTime, nullable=True) # when the device received its token
last_seen_at = Column(UTCDateTime, nullable=True)
revoked_at = Column(UTCDateTime, nullable=True, index=True)
revoked_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
class DevicePairRequest(Base):
__tablename__ = "device_pair_requests"
code = Column(String, primary_key=True) # 6 chars, shown on the device
secret_hash = Column(String, nullable=False) # only the requester may poll
created_at = Column(UTCDateTime, nullable=False, default=utcnow)
expires_at = Column(UTCDateTime, nullable=False, index=True)
device_id = Column(Integer, ForeignKey("devices.id", ondelete="CASCADE"), nullable=True) # set on approval
ip = Column(String, nullable=True)
user_agent = Column(String, nullable=True)
+22
View File
@@ -0,0 +1,22 @@
"""Customer display looks (plan step 5.3): named idle screens a venue designs.
One look is the venue's default; each customer display shows the look in its device config
(`look`, a ref to this table) or the default. A look's `config` is routers/customer_display.py
IdleBody: style, message, theme, QR target…, and pictures as media library ids (logo, image,
slides). Those ids are protected in the library while a look uses them.
"""
from sqlalchemy import JSON, Boolean, Column, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class DisplayLook(Base):
__tablename__ = "display_looks"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
is_default = Column(Boolean, nullable=False, default=False)
config = Column(JSON, nullable=False, default=dict)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
+6 -8
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Float, ForeignKey, Text
from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Text
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class Contact(Base):
@@ -19,7 +17,7 @@ class Contact(Base):
address = Column(Text, nullable=True)
notes = Column(Text, nullable=True)
is_active = Column(Boolean, default=True, nullable=False)
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
expenses = relationship("Expense", back_populates="contact")
@@ -33,10 +31,10 @@ class Expense(Base):
contact_id = Column(Integer, ForeignKey("contacts.id"), nullable=True)
total_amount = Column(Float, nullable=False)
paid_amount = Column(Float, default=0.0, nullable=False)
due_date = Column(DateTime(timezone=True), nullable=True)
due_date = Column(UTCDateTime, nullable=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True)
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
notes = Column(Text, nullable=True)
contact = relationship("Contact", back_populates="expenses")
@@ -50,7 +48,7 @@ class ExpensePayment(Base):
id = Column(Integer, primary_key=True, index=True)
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False)
amount = Column(Float, nullable=False)
paid_at = Column(DateTime(timezone=True), default=_utcnow)
paid_at = Column(UTCDateTime, default=utcnow)
paid_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
notes = Column(Text, nullable=True)
+46
View File
@@ -0,0 +1,46 @@
"""Delivery areas and fee rules (plan phase 3S, step S.3).
The venue lists the areas it delivers to (by name, with postcodes when it wants the customer's
postcode matched) and fee rules evaluated in order by services/fees.py — the same engine the
cloud runs at checkout (the rules travel with the menu snapshot). See that module for the
rule semantics.
"""
from sqlalchemy import Column, Float, Integer, String, Text
from core.timeutil import UTCDateTime, utcnow
from database import Base
class DeliveryArea(Base):
__tablename__ = "delivery_areas"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
postcodes = Column(Text, nullable=False, default="[]") # JSON list of strings
is_active = Column(Integer, nullable=False, default=1)
sort_order = Column(Integer, nullable=False, default=0)
created_at = Column(UTCDateTime, default=utcnow)
class FeeRule(Base):
__tablename__ = "fee_rules"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
is_active = Column(Integer, nullable=False, default=1)
sort_order = Column(Integer, nullable=False, default=0)
# conditions (empty / null = any)
sales_points = Column(Text, nullable=False, default='["online_delivery"]') # JSON list
area_ids = Column(Text, nullable=False, default="[]") # JSON list of ints
subtotal_min = Column(Float, nullable=True) # products total >= this
subtotal_max = Column(Float, nullable=True) # products total < this
items_min = Column(Integer, nullable=True) # number of items >= this
items_max = Column(Integer, nullable=True) # number of items <= this
days = Column(Text, nullable=False, default="[]") # JSON list, Mon=0 … Sun=6
time_from = Column(String, nullable=True) # "HH:MM", venue time
time_to = Column(String, nullable=True) # "HH:MM"; before time_from = crosses midnight
# what it does: set | add | percent | free | minimum
action = Column(String, nullable=False, default="set")
value = Column(Float, nullable=False, default=0.0)
stop = Column(Integer, nullable=False, default=0) # no later rule is looked at once this one applies
created_at = Column(UTCDateTime, default=utcnow)
+4 -6
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean
from sqlalchemy import Column, Integer, String, ForeignKey, Boolean
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class TableFlagDef(Base):
@@ -19,7 +17,7 @@ class TableFlagDef(Base):
text_color = Column(String, nullable=True, default=None) # hex text; None = white
sort_order = Column(Integer, default=0, nullable=False)
is_active = Column(Boolean, default=True, nullable=False)
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
assignments = relationship("TableFlagAssignment", back_populates="flag_def", cascade="all, delete-orphan")
@@ -31,7 +29,7 @@ class TableFlagAssignment(Base):
id = Column(Integer, primary_key=True, index=True)
table_id = Column(Integer, ForeignKey("tables.id"), nullable=False)
flag_id = Column(Integer, ForeignKey("table_flag_defs.id"), nullable=False)
assigned_at = Column(DateTime(timezone=True), default=_utcnow)
assigned_at = Column(UTCDateTime, default=utcnow)
assigned_by = Column(Integer, ForeignKey("users.id"), nullable=True)
flag_def = relationship("TableFlagDef", back_populates="assignments")
+40
View File
@@ -0,0 +1,40 @@
"""The media library (plan step 5.1): every picture and video the venue uses, kept once.
A row is one file, identified by the sha256 of its bytes (unique: uploading the same file
again returns the existing row). The bytes live under `data/media/<sha[:2]>/<sha>/`
(services/media.py): the original as uploaded, and for images three WebP sizes (thumb,
card, full). Files are served by hash at `/api/media/file/<sha>/<variant>` with long cache
headers, so a URL never changes meaning: a different file is a different URL.
Rows are referenced by id from what uses them (products, the customer display, signage;
steps 5.2-5.4). Those users register a usage check in services/media.py so a file in use
can't be deleted.
"""
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from core.timeutil import UTCDateTime, utcnow
from database import Base
class Media(Base):
__tablename__ = "media"
id = Column(Integer, primary_key=True, index=True)
kind = Column(String, nullable=False, index=True) # image | video
name = Column(String, nullable=False) # shown in the library; editable
original_name = Column(String, nullable=True) # the uploaded file's name
content_type = Column(String, nullable=False) # of the original
sha256 = Column(String(64), nullable=False, unique=True)
bytes = Column(Integer, nullable=False) # of the original
width = Column(Integer, nullable=True) # images; videos when the file says
height = Column(Integer, nullable=True)
duration_ms = Column(Integer, nullable=True) # videos (MP4) when the file says
uploaded_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
uploader = relationship("User", lazy="joined")
@property
def uploaded_by_name(self):
return self.uploader.full_name or self.uploader.username if self.uploader is not None else None
+5 -7
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text, Boolean
from sqlalchemy import Column, Integer, String, ForeignKey, Text, Boolean
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class QuickMessageTemplate(Base):
@@ -16,7 +14,7 @@ class QuickMessageTemplate(Base):
body = Column(String, nullable=False)
sort_order = Column(Integer, default=0, nullable=False)
is_active = Column(Boolean, default=True, nullable=False)
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
class StaffMessage(Base):
@@ -33,7 +31,7 @@ class StaffMessage(Base):
message_type = Column(String, nullable=False, default="manager")
# kds_zone: display name of the prep zone that sent this (e.g. "Κουζίνα")
kds_zone = Column(String, nullable=True)
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
sender = relationship("User", foreign_keys=[sender_id])
acks = relationship("StaffMessageAck", back_populates="message", cascade="all, delete-orphan")
@@ -46,7 +44,7 @@ class StaffMessageAck(Base):
id = Column(Integer, primary_key=True, index=True)
message_id = Column(Integer, ForeignKey("staff_messages.id"), nullable=False)
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
acked_at = Column(DateTime(timezone=True), default=_utcnow)
acked_at = Column(UTCDateTime, default=utcnow)
message = relationship("StaffMessage", back_populates="acks")
waiter = relationship("User")
+6 -8
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, ForeignKey
from sqlalchemy import Column, Integer, String, Boolean, Text, ForeignKey
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class SiteNote(Base):
@@ -14,8 +12,8 @@ class SiteNote(Base):
id = Column(Integer, primary_key=True, index=True)
body = Column(Text, nullable=False)
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
created_at = Column(DateTime(timezone=True), default=_utcnow)
updated_at = Column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow)
is_pinned = Column(Boolean, default=False, nullable=False)
created_by = relationship("User", foreign_keys=[created_by_id])
@@ -27,10 +25,10 @@ class SiteTodo(Base):
id = Column(Integer, primary_key=True, index=True)
body = Column(Text, nullable=False)
is_done = Column(Boolean, default=False, nullable=False)
done_at = Column(DateTime(timezone=True), nullable=True)
done_at = Column(UTCDateTime, nullable=True)
done_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
priority = Column(String, default="normal", nullable=False) # "normal" | "high"
created_by = relationship("User", foreign_keys=[created_by_id])
+41
View File
@@ -0,0 +1,41 @@
"""Platform notifications (APPS_PLATFORM §10, plan step 1.11).
System messages to staff: license limits and expiry, support access used, print
failures (later: Ergani, close-day reminders). NOT staff chat or manager messages
(models/message.py, F-030), which stay separate.
- The text is an i18n key (`notification.<key>` in core/i18n/*.json) + params, rendered
in the reader's language when listed.
- audience: "all_managers" (holders of core.dashboard.access) | "perm:<key>" | "user:<id>".
- dedupe_key: while a row with the same key is still live (expires_at NULL or future),
notify() bumps its `count` / `last_at` instead of adding a row.
Written through core/notifications.py only.
"""
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class Notification(Base):
__tablename__ = "notifications"
__table_args__ = {"sqlite_autoincrement": True}
id = Column(Integer, primary_key=True, autoincrement=True)
key = Column(String, nullable=False, index=True) # e.g. "license.limit_reached"
severity = Column(String, nullable=False, default="info") # info | warning | critical
audience = Column(String, nullable=False, index=True)
params = Column(JSON, nullable=True)
dedupe_key = Column(String, nullable=True, index=True)
count = Column(Integer, nullable=False, default=1) # occurrences folded in by dedupe
created_at = Column(UTCDateTime, nullable=False, default=utcnow, index=True)
last_at = Column(UTCDateTime, nullable=False, default=utcnow)
expires_at = Column(UTCDateTime, nullable=True) # hidden (and dedupe ends) after this
class NotificationRead(Base):
__tablename__ = "notification_reads"
notification_id = Column(Integer, ForeignKey("notifications.id", ondelete="CASCADE"), primary_key=True)
user_id = Column(Integer, primary_key=True) # no FK: the support account (id 0) can read too
read_at = Column(UTCDateTime, nullable=False, default=utcnow)
+67 -18
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, Boolean, Float, DateTime, ForeignKey, Text
from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Text
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class Order(Base):
@@ -14,16 +12,17 @@ class Order(Base):
id = Column(Integer, primary_key=True, index=True)
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True) # nullable for online orders
opened_by = Column(Integer, ForeignKey("users.id"), nullable=False)
opened_at = Column(DateTime(timezone=True), default=_utcnow)
opened_at = Column(UTCDateTime, default=utcnow)
status = Column(String, default="open", nullable=False) # open|partially_paid|paid|closed|cancelled
closed_at = Column(DateTime, nullable=True)
closed_at = Column(UTCDateTime, nullable=True)
closed_by = Column(Integer, ForeignKey("users.id"), nullable=True)
notes = Column(Text, nullable=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True)
# KDS
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done
kds_status_changed_at = Column(DateTime(timezone=True), nullable=True)
kds_status_changed_at = Column(UTCDateTime, nullable=True)
order_type = Column(String, default="here", nullable=False) # here|takeaway|delivery
sales_point = Column(String, default="in_store", nullable=False) # core/sales_points.py (phase 3S)
# Xenia Connect — online order fields
source = Column(String, default="pos", nullable=False) # "pos" | "online"
@@ -35,6 +34,12 @@ class Order(Base):
online_customer_address = Column(Text, nullable=True)
online_customer_notes = Column(Text, nullable=True)
online_order_type = Column(String, nullable=True) # "delivery" | "dine_in"
online_delivery_area = Column(String, nullable=True) # the area's name (phase 3S, S.5)
# the site's own price check when the order was pulled (S.5): NULL = the cloud's prices
# match the site's; else JSON {lines: [...], fee: {...}|null} (services/online_check.py)
online_price_diff = Column(Text, nullable=True)
# when the customer wants it (S.5); NULL = as soon as possible
requested_for = Column(UTCDateTime, nullable=True)
# Phase 2F — customer CRM
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=True)
@@ -62,7 +67,7 @@ class OrderWaiter(Base):
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
assigned_at = Column(DateTime(timezone=True), default=_utcnow)
assigned_at = Column(UTCDateTime, default=utcnow)
order = relationship("Order", back_populates="waiters")
waiter = relationship("User", back_populates="order_assignments")
@@ -77,17 +82,24 @@ class OrderItem(Base):
added_by = Column(Integer, ForeignKey("users.id"), nullable=False)
quantity = Column(Float, nullable=False)
unit_price = Column(Float, nullable=False) # price snapshot at time of order
# Name snapshots (D-18, CS-4): what the item was called, and its category, when it was
# ordered. Reports read these, so renaming or moving a product never rewrites history.
# Filled automatically for every new item by the before_flush hook at the end of this
# file; never updated afterwards. category_id is a plain id (categories can be deleted).
product_name = Column(String, nullable=False)
category_id = Column(Integer, nullable=True, index=True)
category_name = Column(String, nullable=True)
selected_options = Column(Text, nullable=True) # JSON array of option ids
removed_ingredients = Column(Text, nullable=True) # JSON array of ingredient ids
notes = Column(Text, nullable=True)
status = Column(String, default="active", nullable=False) # active|paid|cancelled
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done|served|declined
added_at = Column(DateTime(timezone=True), default=_utcnow)
added_at = Column(UTCDateTime, default=utcnow)
printed = Column(Boolean, default=False, nullable=False)
# Payment tracking
paid_by = Column(Integer, ForeignKey("users.id"), nullable=True)
paid_at = Column(DateTime, nullable=True)
paid_at = Column(UTCDateTime, nullable=True)
payment_method = Column(String, nullable=True) # 'cash'|'card'|'other' — future use
paid_in_shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True)
@@ -99,14 +111,20 @@ class OrderItem(Base):
# Phase 2B — cancellation tracking
cancelled_by = Column(Integer, ForeignKey("users.id"), nullable=True)
cancelled_at = Column(DateTime(timezone=True), nullable=True)
cancelled_at = Column(UTCDateTime, nullable=True)
cancel_reason = Column(Text, nullable=True)
# KDS decline tracking
decline_note = Column(Text, nullable=True) # reason set by kitchen when declining
# KDS claim (plan step 3.2c): the cook working on this item; cleared when it moves on
claimed_by = Column(Integer, ForeignKey("users.id"), nullable=True)
claimed_at = Column(UTCDateTime, nullable=True)
# Courses — optional course assignment for sequenced firing
course_id = Column(Integer, nullable=True)
# where the line came from (plan step 4.8): waiter | counter | qr | online; NULL = before 4.8
source = Column(String, nullable=True)
# Deal binding — which deal created this item, and which original item it's linked to
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
@@ -116,11 +134,17 @@ class OrderItem(Base):
product = relationship("Product", back_populates="order_items")
added_by_user = relationship("User", foreign_keys=[added_by], back_populates="order_items")
paid_by_user = relationship("User", foreign_keys=[paid_by], back_populates="items_paid")
claimed_by_user = relationship("User", foreign_keys=[claimed_by])
@property
def unit_type(self) -> str:
return self.product.unit_type if self.product and self.product.unit_type else "piece"
@property
def system_key(self):
"""A line the system added (the delivery fee, S.5): its product's system_key, else None."""
return self.product.system_key if self.product is not None else None
class PrintLog(Base):
__tablename__ = "print_log"
@@ -128,7 +152,7 @@ class PrintLog(Base):
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False)
printed_at = Column(DateTime(timezone=True), default=_utcnow)
printed_at = Column(UTCDateTime, default=utcnow)
item_ids = Column(Text, nullable=False) # JSON array of order_item ids
success = Column(Boolean, nullable=False)
error_message = Column(Text, nullable=True)
@@ -153,10 +177,10 @@ class PrintJob(Base):
status = Column(String, nullable=False, default="pending") # pending|success|cancelled
retry_count = Column(Integer, nullable=False, default=0)
first_attempted_at = Column(DateTime(timezone=True), default=_utcnow)
last_attempted_at = Column(DateTime(timezone=True), nullable=True)
succeeded_at = Column(DateTime(timezone=True), nullable=True)
cancelled_at = Column(DateTime(timezone=True), nullable=True)
first_attempted_at = Column(UTCDateTime, default=utcnow)
last_attempted_at = Column(UTCDateTime, nullable=True)
succeeded_at = Column(UTCDateTime, nullable=True)
cancelled_at = Column(UTCDateTime, nullable=True)
cancel_reason = Column(String, nullable=True) # "staff_cancelled" | "order_closed"
order = relationship("Order", back_populates="print_jobs")
@@ -176,7 +200,7 @@ class OrderAuditLog(Base):
amount = Column(Float, nullable=True) # total value for PAYMENT events
payment_method = Column(String, nullable=True)
note = Column(Text, nullable=True)
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
# Emergency offline payment fields
offline_uuid = Column(String, nullable=True) # client-generated UUID for dedup
offline_at = Column(String, nullable=True) # ISO timestamp from client
@@ -200,9 +224,34 @@ class OrderDiscount(Base):
discount_type = Column(String, nullable=False) # 'percent' | 'fixed'
discount_value = Column(Float, nullable=False) # e.g. 10.0 = 10% or €10.00
applied_by = Column(Integer, ForeignKey("users.id"), nullable=False)
applied_at = Column(DateTime(timezone=True), default=_utcnow)
applied_at = Column(UTCDateTime, default=utcnow)
reason = Column(Text, nullable=True)
order = relationship("Order", back_populates="discounts")
item = relationship("OrderItem")
applied_by_user = relationship("User")
# ── Name snapshots for new order items (D-18) ────────────────────────────────
from sqlalchemy import event as _event # noqa: E402
from sqlalchemy.orm import Session as _Session # noqa: E402
@_event.listens_for(_Session, "before_flush")
def _snapshot_item_names(session, flush_context, instances):
"""Every new OrderItem gets the product's current name and category, whoever creates
it (waiter, counter, online orders, deals, demo seed). An item created with a
product_name already set is left alone: the caller snapshots everything itself
(the v1 importer, plan 7.1)."""
from models.product import Category, Product
for obj in session.new:
if not isinstance(obj, OrderItem) or obj.product_name:
continue
product = session.get(Product, obj.product_id) if obj.product_id is not None else None
obj.product_name = product.name if product else f"#{obj.product_id}"
if obj.category_id is None and product is not None and product.primary_category_id is not None:
obj.category_id = product.primary_category_id # the PRIMARY category (D-23)
if obj.category_id is not None and obj.category_name is None:
cat = session.get(Category, obj.category_id)
obj.category_name = cat.name if cat else None
+15
View File
@@ -0,0 +1,15 @@
from sqlalchemy import Column, ForeignKey, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class PhoneCall(Base):
"""An incoming call the venue's phone system reported (caller ID, plan step 3.5)."""
__tablename__ = "phone_calls"
id = Column(Integer, primary_key=True, index=True)
at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
number = Column(String, nullable=False) # as the phone system sent it
ext = Column(String, nullable=True) # the extension that was dialled
customer_id = Column(Integer, ForeignKey("customers.id", ondelete="SET NULL"), nullable=True)
+2
View File
@@ -27,6 +27,8 @@ class PrepZone(Base):
name = Column(String, nullable=False)
description = Column(String, nullable=True)
notification_name = Column(String, nullable=True)
# Language of this zone's kitchen tickets (D-12). NULL = venue.language.
language = Column(String, nullable=True)
# Printer routing
# auto_print: 'none' | 'master' | 'all'
+10 -12
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, Boolean, Float, DateTime, ForeignKey, Text
from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Text
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class PriceGroup(Base):
@@ -24,7 +22,7 @@ class PriceGroup(Base):
auto_disable_time = Column(String, nullable=True) # "HH:MM" 24h
auto_days = Column(Text, nullable=True) # JSON [0..6], Mon=0
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
created_by = Column(Integer, ForeignKey("users.id"), nullable=True)
@@ -66,9 +64,9 @@ class PriceModifier(Base):
# System-wide nearest-0.10 rounding is always applied as a final pass regardless.
round_to = Column(String, nullable=True) # '0.05'|'0.10'|'0.20'|'0.50'|'x.99'|'x.00'
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
created_by = Column(Integer, ForeignKey("users.id"), nullable=True)
updated_at = Column(DateTime(timezone=True), nullable=True)
updated_at = Column(UTCDateTime, nullable=True)
updated_by = Column(Integer, ForeignKey("users.id"), nullable=True)
conditions = relationship("PriceModifierCondition", back_populates="modifier",
@@ -91,7 +89,7 @@ class PriceModifierCondition(Base):
min_item_quantity {"min": N} (this product's qty in cart)
min_category_qty {"category_id": N, "min": N} (items in category in cart)
min_order_value {"min": 0.00} (cart total before modifiers)
order_channel {"channels": ["pos","online","qr","takeaway"]}
order_channel {"channels": [sales point, ...]} (core/sales_points.py; phase 3S)
price_group_active {"price_group_id": N}
user_tier {"tiers": ["bronze","silver","gold"]} (placeholder, needs user accounts)
low_stock {"threshold": N} (placeholder, needs inventory)
@@ -166,7 +164,7 @@ class Deal(Base):
action_free_target_ids = Column(Text, nullable=True) # JSON array of IDs or tag strings
action_free_quantity = Column(Integer, nullable=False, default=1)
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
created_by = Column(Integer, ForeignKey("users.id"), nullable=True)
conditions = relationship("DealCondition", back_populates="deal",
@@ -216,8 +214,8 @@ class PriceEventLog(Base):
__tablename__ = "price_event_log"
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) # NULL for order-level events
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True) # NULL for order-level events
# Event classification
event_type = Column(String, nullable=False)
@@ -249,7 +247,7 @@ class PriceEventLog(Base):
# For deal_offer_accepted: product IDs the waiter chose
selected_item_ids = Column(Text, nullable=True) # JSON array of product IDs
applied_at = Column(DateTime(timezone=True), default=_utcnow)
applied_at = Column(UTCDateTime, default=utcnow)
order = relationship("Order", foreign_keys=[order_id])
order_item = relationship("OrderItem", foreign_keys=[order_item_id])
-1
View File
@@ -16,7 +16,6 @@ class Printer(Base):
duplicates = Column(Integer, default=0, nullable=False)
codepage_n = Column(Integer, default=29, nullable=False)
products = relationship("Product", back_populates="printer_zone")
print_logs = relationship("PrintLog", back_populates="printer")
print_jobs = relationship("PrintJob", back_populates="printer")
prep_zones = relationship("PrepZone", secondary="prep_zone_printers", back_populates="printers")
+68 -12
View File
@@ -1,6 +1,9 @@
from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Text
from sqlalchemy.orm import relationship
from database import Base
from core.sales_points import ALL as _SALES_POINTS, dump as _dump_sales_points
_ALL_SALES_POINTS = _dump_sales_points(_SALES_POINTS)
class Category(Base):
@@ -16,8 +19,19 @@ class Category(Base):
general_sort_order = Column(Integer, default=0, nullable=False)
# sub-categories only: if True, the accordion section is expanded by default on the PWA
auto_expanded = Column(Boolean, default=False, nullable=False)
# Its picture in the media library (plan step 5.2); the library refuses to delete it while set
media_id = Column(Integer, ForeignKey("media.id", ondelete="SET NULL"), nullable=True, index=True)
media = relationship("Media", lazy="joined")
products = relationship("Product", back_populates="category")
@property
def image(self):
from services.media import image_of
return image_of(self.media)
# Products whose PRIMARY category this is (tickets, reports). Every product listed in
# this category, primary or not: `memberships` (ProductCategory, D-23).
primary_products = relationship("Product", back_populates="primary_category")
memberships = relationship("ProductCategory", back_populates="category", cascade="all, delete-orphan")
subcategories = relationship("Category", back_populates="parent", foreign_keys="Category.parent_id")
parent = relationship("Category", back_populates="subcategories", remote_side="Category.id", foreign_keys="Category.parent_id")
@@ -28,24 +42,32 @@ class Product(Base):
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
description = Column(Text, nullable=True)
category_id = Column(Integer, ForeignKey("categories.id"), nullable=True)
# D-23: a product can be listed in several categories (product_categories). The primary
# one decides ticket grouping, prep-zone category order and the category order items
# snapshot (D-18). It is always one of the product's categories (routers/products.py).
primary_category_id = Column(Integer, ForeignKey("categories.id"), nullable=True, index=True)
base_price = Column(Float, nullable=False)
is_available = Column(Boolean, default=True, nullable=False)
# "active" | "archived" — archived products are kept for order history but hidden from active use
# "active" | "archived" — archived products are kept for order history but hidden from active use;
# "system" — a line the system adds itself (services/system_products.py), never on a menu
lifecycle_status = Column(String, default="active", nullable=False)
printer_zone_id = Column(Integer, ForeignKey("printers.id"), nullable=True)
image_url = Column(String, nullable=True)
# system products only (phase 3S, S.5): what the line is, e.g. "delivery_fee"
system_key = Column(String, nullable=True, unique=True, index=True)
# Its photo in the media library (plan step 5.2; the old image_url files moved there in 0027)
media_id = Column(Integer, ForeignKey("media.id", ondelete="SET NULL"), nullable=True, index=True)
media = relationship("Media", lazy="joined")
sort_order = Column(Integer, default=0, nullable=False)
# Xenia Connect — digital menu overrides
digital_visible = Column(Integer, default=1, nullable=False)
# Where it's sold (phase 3S): JSON list of sales points (core/sales_points.py). Prices
# per sales point are price modifiers (condition order_channel), not columns.
sold_at = Column(Text, nullable=False, default=_ALL_SALES_POINTS)
# Xenia Connect — what the customer apps show (name, text, picture); digital_available =
# orderable online right now (a temporary switch, like is_available)
digital_available = Column(Integer, default=1, nullable=False)
digital_name = Column(String, nullable=True)
digital_description = Column(String, nullable=True)
digital_price = Column(Float, nullable=True)
digital_discount = Column(Float, default=0.0, nullable=False)
digital_image_url = Column(String, nullable=True)
# sha256 of the image_url file last successfully pushed to the cloud — lets
# sha256 of the photo file (card size) last successfully pushed to the cloud — lets
# cloud_sync skip re-uploading unchanged images on every sync tick
cloud_image_hash = Column(String, nullable=True)
@@ -69,8 +91,18 @@ class Product(Base):
fiscal_name = Column(String, nullable=True) # short name for receipt (falls back to name)
fiscal_vat_group_id = Column(Integer, nullable=True) # machine VAT group ID (1-based integer)
category = relationship("Category", back_populates="products")
printer_zone = relationship("Printer", back_populates="products")
primary_category = relationship("Category", back_populates="primary_products")
memberships = relationship("ProductCategory", back_populates="product", cascade="all, delete-orphan",
order_by="ProductCategory.category_id")
@property
def category_ids(self) -> list[int]:
"""The categories it's listed in, primary first."""
ids = [m.category_id for m in self.memberships]
if self.primary_category_id in ids:
ids.remove(self.primary_category_id)
ids.insert(0, self.primary_category_id)
return ids
prep_zones = relationship("PrepZone", secondary="product_prep_zones", back_populates="products")
quick_options = relationship("ProductQuickOption", back_populates="product", cascade="all, delete-orphan")
options = relationship("ProductOption", back_populates="product", cascade="all, delete-orphan")
@@ -79,6 +111,17 @@ class Product(Base):
modifier_groups = relationship("ProductModifierGroup", back_populates="product", cascade="all, delete-orphan")
order_items = relationship("OrderItem", back_populates="product")
@property
def image(self):
"""{"id", "name", "thumb", "card", "full"} of its photo, or None."""
from services.media import image_of
return image_of(self.media)
@property
def image_url(self):
"""The card size of its photo (what the phones and the counter show), or None."""
return (self.image or {}).get("card")
class ProductModifierGroup(Base):
"""A named folder/group that can contain options, ingredients, or preference sets."""
@@ -188,3 +231,16 @@ class ProductPreferenceChoice(Base):
is_compact = Column(Boolean, default=False, nullable=False)
set = relationship("ProductPreferenceSet", back_populates="choices")
class ProductCategory(Base):
"""A product listed in a category, with its position in that category's list (D-23)."""
__tablename__ = "product_categories"
product_id = Column(Integer, ForeignKey("products.id", ondelete="CASCADE"), primary_key=True)
category_id = Column(Integer, ForeignKey("categories.id", ondelete="CASCADE"), primary_key=True, index=True)
sort_order = Column(Integer, nullable=False, default=0)
product = relationship("Product", back_populates="memberships")
category = relationship("Category", back_populates="memberships")
+4 -6
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy import Column, Integer, String, ForeignKey
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class RecoveryCode(Base):
@@ -14,7 +12,7 @@ class RecoveryCode(Base):
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
code_hash = Column(String, nullable=False)
created_at = Column(DateTime(timezone=True), default=_utcnow, nullable=False)
used_at = Column(DateTime(timezone=True), nullable=True)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
used_at = Column(UTCDateTime, nullable=True)
user = relationship("User", backref="recovery_codes")
+45
View File
@@ -0,0 +1,45 @@
"""Refunds (plan step 3.3e): money given back for paid items, kept apart from the sale.
The paid items are never edited: a refund row says how much of which items went back, how
(cash from the drawer or back to the card), in whose shift (that cashier's cash goes down)
and what the fiscal device made of it (a credit note, or done by hand on the machine).
"""
from sqlalchemy import Column, Float, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
from core.timeutil import UTCDateTime, utcnow
from database import Base
class Refund(Base):
__tablename__ = "refunds"
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True, index=True) # the refunding cashier's
refunded_by = Column(Integer, ForeignKey("users.id"), nullable=False)
approved_by = Column(Integer, ForeignKey("users.id"), nullable=True) # a manager's override, if one was needed
device_id = Column(Integer, ForeignKey("devices.id"), nullable=True)
method = Column(String, nullable=False) # cash | card
amount = Column(Float, nullable=False)
reason = Column(Text, nullable=True)
# None (fiscal off) | manual (cashier issues it on the machine) | pending | success | failed
fiscal_status = Column(String, nullable=True)
fiscal_reference = Column(String, nullable=True)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
items = relationship("RefundItem", back_populates="refund", cascade="all, delete-orphan")
class RefundItem(Base):
__tablename__ = "refund_items"
id = Column(Integer, primary_key=True, index=True)
refund_id = Column(Integer, ForeignKey("refunds.id", ondelete="CASCADE"), nullable=False, index=True)
order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=False, index=True)
quantity = Column(Float, nullable=False)
amount = Column(Float, nullable=False)
refund = relationship("Refund", back_populates="items")
order_item = relationship("OrderItem")
+20 -7
View File
@@ -1,6 +1,6 @@
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text
from sqlalchemy import Column, Float, Integer, String, ForeignKey, Text
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
@@ -17,12 +17,13 @@ class Reservation(Base):
note = Column(Text, nullable=True)
# When the customer wants the table
reserved_for = Column(DateTime, nullable=False)
reserved_for = Column(UTCDateTime, nullable=False)
# Optional table assignment (assignable/editable later)
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
# Lifecycle: pending | arrived | cancelled | no_show
# Lifecycle: pending (confirmed, upcoming) | arrived | cancelled | no_show;
# online requests (phase 3S, S.6) start as requested → pending (confirmed) | declined
status = Column(String, nullable=False, default="pending")
# Source: manager_app | waiter_app | online
@@ -34,9 +35,21 @@ class Reservation(Base):
# For future online reservations: cloud-side customer identifier
online_customer_id = Column(String, nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc),
onupdate=lambda: datetime.now(timezone.utc))
# Online bookings (phase 3S, S.6): the cloud's order (status mirrored to the customer's page)
online_order_cloud_id = Column(Integer, nullable=True, index=True)
online_ref = Column(String, nullable=True) # "ORD-0042"
# food ordered ahead: the cloud's lines (its prices) until the kitchen gets them, then the order
items_json = Column(Text, nullable=True) # JSON list as the cloud sent it; NULL = a table only
total = Column(Float, nullable=True)
online_price_diff = Column(Text, nullable=True) # services/online_check.py; NULL = matched
fire_at = Column(UTCDateTime, nullable=True) # when the kitchen gets the food (set on confirming)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=True) # created at fire time
response_note = Column(Text, nullable=True) # why it was declined / cancelled (the customer sees it)
created_at = Column(UTCDateTime, default=utcnow)
updated_at = Column(UTCDateTime, default=utcnow,
onupdate=utcnow)
table = relationship("Table", foreign_keys=[table_id])
order = relationship("Order", foreign_keys=[order_id])
created_by = relationship("User", foreign_keys=[created_by_user_id])
+19
View File
@@ -0,0 +1,19 @@
"""The venue's own role defaults (plan step 4.3).
A role's default keys come from the manifests (Perm(..., roles=...)). A venue can change
them in the manager (Settings → Operation → "What each role may do"): one row per key it
adds to (granted=True) or removes from (granted=False) a role. role_template(role, db)
applies them; new staff get the venue's version, and a change is also applied to every
person who has that role (core/access/templates.py::set_role_keys).
"""
from sqlalchemy import Boolean, Column, String
from database import Base
class RolePermission(Base):
__tablename__ = "role_permissions"
role = Column(String, primary_key=True)
key = Column(String, primary_key=True)
granted = Column(Boolean, nullable=False)
+3 -5
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, Date, Time, Text, DateTime, ForeignKey
from sqlalchemy import Column, Integer, String, Date, Time, Text, ForeignKey
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class ScheduledShift(Base):
@@ -18,7 +16,7 @@ class ScheduledShift(Base):
end_time = Column(String, nullable=False)
notes = Column(Text, nullable=True)
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
created_at = Column(DateTime(timezone=True), default=_utcnow)
created_at = Column(UTCDateTime, default=utcnow)
user = relationship("User", foreign_keys=[user_id])
created_by = relationship("User", foreign_keys=[created_by_id])
+28
View File
@@ -0,0 +1,28 @@
"""Login sessions (APPS_PLATFORM D-9, §6.2).
One row per login. The JWT carries the row id as `sid`; a request is accepted only while
its session is active (ended_at NULL). This makes logout real, survives restarts, lets
managers see and end sessions, and enforces the one-session-per-user rules.
Read and written through core/sessions.py only.
"""
from sqlalchemy import Column, ForeignKey, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class LoginSession(Base):
__tablename__ = "sessions"
id = Column(String, primary_key=True) # uuid4 hex
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=True, index=True)
# NULL user_id = the support account (synthetic, no users row; step 1.10)
device_id = Column(Integer, ForeignKey("devices.id"), nullable=True, index=True) # terminal sessions: the device
client = Column(String, nullable=False) # manager | waiter | terminal | support
created_at = Column(UTCDateTime, nullable=False, default=utcnow)
last_seen_at = Column(UTCDateTime, nullable=False, default=utcnow)
ended_at = Column(UTCDateTime, nullable=True, index=True)
expires_at = Column(UTCDateTime, nullable=True) # hard end (support sessions: 4 h); NULL = none
end_reason = Column(String, nullable=True) # logout | replaced | ended_by_manager | user_blocked | refreshed | device_revoked | device_reassigned | expired
ip = Column(String, nullable=True)
user_agent = Column(String, nullable=True)
+3 -5
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy import Column, Integer, String, ForeignKey
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class PosSettings(Base):
@@ -13,7 +11,7 @@ class PosSettings(Base):
key = Column(String, primary_key=True)
value = Column(String, nullable=False)
updated_at = Column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
updated_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
updated_by = relationship("User", foreign_keys=[updated_by_id])
+6 -8
View File
@@ -1,11 +1,9 @@
from sqlalchemy import Column, Integer, Float, DateTime, ForeignKey, Text
from sqlalchemy import Column, Integer, Float, ForeignKey, Text
from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base
def _utcnow():
return datetime.now(timezone.utc)
class WaiterShift(Base):
@@ -14,8 +12,8 @@ class WaiterShift(Base):
id = Column(Integer, primary_key=True, index=True)
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=False)
started_at = Column(DateTime(timezone=True), default=_utcnow, nullable=False)
ended_at = Column(DateTime(timezone=True), nullable=True)
started_at = Column(UTCDateTime, default=utcnow, nullable=False)
ended_at = Column(UTCDateTime, nullable=True)
starting_cash = Column(Float, nullable=True)
total_collected = Column(Float, nullable=True) # snapshot written at shift end
notes = Column(Text, nullable=True)
@@ -35,7 +33,7 @@ class ShiftBreak(Base):
id = Column(Integer, primary_key=True, index=True)
shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=False)
started_at = Column(DateTime(timezone=True), default=_utcnow, nullable=False)
ended_at = Column(DateTime(timezone=True), nullable=True)
started_at = Column(UTCDateTime, default=utcnow, nullable=False)
ended_at = Column(UTCDateTime, nullable=True)
shift = relationship("WaiterShift", back_populates="breaks")
+19
View File
@@ -0,0 +1,19 @@
"""Site enablement of modules (APPS_PLATFORM §5.3, D-4).
A module with no row is enabled (opt-out). Disabling keeps all data; it hides the UI,
makes the module's endpoints answer `module.disabled` and stops its workers.
Read and written through core/modules/state.py only.
"""
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class SiteModule(Base):
__tablename__ = "site_modules"
key = Column(String, primary_key=True)
enabled = Column(Boolean, nullable=False, default=True)
updated_at = Column(UTCDateTime, nullable=False, default=utcnow, onupdate=utcnow)
updated_by = Column(Integer, ForeignKey("users.id"), nullable=True)
+26
View File
@@ -0,0 +1,26 @@
"""Support access challenges (APPS_PLATFORM D-16, §6.5, plan step 1.10).
One row per challenge shown on a login screen ("Support access"). It is valid for 15 min,
once, with a few wrong tries. A used row is the audit record of a support login: when,
from where and which session it opened. Rows are never deleted.
Written through routers/auth.py (support endpoints) only.
"""
from sqlalchemy import Column, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class SupportChallenge(Base):
__tablename__ = "support_challenges"
__table_args__ = {"sqlite_autoincrement": True}
id = Column(Integer, primary_key=True, autoincrement=True)
challenge = Column(String, nullable=False, unique=True) # normalized, 8 chars
created_at = Column(UTCDateTime, nullable=False, default=utcnow)
expires_at = Column(UTCDateTime, nullable=False, index=True)
attempts = Column(Integer, nullable=False, default=0) # wrong codes entered
used_at = Column(UTCDateTime, nullable=True)
session_id = Column(String, nullable=True) # the support session it opened
ip = Column(String, nullable=True)
user_agent = Column(String, nullable=True)
+24
View File
@@ -0,0 +1,24 @@
"""WebSocket replay buffer (F-014): every broadcast event gets a seq id the clients resume from.
Written and read with raw SQL in services/ws_bus.py (hot path, no ORM). The model
exists so the table is part of the Alembic-managed schema.
- sqlite_autoincrement: ids must never be reused after old rows are pruned, or a
client's cursor could skip events.
- created_at is a UTCDateTime; ws_bus writes it with core.timeutil.to_db_str() so the
raw-SQL text matches what the type stores (prune compares the text).
"""
from sqlalchemy import Column, Integer, String, Text
from core.timeutil import UTCDateTime
from database import Base
class SyncEvent(Base):
__tablename__ = "sync_events"
__table_args__ = {"sqlite_autoincrement": True}
id = Column(Integer, primary_key=True)
event_type = Column(String, nullable=False)
payload = Column(Text, nullable=False)
target_user_ids = Column(Text, nullable=True) # JSON list; NULL = not addressed to users
target_device_ids = Column(Text, nullable=True) # JSON list of devices (plan 3.1a); NULL = none
created_at = Column(UTCDateTime, nullable=False, index=True)

Some files were not shown because too many files have changed in this diff Show More