Compare commits
226
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f107deca8c | ||
|
|
096bd53dbd | ||
|
|
7706bf2470 | ||
|
|
3eeafb565a | ||
|
|
72e175ab73 | ||
|
|
0a353c5f97 | ||
|
|
f87f9ff23c | ||
|
|
e3f4f3eeee | ||
|
|
e708202f3a | ||
|
|
99145e83da | ||
|
|
33a5125abc | ||
|
|
cd8218689c | ||
|
|
1b111c0e27 | ||
|
|
0bd32d9171 | ||
|
|
84c2d5b2d8 | ||
|
|
673113aff7 | ||
|
|
1eb7e5e3a9 | ||
|
|
189bd2777b | ||
|
|
f26e51273c | ||
|
|
2a38602d45 | ||
|
|
1c8d45e00c | ||
|
|
d5c19e17ce | ||
|
|
14d592d963 | ||
|
|
aa8ba5d1d4 | ||
|
|
aa3fe85053 | ||
|
|
aaa0914778 | ||
|
|
e8c8ec825e | ||
|
|
1b993e4573 | ||
|
|
83551714f7 | ||
|
|
60e6a16217 | ||
|
|
abab158b7c | ||
|
|
15413dea1b | ||
|
|
301502965c | ||
|
|
181b2f16b0 | ||
|
|
1053703f0d | ||
|
|
f158124aff | ||
|
|
9021373a6b | ||
|
|
244e93f827 | ||
|
|
476c55abc0 | ||
|
|
94c10944ed | ||
|
|
f3fc3340d2 | ||
|
|
9297cbcd3b | ||
|
|
5915177c82 | ||
|
|
87cd90c8f5 | ||
|
|
b77bb8bb40 | ||
|
|
618fef53ef | ||
|
|
fd917797a7 | ||
|
|
6f4ab23582 | ||
|
|
26ba19cba5 | ||
|
|
ebb3fac6bc | ||
|
|
2b44d55f81 | ||
|
|
f383060bad | ||
|
|
294b769850 | ||
|
|
f6fcfb7736 | ||
|
|
bde125bf09 | ||
|
|
07c9a0aecf | ||
|
|
93c0dd7d9c | ||
|
|
6bdf0bdd79 | ||
|
|
7767bdb728 | ||
|
|
4df59c33ef | ||
|
|
6643614ff6 | ||
|
|
f31bdf42aa | ||
|
|
070c9cf625 | ||
|
|
f4aae6abbc | ||
|
|
fd3254aa31 | ||
|
|
c1af7770cf | ||
|
|
c43dc8b55b | ||
|
|
e395d99704 | ||
|
|
5048f82a4c | ||
|
|
8a02173450 | ||
|
|
2dc5da446e | ||
|
|
218a6c9c5e | ||
|
|
b5361e10ca | ||
|
|
f8d0d29d8f | ||
|
|
cc81e0a31f | ||
|
|
2a6640fe5c | ||
|
|
6c982e3139 | ||
|
|
5f6b51fb8b | ||
|
|
152388321e | ||
|
|
4d63216167 | ||
|
|
314e9c2457 | ||
|
|
e90c2f4f8f | ||
|
|
e612e2436c | ||
|
|
0d766d3c86 | ||
|
|
b5951ba373 | ||
|
|
97140b13f9 | ||
|
|
a2d9e55222 | ||
|
|
7fc32ad917 | ||
|
|
51b764fe7e | ||
|
|
6d84e43330 | ||
|
|
27d7bbb976 | ||
|
|
87dff573df | ||
|
|
15bd0f5b57 | ||
|
|
e09056a7a4 | ||
|
|
5ad4c4ef55 | ||
|
|
238f8ec5a0 | ||
|
|
24971533a0 | ||
|
|
1fc34d6c9e | ||
|
|
eba630e06e | ||
|
|
f57894dcb7 | ||
|
|
1e8271e370 | ||
|
|
198f8ff571 | ||
|
|
beb53c65bb | ||
|
|
d8c3a6c57c | ||
|
|
9e1912bce0 | ||
|
|
f8d91e7fae | ||
|
|
2c4f78af47 | ||
|
|
37155c0457 | ||
|
|
8e0a786bbc | ||
|
|
bcf91bf6e9 | ||
|
|
8abe4d92d3 | ||
|
|
a29a167977 | ||
|
|
8299184e3a | ||
|
|
9f5498332a | ||
|
|
f85894a72e | ||
|
|
d0c6a10e47 | ||
|
|
dabe807ce0 | ||
|
|
88a9703902 | ||
|
|
18d580d87c | ||
|
|
652e6a26af | ||
|
|
70c8f2bb57 | ||
|
|
0ca700279a | ||
|
|
8ea44d71aa | ||
|
|
df27133af9 | ||
|
|
9bfe54554d | ||
|
|
ffeb2b45cb | ||
|
|
1b468fe44b | ||
|
|
f2182dcb37 | ||
|
|
d542cf7d34 | ||
|
|
988d413d8e | ||
|
|
bff82a332a | ||
|
|
17bee66df1 | ||
|
|
b1112b249e | ||
|
|
6b237fd169 | ||
|
|
77e0adbe9c | ||
|
|
5f6d4ab428 | ||
|
|
d5c4400fde | ||
|
|
c24cb72640 | ||
|
|
7ff3c3b48e | ||
|
|
bda5cde92b | ||
|
|
034426f870 | ||
|
|
f1f20f7bba | ||
|
|
cc4e76019b | ||
|
|
e9b6ef57e0 | ||
|
|
7cbd0325a4 | ||
|
|
eb22997f8e | ||
|
|
2426ffddad | ||
|
|
92bc1b0113 | ||
|
|
cc00ec39c7 | ||
|
|
1f28016122 | ||
|
|
0d0b2d78e1 | ||
|
|
49a412d748 | ||
|
|
df57fd1552 | ||
|
|
78c8824356 | ||
|
|
dbb8d5f0f4 | ||
|
|
3580f2815c | ||
|
|
c7102f1c89 | ||
|
|
17bef9915f | ||
|
|
905c2955b0 | ||
|
|
3699935347 | ||
|
|
6d42be95f8 | ||
|
|
3c5751025c | ||
|
|
82c6ca4e0a | ||
|
|
834fe6e250 | ||
|
|
5a21f67b42 | ||
|
|
94a68b1c06 | ||
|
|
3a522e457d | ||
|
|
650fee7873 | ||
|
|
c699542565 | ||
|
|
91da3aeb27 | ||
|
|
1d7a521e05 | ||
|
|
e128cc37ec | ||
|
|
9f1e12156e | ||
|
|
3ede13e04a | ||
|
|
b7fda58af9 | ||
|
|
0d43e6a111 | ||
|
|
231a97c186 | ||
|
|
968b6c78fb | ||
|
|
ab1e61a10f | ||
|
|
d3d328804e | ||
|
|
980127379b | ||
|
|
9fa728c039 | ||
|
|
e560d93cd5 | ||
|
|
584dd1e510 | ||
|
|
f00c99fd36 | ||
|
|
ffca0ace43 | ||
|
|
d80f53a31e | ||
|
|
12fdea0914 | ||
|
|
0ec3d4735b | ||
|
|
13a451a756 | ||
|
|
a349043abb | ||
|
|
251cac9807 | ||
|
|
d82a254cdb | ||
|
|
fe264f0a23 | ||
|
|
a1e415ac05 | ||
|
|
41250b7fc7 | ||
|
|
43f21dbf6c | ||
|
|
18f13f12dd | ||
|
|
7811bf5dcb | ||
|
|
2b9f841bbd | ||
|
|
8924a16747 | ||
|
|
ab82598859 | ||
|
|
cae5d75005 | ||
|
|
ee74f84c9f | ||
|
|
676a725807 | ||
|
|
76aac203d6 | ||
|
|
034106918d | ||
|
|
0f3237f125 | ||
|
|
a486e3ff63 | ||
|
|
0b0f5c60c3 | ||
|
|
5230606144 | ||
|
|
2d47530069 | ||
|
|
9fcb4df30e | ||
|
|
18012c2c95 | ||
|
|
678b54dac7 | ||
|
|
0f9946e6ca | ||
|
|
1c8e245603 | ||
|
|
934fda9405 | ||
|
|
34ae328b0d | ||
|
|
02ec1aa28f | ||
|
|
8533a1452b | ||
|
|
36e9044972 | ||
|
|
8a5a6f8be9 | ||
|
|
b5b647422a | ||
|
|
f3d03bf85f | ||
|
|
72b12ddd9c |
@@ -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
|
||||||
+13
-2
@@ -1,14 +1,25 @@
|
|||||||
# Registry
|
# Registry
|
||||||
REGISTRY=registry.bonamin.gr
|
REGISTRY=registry.bonamin.net
|
||||||
VERSION=0.1.0
|
VERSION=0.1.0
|
||||||
|
|
||||||
# Backend runtime secrets (get SITE_ID and SITE_KEY from the sysadmin panel)
|
# Backend runtime secrets (get SITE_ID and SITE_KEY from the sysadmin panel)
|
||||||
SITE_ID=your-site-id
|
SITE_ID=your-site-id
|
||||||
SITE_KEY=your-site-key
|
SITE_KEY=your-site-key
|
||||||
CLOUD_URL=https://xenia-admin.bonamin.gr
|
CLOUD_URL=https://xenia-api.bonamin.net
|
||||||
SECRET_KEY=generate-with-openssl-rand-hex-32
|
SECRET_KEY=generate-with-openssl-rand-hex-32
|
||||||
LICENSE_GRACE_HOURS=24
|
LICENSE_GRACE_HOURS=24
|
||||||
|
|
||||||
|
# This machine's LAN IP on the PHYSICAL network (Ethernet/WiFi) — the address
|
||||||
|
# phones open (http://<HOST_IP>) and the pairing QR code encodes. Never a VPN
|
||||||
|
# address (WireGuard/Tailscale/ZeroTier). install.sh detects it; reserve it in
|
||||||
|
# the router's DHCP.
|
||||||
|
HOST_IP=
|
||||||
|
|
||||||
|
# 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
|
# Volumes — absolute paths on the client machine
|
||||||
DATA_PATH=/opt/xenia/data
|
DATA_PATH=/opt/xenia/data
|
||||||
LOGO_PATH=/opt/xenia/logo.png
|
LOGO_PATH=/opt/xenia/logo.png
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Files that run or are read on Linux client machines must keep LF endings,
|
||||||
|
# even when checked out on Windows with core.autocrlf=true (install.sh is scp'd as-is).
|
||||||
|
*.sh text eol=lf
|
||||||
|
*.conf text eol=lf
|
||||||
|
Dockerfile text eol=lf
|
||||||
|
*.yml text eol=lf
|
||||||
|
.env.example text eol=lf
|
||||||
|
gradlew text eol=lf
|
||||||
|
*.bat text eol=crlf
|
||||||
@@ -37,3 +37,6 @@ data/
|
|||||||
certs/*.pem
|
certs/*.pem
|
||||||
certs/*.crt
|
certs/*.crt
|
||||||
certs/*.key
|
certs/*.key
|
||||||
|
|
||||||
|
# Test caches
|
||||||
|
.pytest_cache/
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# client-services
|
||||||
|
|
||||||
|
Read [docs/README.md](docs/README.md) (pack rules) and the global [../docs/README.md](../docs/README.md) (Working Rules) before making changes.
|
||||||
|
This is its own git repo. Commit here first, then bump the pointer in the parent `xenia-pos` repo.
|
||||||
+18
-2
@@ -2,19 +2,35 @@ services:
|
|||||||
backend:
|
backend:
|
||||||
build: ./local_backend
|
build: ./local_backend
|
||||||
image: ${REGISTRY}/pos-backend:${VERSION:-latest}
|
image: ${REGISTRY}/pos-backend:${VERSION:-latest}
|
||||||
|
environment:
|
||||||
|
- LICENSE_MODE=off # dev machine: every module, no limits (never on a site)
|
||||||
ports:
|
ports:
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
|
volumes:
|
||||||
|
- ${FISCAL_PATH:-./fiscal_test}:/mnt/fiscal
|
||||||
|
|
||||||
waiter_pwa:
|
waiter_pwa:
|
||||||
build:
|
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}
|
image: ${REGISTRY}/pos-waiter:${VERSION:-latest}
|
||||||
ports:
|
ports:
|
||||||
- "5173:80"
|
- "5173:80"
|
||||||
|
|
||||||
manager_dashboard:
|
manager_dashboard:
|
||||||
build:
|
build:
|
||||||
context: ./manager_dashboard
|
context: .
|
||||||
|
dockerfile: manager_dashboard/Dockerfile
|
||||||
image: ${REGISTRY}/pos-manager:${VERSION:-latest}
|
image: ${REGISTRY}/pos-manager:${VERSION:-latest}
|
||||||
ports:
|
ports:
|
||||||
- "5174:80"
|
- "5174:80"
|
||||||
|
|
||||||
|
terminal:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: terminal/Dockerfile
|
||||||
|
image: ${REGISTRY}/pos-terminal:${VERSION:-latest}
|
||||||
|
ports:
|
||||||
|
- "5175:80"
|
||||||
|
|||||||
+48
-2
@@ -6,14 +6,40 @@ services:
|
|||||||
- SITE_ID=${SITE_ID}
|
- SITE_ID=${SITE_ID}
|
||||||
- SITE_KEY=${SITE_KEY}
|
- SITE_KEY=${SITE_KEY}
|
||||||
- CLOUD_URL=${CLOUD_URL}
|
- CLOUD_URL=${CLOUD_URL}
|
||||||
|
- LICENSE_MODE=${LICENSE_MODE:-enforced} # 'off' only for dev/test stacks (all modules, no limits)
|
||||||
- SECRET_KEY=${SECRET_KEY}
|
- SECRET_KEY=${SECRET_KEY}
|
||||||
- LICENSE_GRACE_HOURS=${LICENSE_GRACE_HOURS:-24}
|
- LICENSE_GRACE_HOURS=${LICENSE_GRACE_HOURS:-24}
|
||||||
- DATABASE_URL=sqlite:////app/data/pos.db
|
- DATABASE_URL=sqlite:////app/data/pos.db
|
||||||
- VERSION=${VERSION:-0.0.0}
|
- VERSION=${VERSION:-0.0.0}
|
||||||
- HOST_IP=${HOST_IP:-}
|
- 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)
|
||||||
|
- SUPPORT_SECRET=${SUPPORT_SECRET:-}
|
||||||
volumes:
|
volumes:
|
||||||
- ${DATA_PATH}:/app/data
|
- ${DATA_PATH}:/app/data
|
||||||
- ${LOGO_PATH}:/app/logo.png:ro
|
- ${LOGO_PATH}:/app/logo.png:ro
|
||||||
|
- ${FISCAL_PATH}:/mnt/fiscal
|
||||||
|
- netinfo:/netinfo:ro
|
||||||
|
# "Healthy" = app started, which also means the TLS key/cert for the
|
||||||
|
# proxy's :8443 exist (created at startup by services/tls_identity.py)
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/system/health', timeout=3)"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 12
|
||||||
|
start_period: 20s
|
||||||
|
|
||||||
|
# Finds the server's LAN IP on the PHYSICAL network (never a VPN) every minute
|
||||||
|
# and shares it with the backend (pairing QR, manager, heartbeat). Needs the
|
||||||
|
# host's network namespace because the backend's bridge network can't see
|
||||||
|
# real NICs. Same image as the backend — see services/netinfo_helper.py.
|
||||||
|
netinfo:
|
||||||
|
image: ${REGISTRY}/pos-backend:${VERSION:-latest}
|
||||||
|
restart: unless-stopped
|
||||||
|
network_mode: host
|
||||||
|
command: ["python", "-m", "services.netinfo_helper"]
|
||||||
|
volumes:
|
||||||
|
- netinfo:/netinfo
|
||||||
|
|
||||||
waiter_pwa:
|
waiter_pwa:
|
||||||
image: ${REGISTRY}/pos-waiter:${VERSION:-latest}
|
image: ${REGISTRY}/pos-waiter:${VERSION:-latest}
|
||||||
@@ -27,16 +53,36 @@ services:
|
|||||||
depends_on:
|
depends_on:
|
||||||
- backend
|
- 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:
|
proxy:
|
||||||
image: nginx:alpine
|
image: nginx:alpine
|
||||||
ports:
|
ports:
|
||||||
- "80:80"
|
- "80:80"
|
||||||
- "443:443"
|
- "443:443"
|
||||||
- "4443:4443"
|
- "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:
|
volumes:
|
||||||
- ./nginx-proxy/nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
- ./nginx-proxy/nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
||||||
- ./certs:/etc/nginx/certs:ro
|
- ./certs:/etc/nginx/certs:ro
|
||||||
|
- ${DATA_PATH}/tls:/etc/nginx/xenia-tls:ro
|
||||||
depends_on:
|
depends_on:
|
||||||
- waiter_pwa
|
backend:
|
||||||
- manager_dashboard
|
condition: service_healthy
|
||||||
|
waiter_pwa:
|
||||||
|
condition: service_started
|
||||||
|
manager_dashboard:
|
||||||
|
condition: service_started
|
||||||
|
terminal:
|
||||||
|
condition: service_started
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
netinfo:
|
||||||
|
|||||||
+105
@@ -0,0 +1,105 @@
|
|||||||
|
# Design language (on-site frontends)
|
||||||
|
|
||||||
|
> The rules every screen of the manager (and later the terminal and the waiter app) follows, so the product looks like one thing.
|
||||||
|
> **Read this before writing or changing any page, dialog or component.** Change a rule here first, then in `packages/ui`, never in one page.
|
||||||
|
> Started 2026-11-20 from the owner's UI review (modelled on the BellSystems control panel's `DESIGN.md`).
|
||||||
|
|
||||||
|
## 1. Principles
|
||||||
|
|
||||||
|
- **Global, never local.** Anything that two pages need is a component or a token in `@xenia/ui` (`packages/ui`). If a page needs a new look, add it to `@xenia/ui` and use it from there. Never rebuild a dropdown, a tab strip or a page frame inside a page.
|
||||||
|
- **Tokens only.** Colours, sizes, radii, paddings and heights come from `packages/ui/src/tokens.css` (Tailwind names from `tailwind-preset.js`). No hex or rgb values in app code (see also CS-16).
|
||||||
|
- **Same height in a row.** Controls that sit side by side (a search box, dropdowns, chips, buttons) share one height: `md` (44 px, `--x-control-md`) unless the whole row is `sm`.
|
||||||
|
- **Quiet secondary text.** `text-ink-2` / `text-ink-3` are muted on purpose. Don't make subtitles, hints or labels darker to make them stand out.
|
||||||
|
|
||||||
|
## 2. The page rule
|
||||||
|
|
||||||
|
Every page's root is `<Page>` from `@xenia/ui`. It provides:
|
||||||
|
|
||||||
|
- **its own scrolling** (the shell's `<main>` never scrolls),
|
||||||
|
- **the width:** it fills the content area up to 2200 px (`--x-page-max`). On a 1080p monitor the page fills the screen; on an ultrawide it stays 2200 px wide and is **centred**. The width never depends on the window's height (owner 2026-11-21: a short window used to narrow the page),
|
||||||
|
- **the padding and gaps** (`--x-page-pad`, `--x-page-gap`), the same on every page.
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
<Page testId="contacts-page">
|
||||||
|
<PageHeader title="…" subtitle="…" actions={<Button>New</Button>} />
|
||||||
|
<Toolbar>
|
||||||
|
<SearchInput value={q} onChange={setQ} placeholder="…" />
|
||||||
|
<Dropdown multiple value={kinds} onChange={setKinds} allLabel="All kinds" options={…} />
|
||||||
|
</Toolbar>
|
||||||
|
<Panel padded={false}><Table … /></Panel>
|
||||||
|
</Page>
|
||||||
|
```
|
||||||
|
|
||||||
|
- `top={<Tabs … />}` keeps a tab strip above the scrolling part (Online orders, Settings). The tab is kept in the address (`?tab=`). Tabs that don't fit **wrap onto another row**; they are never hidden in a sideways scroll (6F.0, owner 2026-11-23).
|
||||||
|
- `header={<PageHeader … />}` with `top`: the page's title and description come **first**, then the tabs (Offers & pricing). Each tab then starts with its own head: title, description, its "New" button at the top right.
|
||||||
|
- `fit`: the page is exactly the screen's height and doesn't scroll; its `Pane`s do, each on its own (Products). Put them in an element with `x-page__fill`. Phones scroll as usual.
|
||||||
|
- The scrollbar's room is always kept (`scrollbar-gutter: stable`), so a short tab is exactly as wide as a long one.
|
||||||
|
- Every page is full width, **Settings included** (6F.0, owner 2026-11-23: an 880 px Settings page looked narrower than the rest and cut its tabs). Settings and other pages of cards put them in `<Columns>`: cards flow top to bottom, then into the next column, each column at least 34rem (two on 1080p, three on an ultrawide, one on a laptop or phone); `x-columns__wide` / `<ColumnsWide>` spans all columns (an intro row, a wide editor). `width="form"` (880 px, centred) stays only for a single form that reads better narrow; no page uses it now.
|
||||||
|
- A settings row (`SettingRow`) keeps its control in a 16rem box on the right: selects and inputs fill it, switches and buttons sit at its right edge.
|
||||||
|
- **Never** put `p-*`, `max-w-*`, `mx-auto`, `h-full` or `overflow-*` on a page's root, and never nest a second width limit inside it.
|
||||||
|
- Checked by `tests/e2e/manager_layout.mjs` (1920×1080 and 3440×1440: every page fills / is centred, and scrolls). Add a new page to its `PAGES` list.
|
||||||
|
|
||||||
|
Every page is on `<Page>` except Inventory → Stock (a placeholder). Two-column pages put each side in its own container. Products is a `Page fit` with two `Pane`s (header and footer stay, only the list scrolls; the list's body `sunken`, a shade darker, so the white product rows stand out). The floor editor: the map and its panels, the narrow side `sticky`.
|
||||||
|
|
||||||
|
## 3. Components (`@xenia/ui`)
|
||||||
|
|
||||||
|
| Need | Use | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| A page | `Page`, `PageHeader` | §2 |
|
||||||
|
| Cards in columns (settings) | `Columns`, `ColumnsWide` | §2; a card never splits across two columns |
|
||||||
|
| Filters / actions over a list | `Toolbar`, `ToolbarSpacer` | every control in it the same height; the search box grows |
|
||||||
|
| Search | `SearchInput` | icon, clear button; `onChange(text)` |
|
||||||
|
| Choose one / several | `Dropdown` (`multiple`) | **never a native `<select>` in a toolbar.** Multi: value is an array, `[]` = all (`allLabel`). Options can carry a `dot` (a zone's colour) and a `hint`. Search box from 9 options. Same heights as `Input`. Native `Select` stays only inside forms where the phone's own picker is better |
|
||||||
|
| A small panel under a button | `Popover` (`open`, `anchor` = the button's ref, `onClose`) | a colour picker, an "Add…" menu. Drawn over everything (portal), flips above, stays inside the window: **never an `absolute` panel inside a section** (it is clipped and makes the section scroll) |
|
||||||
|
| A colour (a venue's: data) | `ColourField` (`auto`, `opacity`, `presets`) | a field with its swatch and code; its panel (over the page) has 12 ready colours, the picker, the opacity (`#rrggbbaa`) and the code. `auto` = a first choice that leaves it to something else ("As the slide"). **Never** a bare `<input type="color">` |
|
||||||
|
| An icon from a set | `IconPicker` (`icons` = { key: component }) | a field showing the icon; a grid of the set over the page, "No icon" first |
|
||||||
|
| Money, a weight, any number with decimals | `MoneyInput` (€, cents), `DecimalInput` (`decimals`, `allowNegative`, `suffix`) | typed with a comma **or** a dot ("12,50", "1.234,50"); reports a number, `null` when empty, `NaN` when it isn't a number (show the error). **Never** `type="number"` with a decimal step, `parseFloat` or `.replace(',', '.')`: they drop the comma a Greek keypad types (6F.2; guarded by `packages/i18n/tests/typed-numbers.test.mjs`). Fields kept as text read it with `parseNumber` |
|
||||||
|
| A whole number (seconds, counts) | `NumberInput` (`min`, `max`, `suffix`) | − / + on its sides, as tall as an input; it may be emptied while typing (`onChange(null)`): the form shows the error and blocks saving. **Never** clamp on every key (the user can't clear the field). With a `min` below 0 a minus may be typed in front |
|
||||||
|
| A note in a box (what works, a caution) | `Notice` (`tone`, `title`, `icon`, `items` = [{ tone, label, text }]) | a tinted box with a bar on its left; `items` are points with a tone dot and a bold label. **Never** a local `bg-info-soft` paragraph rebuilt per page |
|
||||||
|
| A slider with its value | `Slider` (`suffix`) | framed and as tall as the fields beside it; the value sits as close to it as the frame's padding. **Never** a bare `<input type="range">` |
|
||||||
|
| Fields that should wrap | `FieldRow` (`min`, `shade` on every other row) | each field keeps its least width; a row that wraps is framed (and tinted with `shade`), a row on one line looks like any row |
|
||||||
|
| Toggles that go together (bold / italic / underline) | `Segmented multiple` | value is an array |
|
||||||
|
| A toggle filter (a state) | `FilterChip` (`tone`, `count`) | |
|
||||||
|
| Two or three views (List / Map / QR) | `Segmented` | the view in the address (`?view=`) |
|
||||||
|
| Sections of a page or a dialog | `Tabs` (`size="lg"` on pages) | scrolls sideways only, never up/down. `inset`: the strip is a card's header (card padding at the sides, the same room above and below a button in `end`, the labels level with it, no line under it). `fill`: the tabs share the width equally (a narrow column) |
|
||||||
|
| A container whose list scrolls | `Pane` (`header`, `footer`, `sunken`) | header and footer stay, the body scrolls; one side of a `Page fit` |
|
||||||
|
| A help tip | `InfoTip` | opens on hover (mouse) and on tap. Beside a switch: `Switch info={<InfoTip>…}` puts it right after the text, never after the switch |
|
||||||
|
| Row actions that stand apart | `IconButton tone` | `danger` delete / archive · `warning` block · `info` zones · `accent` edit · `success` unblock: a **grey** square at rest; under the pointer it lights up in its colour (soft background, coloured icon). Every row action of a row has a tone, so they all look the same at rest. Neutral actions stay `ghost` |
|
||||||
|
| A quiet text action that warns | `Button variant="ghost" tone="danger"` | grey text, red under the pointer ("Remove" a picture) |
|
||||||
|
| A switch on its own in a row of buttons | `Switch` without a label | lines up with the buttons (centred), never with a text baseline |
|
||||||
|
| Dialogs | `Dialog` `sm` 400 · `md` 520 · `lg` 720 · `xl` 920 · `wide` (~88 % of a 16:9 screen, capped on ultrawides) | the day summary is `xl`, the product editor `wide` |
|
||||||
|
| Ask before doing something (delete, leave unsaved work) | `useConfirm()` → `confirm({ title, body, confirmLabel, tone })` (or `ConfirmDialog`) | **never the browser's `window.confirm`**; render the returned dialog in the component. Leaving unsaved work: add `altLabel` ("Save and leave"): the promise answers `'alt'` |
|
||||||
|
| A switch in a row of fields | `Switch boxed` | framed and as tall as an input: text left, switch right; a click anywhere in the frame toggles it |
|
||||||
|
| Two or three choices that fill a form column (alignment…) | `Segmented fill` | options share the width; icon-only options pass `ariaLabel` |
|
||||||
|
| A side drawer | `Sheet side="right"` (`size="wide"`: 600 px) | the permissions editor is `wide` |
|
||||||
|
| Something that stays at the top of a dialog or drawer | `toolbar` (Dialog / Sheet) | under the title, doesn't scroll: the permissions' search box |
|
||||||
|
| A control beside a dialog's close button | `headerEnd` (Dialog / Sheet) | the product editor's language picker |
|
||||||
|
| A toggle on a row (several, compact…) | `FilterChip size="sm" tone pressed` | takes its colour when on; a toned `IconButton` with `aria-pressed` (the favourite's heart) keeps its colour while on |
|
||||||
|
| Print only this | `PrintArea` (+ `PrintSheet` for cards to cut out) | rendered into `<body>`, hidden on screen; while mounted, printing prints only it. One per page |
|
||||||
|
| Section titles inside a panel or drawer | `text-overline font-semibold uppercase tracking-wide text-ink-3` + a `flex-1 border-t border-line` rule after it | as the navigation's group titles |
|
||||||
|
|
||||||
|
The manager's own building blocks (until they move to `@xenia/ui`): `Panel`, `Table`, `Stat` in `pages/reports/kit/parts.jsx`; `Card`, `Figure`, `Pill`, `SplitBar` in `pages/overview/parts.jsx`.
|
||||||
|
|
||||||
|
## 4. Type and spacing tokens
|
||||||
|
|
||||||
|
| Token / class | Value | Use |
|
||||||
|
|---|---|---|
|
||||||
|
| `text-overline` + `font-semibold uppercase tracking-wide text-ink-3` | 11 px | the small labels over figures and sections ("REVENUE", "TOTAL"). Never `text-caption` for these |
|
||||||
|
| `text-caption` | 12 px | hints, sub-lines |
|
||||||
|
| `text-label` | 13 px | rows in summaries, table cells, chips |
|
||||||
|
| `text-body` | 14 px | body text |
|
||||||
|
| `p-card`, `px-card`, `py-card-y` | 20 px / 14 px | inside every card, panel and section: header rows (`px-card py-card-y`) and bodies (`p-card`) |
|
||||||
|
|
||||||
|
## 5. Tables
|
||||||
|
|
||||||
|
- `Table` cells are vertically **centred** (`align-middle`): a one-line cell sits in the middle of a two-line row.
|
||||||
|
- Row actions last, right-aligned, `IconButton size="sm" variant="ghost"`.
|
||||||
|
- A column's help is `tip` (an `InfoTip` in the header, opens on hover).
|
||||||
|
|
||||||
|
## 6. Before you finish a UI change
|
||||||
|
|
||||||
|
1. `npm run build:manager` and `npm run lint -w manager-dashboard` pass.
|
||||||
|
2. `npm test -w @xenia/ui` (contrast in every look) passes.
|
||||||
|
3. `node tests/e2e/manager_layout.mjs` passes; look at its screenshots in `tests/e2e/out/manager-layout/`.
|
||||||
|
4. Live preview while working: `npx vite --port 5184` in `manager_dashboard/` (hot reload, uses the running backend on :8000; touches nothing in Docker).
|
||||||
|
**After a change to `packages/ui/tailwind-preset.js`, restart every running dev server.** Vite reloads CSS and components, but Tailwind reads the preset only at start: a server started before the change never makes the new classes (`p-card`, `text-overline`, `max-w-page` …), and cards lose all their padding.
|
||||||
+232
File diff suppressed because one or more lines are too long
+367
-47
@@ -7,6 +7,40 @@ set -e
|
|||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
|
||||||
|
# LAN IP of this machine on the PHYSICAL network (the address phones use:
|
||||||
|
# http://<HOST_IP>). Must never be a VPN address: with a full-tunnel WireGuard /
|
||||||
|
# Tailscale / ZeroTier client, "the interface that reaches the internet" is the
|
||||||
|
# tunnel, which phones on the restaurant WiFi can't reach.
|
||||||
|
# Real NICs (Ethernet, WiFi) have /sys/class/net/<if>/device; VPN tunnels,
|
||||||
|
# Docker bridges, veths and loopback don't.
|
||||||
|
# XENIA_SYS_NET overrides the sysfs path (tests only).
|
||||||
|
detect_host_ip() {
|
||||||
|
local sys_net="${XENIA_SYS_NET:-/sys/class/net}" ifc ip=""
|
||||||
|
command -v ip >/dev/null 2>&1 || { hostname -I 2>/dev/null | awk '{print $1}'; return; }
|
||||||
|
|
||||||
|
first_ipv4() { ip -4 -o addr show dev "$1" 2>/dev/null | awk '{split($4, a, "/"); print a[1]; exit}'; }
|
||||||
|
|
||||||
|
# 1) Interface of the main-table default route, if it's real hardware.
|
||||||
|
# (wg-quick full-tunnel routing uses policy rules + its own table, so the
|
||||||
|
# main table's default route still points at the physical uplink.)
|
||||||
|
ifc=$(ip route show default 2>/dev/null | awk '{for (i=1;i<=NF;i++) if ($i=="dev") {print $(i+1); exit}}')
|
||||||
|
if [ -n "$ifc" ] && [ -e "$sys_net/$ifc/device" ]; then
|
||||||
|
ip=$(first_ipv4 "$ifc")
|
||||||
|
fi
|
||||||
|
# 2) Otherwise the first real-hardware interface that has an IPv4 address.
|
||||||
|
if [ -z "$ip" ]; then
|
||||||
|
for path in "$sys_net"/*; do
|
||||||
|
ifc=$(basename "$path")
|
||||||
|
[ -e "$path/device" ] || continue
|
||||||
|
ip=$(first_ipv4 "$ifc")
|
||||||
|
[ -n "$ip" ] && break
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
# 3) Last resort — the admin confirms it at the prompt anyway.
|
||||||
|
[ -z "$ip" ] && ip=$(hostname -I 2>/dev/null | awk '{print $1}')
|
||||||
|
echo "$ip"
|
||||||
|
}
|
||||||
|
|
||||||
echo "=== Xenia POS Install ==="
|
echo "=== Xenia POS Install ==="
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
@@ -27,13 +61,18 @@ if [ ! -f "$SCRIPT_DIR/.env" ]; then
|
|||||||
echo " A .env file has been created from .env.example."
|
echo " A .env file has been created from .env.example."
|
||||||
echo " You must fill in SITE_ID, SITE_KEY, and SECRET_KEY before starting."
|
echo " You must fill in SITE_ID, SITE_KEY, and SECRET_KEY before starting."
|
||||||
echo ""
|
echo ""
|
||||||
echo " Get SITE_ID and SITE_KEY from: https://xenia-admin.bonamin.gr"
|
echo " Get SITE_ID and SITE_KEY from: https://xenia-admin.bonamin.net"
|
||||||
echo " Generate SECRET_KEY with: openssl rand -hex 32"
|
echo " Generate SECRET_KEY with: openssl rand -hex 32"
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
read -rp " Enter SITE_ID: " INPUT_SITE_ID
|
read -rp " Enter SITE_ID: " INPUT_SITE_ID
|
||||||
read -rp " Enter SITE_KEY: " INPUT_SITE_KEY
|
read -rp " Enter SITE_KEY: " INPUT_SITE_KEY
|
||||||
read -rp " Enter SECRET_KEY (leave blank to auto-generate): " INPUT_SECRET_KEY
|
read -rp " Enter SECRET_KEY (leave blank to auto-generate): " INPUT_SECRET_KEY
|
||||||
|
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
|
if [ -z "$INPUT_SECRET_KEY" ]; then
|
||||||
INPUT_SECRET_KEY=$(openssl rand -hex 32)
|
INPUT_SECRET_KEY=$(openssl rand -hex 32)
|
||||||
@@ -43,22 +82,164 @@ if [ ! -f "$SCRIPT_DIR/.env" ]; then
|
|||||||
sed -i "s/^SITE_ID=.*/SITE_ID=${INPUT_SITE_ID}/" "$SCRIPT_DIR/.env"
|
sed -i "s/^SITE_ID=.*/SITE_ID=${INPUT_SITE_ID}/" "$SCRIPT_DIR/.env"
|
||||||
sed -i "s/^SITE_KEY=.*/SITE_KEY=${INPUT_SITE_KEY}/" "$SCRIPT_DIR/.env"
|
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/^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 ""
|
||||||
echo " .env written. Review it at: $SCRIPT_DIR/.env"
|
echo " .env written. Review it at: $SCRIPT_DIR/.env"
|
||||||
echo ""
|
echo ""
|
||||||
else
|
else
|
||||||
echo " .env already exists — skipping."
|
echo " .env already exists — keeping it."
|
||||||
|
if ! grep -q '^HOST_IP=.\+' "$SCRIPT_DIR/.env"; then
|
||||||
|
DETECTED_IP=$(detect_host_ip)
|
||||||
|
sed -i '/^HOST_IP=/d' "$SCRIPT_DIR/.env"
|
||||||
|
echo "HOST_IP=${DETECTED_IP}" >> "$SCRIPT_DIR/.env"
|
||||||
|
echo " HOST_IP was not set — added HOST_IP=${DETECTED_IP} (edit .env if wrong)."
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ── 3. Write nginx-proxy/nginx.conf ──────────────────────────────────────────
|
# ── 3. Write nginx-proxy/nginx.conf ──────────────────────────────────────────
|
||||||
echo "[ 3/5 ] Writing nginx proxy config..."
|
echo "[ 3/5 ] Writing nginx proxy config..."
|
||||||
cat > "$SCRIPT_DIR/nginx-proxy/nginx.conf" << 'EOF'
|
cat > "$SCRIPT_DIR/nginx-proxy/nginx.conf" << 'EOF'
|
||||||
|
# Xenia POS — on-site proxy config.
|
||||||
|
# install.sh writes this exact file on client sites; nginx-proxy/nginx.conf in the
|
||||||
|
# repo is a byte-identical copy. Change both together (global Working Rule 9).
|
||||||
|
#
|
||||||
|
# :80 waiter.* / manager.* hostnames → redirect to https (legacy domain setup)
|
||||||
|
# :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.
|
||||||
|
|
||||||
|
map $http_upgrade $connection_upgrade {
|
||||||
|
default 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 {
|
server {
|
||||||
listen 80;
|
listen 80;
|
||||||
|
server_name waiter.* manager.*;
|
||||||
return 301 https://$host$request_uri;
|
return 301 https://$host$request_uri;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80 default_server;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
# 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;
|
||||||
|
|
||||||
|
location ~ ^/manager/?$ {
|
||||||
|
return 302 http://$host:8081/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://waiter_pwa:80;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 8081 default_server;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
# 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;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://manager_dashboard:80;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
server {
|
||||||
listen 443 ssl;
|
listen 443 ssl;
|
||||||
server_name waiter.*;
|
server_name waiter.*;
|
||||||
@@ -68,13 +249,38 @@ server {
|
|||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
location / {
|
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
||||||
proxy_pass http://waiter_pwa:80;
|
# 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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://waiter_pwa:80;
|
||||||
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
server {
|
server {
|
||||||
@@ -86,35 +292,156 @@ server {
|
|||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
location / {
|
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
||||||
proxy_pass http://manager_dashboard:80;
|
# 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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://manager_dashboard:80;
|
||||||
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
server {
|
server {
|
||||||
listen 443 ssl default_server;
|
listen 443 ssl default_server;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
ssl_certificate /etc/nginx/certs/cert.pem;
|
ssl_certificate /etc/nginx/certs/cert.pem;
|
||||||
ssl_certificate_key /etc/nginx/certs/key.pem;
|
ssl_certificate_key /etc/nginx/certs/key.pem;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
location /api/ {
|
# 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_pass http://backend:8000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
}
|
}
|
||||||
|
|
||||||
location / {
|
location /api/ {
|
||||||
proxy_pass http://waiter_pwa:80;
|
proxy_pass http://backend:8000;
|
||||||
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_read_timeout 3600s;
|
||||||
|
proxy_send_timeout 3600s;
|
||||||
|
proxy_buffering off;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://waiter_pwa:80;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 8443 ssl default_server;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
# Encrypted LAN entry for the native app (plan step 7). Key + self-signed cert
|
||||||
|
# are created and renewed by the backend (services/tls_identity.py) under
|
||||||
|
# ${DATA_PATH}/tls; phones pin the public key, so renewals need no action.
|
||||||
|
ssl_certificate /etc/nginx/xenia-tls/cert.pem;
|
||||||
|
ssl_certificate_key /etc/nginx/xenia-tls/key.pem;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
|
||||||
|
# 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;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://waiter_pwa:80;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 4443 ssl default_server;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
ssl_certificate /etc/nginx/certs/cert.pem;
|
||||||
|
ssl_certificate_key /etc/nginx/certs/key.pem;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://manager_dashboard:80;
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
EOF
|
EOF
|
||||||
@@ -122,34 +449,24 @@ EOF
|
|||||||
# ── 4. SSL certificates ───────────────────────────────────────────────────────
|
# ── 4. SSL certificates ───────────────────────────────────────────────────────
|
||||||
echo "[ 4/5 ] Checking SSL certificates..."
|
echo "[ 4/5 ] Checking SSL certificates..."
|
||||||
|
|
||||||
|
# Phones normally use plain HTTP on the LAN (http://<HOST_IP>), which needs no
|
||||||
|
# certificate. nginx still needs *a* cert to start its HTTPS listeners, so when
|
||||||
|
# none is present we generate a self-signed one. A real certificate (legacy
|
||||||
|
# domain setup) can replace certs/cert.pem + certs/key.pem at any time.
|
||||||
if [ -f "$SCRIPT_DIR/certs/cert.pem" ] && [ -f "$SCRIPT_DIR/certs/key.pem" ]; then
|
if [ -f "$SCRIPT_DIR/certs/cert.pem" ] && [ -f "$SCRIPT_DIR/certs/key.pem" ]; then
|
||||||
echo " Certificates already exist — skipping."
|
echo " Certificates already exist — keeping them."
|
||||||
else
|
else
|
||||||
echo ""
|
CERT_IP=$(grep '^HOST_IP=' "$SCRIPT_DIR/.env" 2>/dev/null | cut -d= -f2)
|
||||||
echo " No certificates found in certs/"
|
CERT_SAN="DNS:localhost,IP:127.0.0.1"
|
||||||
echo ""
|
[ -n "$CERT_IP" ] && CERT_SAN="$CERT_SAN,IP:$CERT_IP"
|
||||||
echo " DNS requirement:"
|
openssl req -x509 -newkey rsa:2048 -nodes -days 3650 \
|
||||||
echo " Two subdomains must point to this machine's IP:"
|
-keyout "$SCRIPT_DIR/certs/key.pem" \
|
||||||
echo " waiter.YOURDOMAIN → this machine's IP"
|
-out "$SCRIPT_DIR/certs/cert.pem" \
|
||||||
echo " manager.YOURDOMAIN → this machine's IP"
|
-subj "/CN=xenia-pos" \
|
||||||
echo " The waiter domain should also be registered in the sysadmin"
|
-addext "subjectAltName=$CERT_SAN" >/dev/null 2>&1
|
||||||
echo " panel as the 'Waiter Domain' so phones get the QR code."
|
chmod 600 "$SCRIPT_DIR/certs/key.pem"
|
||||||
echo ""
|
echo " No certificates found — generated a self-signed one (valid 10 years)."
|
||||||
echo " Option A — Let's Encrypt (recommended):"
|
echo " Phones use plain HTTP on the LAN, so this is only for the HTTPS ports."
|
||||||
echo " sudo apt install certbot"
|
|
||||||
echo " sudo certbot certonly --manual --preferred-challenges dns \\"
|
|
||||||
echo " -d waiter.YOURDOMAIN -d manager.YOURDOMAIN"
|
|
||||||
echo " sudo cp /etc/letsencrypt/live/waiter.YOURDOMAIN/fullchain.pem certs/cert.pem"
|
|
||||||
echo " sudo cp /etc/letsencrypt/live/waiter.YOURDOMAIN/privkey.pem certs/key.pem"
|
|
||||||
echo ""
|
|
||||||
echo " Option B — Self-signed / mkcert (local testing only):"
|
|
||||||
echo " sudo apt install mkcert libnss3-tools"
|
|
||||||
echo " mkcert -install"
|
|
||||||
echo " mkcert -cert-file certs/cert.pem -key-file certs/key.pem \\"
|
|
||||||
echo " waiter.YOURDOMAIN manager.YOURDOMAIN"
|
|
||||||
echo ""
|
|
||||||
echo " Add certs then run: docker compose up -d"
|
|
||||||
echo ""
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ── 5. Logo ───────────────────────────────────────────────────────────────────
|
# ── 5. Logo ───────────────────────────────────────────────────────────────────
|
||||||
@@ -161,18 +478,21 @@ if [ ! -s "$SCRIPT_DIR/logo.png" ]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# ── Done ─────────────────────────────────────────────────────────────────────
|
# ── Done ─────────────────────────────────────────────────────────────────────
|
||||||
|
HOST_IP_NOW=$(grep '^HOST_IP=' "$SCRIPT_DIR/.env" 2>/dev/null | cut -d= -f2)
|
||||||
|
HOST_IP_NOW="${HOST_IP_NOW:-SERVER-IP}"
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "=== Setup complete ==="
|
echo "=== Setup complete ==="
|
||||||
echo ""
|
echo ""
|
||||||
|
echo "Starting stack..."
|
||||||
if [ -f "$SCRIPT_DIR/certs/cert.pem" ] && [ -f "$SCRIPT_DIR/certs/key.pem" ]; then
|
docker compose -f "$SCRIPT_DIR/docker-compose.yml" up -d
|
||||||
echo "Starting stack..."
|
echo ""
|
||||||
docker compose -f "$SCRIPT_DIR/docker-compose.yml" up -d
|
echo "Done! Services running. From any phone or PC on this network:"
|
||||||
echo ""
|
echo " Waiter app: http://${HOST_IP_NOW}"
|
||||||
echo "Done! Services running."
|
echo " Manager app: http://${HOST_IP_NOW}/manager (→ port 8081)"
|
||||||
echo " Waiter app: https://waiter.YOURDOMAIN"
|
echo " Screens: http://${HOST_IP_NOW}:8082 (kitchen display, counter POS; pair them under Devices)"
|
||||||
echo " Manager app: https://manager.YOURDOMAIN"
|
echo ""
|
||||||
else
|
echo "Tip: reserve ${HOST_IP_NOW} for this machine in the router's DHCP settings"
|
||||||
echo "Add SSL certificates to certs/ then run:"
|
echo " so the address never changes."
|
||||||
echo " docker compose up -d"
|
echo ""
|
||||||
fi
|
echo "If the proxy config changed, restart it: docker compose restart proxy"
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Third-party software shipped in the backend image
|
||||||
|
|
||||||
|
Xenia POS's own code is not covered by this file. It lists separate programs that are shipped
|
||||||
|
inside the backend image and run by it as separate processes.
|
||||||
|
|
||||||
|
## FFmpeg
|
||||||
|
|
||||||
|
- **What it does here:** makes the still frame and the screen-friendly version of uploaded
|
||||||
|
videos (`services/video.py`, plan step 5.4e). The backend starts it as a separate program and
|
||||||
|
reads its output; nothing of FFmpeg is linked into Xenia's code.
|
||||||
|
- **Where it comes from:** the `imageio-ffmpeg` Python package, version pinned in
|
||||||
|
`requirements.txt` (0.8.1). The package carries one static FFmpeg build per platform
|
||||||
|
(Linux x86-64 / ARM64: FFmpeg 9.0.2 built by the imageio project from the BtbN FFmpeg-Builds
|
||||||
|
scripts; Windows: the gyan.dev "essentials" build). Inside the image the program is at
|
||||||
|
`/usr/local/lib/python3.12/site-packages/imageio_ffmpeg/binaries/`.
|
||||||
|
- **Licence:** FFmpeg is free software under the **GNU General Public License, version 3 or
|
||||||
|
later** (built with `--enable-gpl --enable-version3`, no non-free parts). It includes x264
|
||||||
|
(GPL v2 or later) and other libraries under the GPL / LGPL. The full licence text:
|
||||||
|
<https://www.gnu.org/licenses/gpl-3.0.txt>. `ffmpeg -L` prints the licence of the build.
|
||||||
|
- **Source code:** FFmpeg: <https://ffmpeg.org/download.html> (git tag `n9.0.2`). Build scripts:
|
||||||
|
<https://github.com/BtbN/FFmpeg-Builds> and <https://github.com/imageio/imageio-ffmpeg>.
|
||||||
|
On request we provide the exact corresponding source of the FFmpeg build shipped with any
|
||||||
|
Xenia POS release, for at least three years after that release.
|
||||||
|
- **The package around it** (`imageio-ffmpeg`): BSD 2-Clause licence,
|
||||||
|
Copyright (c) 2019-2025, imageio.
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Built-in media (plan step 5.4a)
|
||||||
|
|
||||||
|
Pictures placed in this folder ship inside the backend image and are imported into every
|
||||||
|
venue's media library at start-up as **built-in** items: they show in their own "Built-in"
|
||||||
|
collection, can be picked anywhere (signage backgrounds, customer display looks, products), and
|
||||||
|
can't be deleted or renamed by a venue. The display name is the file name without its extension
|
||||||
|
(underscores and dashes become spaces).
|
||||||
|
|
||||||
|
Only picture files are imported (JPG, PNG, WebP, AVIF, GIF); this README and anything else is
|
||||||
|
ignored. Removing a file here does not remove it from venues that already have it.
|
||||||
@@ -19,8 +19,16 @@ class Settings(BaseSettings):
|
|||||||
CLOUD_URL: str = ""
|
CLOUD_URL: str = ""
|
||||||
SECRET_KEY: str = "change-me-generate-a-long-random-string"
|
SECRET_KEY: str = "change-me-generate-a-long-random-string"
|
||||||
DATABASE_URL: str = f"sqlite:///{_DB_DEFAULT.as_posix()}"
|
DATABASE_URL: str = f"sqlite:///{_DB_DEFAULT.as_posix()}"
|
||||||
VERSION: str = "0.0.0"
|
VERSION: str = "0.3.1"
|
||||||
CONNECT_SYNC_INTERVAL_SECONDS: int = 30 # how often to poll for pending online orders
|
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"
|
||||||
|
|
||||||
|
# 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"}
|
model_config = {"env_file": str(_HERE / ".env"), "env_file_encoding": "utf-8"}
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
|
"""
|
||||||
@@ -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.
|
||||||
|
"""
|
||||||
@@ -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)
|
||||||
@@ -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}")
|
||||||
@@ -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 "*")
|
||||||
@@ -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}")
|
||||||
@@ -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
|
||||||
@@ -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))
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""Allergens (plan step 6.3): the 14 that EU Regulation 1169/2011 (Annex II) requires a venue
|
||||||
|
to declare. A fixed list in code, in the Annex's order; labels live in the i18n packages
|
||||||
|
(`common:allergens.<key>`), the same list in `packages/access/src/allergens.js`.
|
||||||
|
|
||||||
|
A product stores what it has (`products.allergens`, JSON) as {key: level}:
|
||||||
|
contains it is in the recipe
|
||||||
|
may_contain traces, e.g. made in the same kitchen ("may contain")
|
||||||
|
A key that isn't listed means neither. Unknown keys or levels are refused (catalog.allergen).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
ALLERGENS: tuple[str, ...] = (
|
||||||
|
"gluten", "crustaceans", "eggs", "fish", "peanuts", "soybeans", "milk",
|
||||||
|
"nuts", "celery", "mustard", "sesame", "sulphites", "lupin", "molluscs",
|
||||||
|
)
|
||||||
|
LEVELS: tuple[str, ...] = ("contains", "may_contain")
|
||||||
|
|
||||||
|
|
||||||
|
def normalize(value) -> dict[str, str]:
|
||||||
|
"""A product's allergens as {key: level} in the list's order; raises XeniaError on anything else."""
|
||||||
|
from core.errors import XeniaError
|
||||||
|
if value in (None, "", {}):
|
||||||
|
return {}
|
||||||
|
if isinstance(value, str):
|
||||||
|
value = json.loads(value)
|
||||||
|
if not isinstance(value, dict):
|
||||||
|
raise XeniaError("catalog.allergen", allergen=str(value))
|
||||||
|
for key, level in value.items():
|
||||||
|
if key not in ALLERGENS or level not in LEVELS:
|
||||||
|
raise XeniaError("catalog.allergen", allergen=f"{key}: {level}")
|
||||||
|
return {k: value[k] for k in ALLERGENS if k in value}
|
||||||
|
|
||||||
|
|
||||||
|
def of(product) -> dict[str, str]:
|
||||||
|
"""What a product row stores, read safely (bad data in the column: nothing)."""
|
||||||
|
raw = getattr(product, "allergens", None)
|
||||||
|
if not raw:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
return normalize(raw)
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def dump(value) -> str | None:
|
||||||
|
"""For the column: JSON, or None when there are none."""
|
||||||
|
data = normalize(value)
|
||||||
|
return json.dumps(data) if data else None
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"""Smart day filters (owner 2026-11-21): the 1st / last day of the month, its first / last week, and
|
||||||
|
Greek public holidays (fixed dates and those that follow the Orthodox Easter).
|
||||||
|
|
||||||
|
The same rules in JavaScript: packages/signage/src/logic.js (a screen applies its schedule while
|
||||||
|
the server is down); both sides are tested with the same dates.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import calendar
|
||||||
|
from datetime import date, timedelta
|
||||||
|
|
||||||
|
# the filters a schedule line can have: any one that holds is enough, except "not_holiday",
|
||||||
|
# which keeps the line off on public holidays
|
||||||
|
MONTH_DAYS = ("first", "last", "first_week", "last_week", "holiday", "not_holiday")
|
||||||
|
|
||||||
|
_FIXED = ((1, 1), (1, 6), (3, 25), (5, 1), (8, 15), (10, 28), (12, 25), (12, 26))
|
||||||
|
# days from the Orthodox Easter Sunday: Clean Monday, Good Friday, Easter Sunday, Easter Monday, Whit Monday
|
||||||
|
_FROM_EASTER = (-48, -2, 0, 1, 50)
|
||||||
|
|
||||||
|
|
||||||
|
def orthodox_easter(year: int) -> date:
|
||||||
|
"""The Orthodox Easter Sunday (Meeus' Julian algorithm, + 13 days to the Gregorian calendar, 1900-2099)."""
|
||||||
|
a, b, c = year % 4, year % 7, year % 19
|
||||||
|
d = (19 * c + 15) % 30
|
||||||
|
e = (2 * a + 4 * b - d + 34) % 7
|
||||||
|
month = (d + e + 114) // 31
|
||||||
|
day = (d + e + 114) % 31 + 1
|
||||||
|
return date(year, month, day) + timedelta(days=13)
|
||||||
|
|
||||||
|
|
||||||
|
def is_holiday(day: date) -> bool:
|
||||||
|
"""A Greek public holiday (nationwide)."""
|
||||||
|
if (day.month, day.day) in _FIXED:
|
||||||
|
return True
|
||||||
|
easter = orthodox_easter(day.year)
|
||||||
|
return any(day == easter + timedelta(days=n) for n in _FROM_EASTER)
|
||||||
|
|
||||||
|
|
||||||
|
def month_days_ok(tokens, day: date) -> bool:
|
||||||
|
"""Does a day pass a line's smart filters (empty = every day)?"""
|
||||||
|
tokens = [t for t in (tokens or []) if t in MONTH_DAYS]
|
||||||
|
if not tokens:
|
||||||
|
return True
|
||||||
|
hol = is_holiday(day)
|
||||||
|
if "not_holiday" in tokens and hol:
|
||||||
|
return False
|
||||||
|
wanted = [t for t in tokens if t != "not_holiday"]
|
||||||
|
if not wanted:
|
||||||
|
return True
|
||||||
|
last = calendar.monthrange(day.year, day.month)[1]
|
||||||
|
return any((t == "first" and day.day == 1) or (t == "last" and day.day == last)
|
||||||
|
or (t == "first_week" and day.day <= 7) or (t == "last_week" and day.day > last - 7)
|
||||||
|
or (t == "holiday" and hol) for t in wanted)
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
"""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 is wrapped as code "http.<status>" with its original `detail` untouched
|
||||||
|
(the routers have none since step 6.1; tests/test_errors.py refuses new ones).
|
||||||
|
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.session_elsewhere": (409, "You're signed in on another device ({device}, since {since}). Continue? It will be signed out."),
|
||||||
|
"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, MOV 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."),
|
||||||
|
"signage.playlist_unknown": (404, "Playlist {playlist_id} not found."),
|
||||||
|
"signage.slide_unknown": (404, "Slide {slide_id} not found."),
|
||||||
|
"signage.not_a_screen": (404, "Device {device_id} isn't a signage screen."),
|
||||||
|
"signage.schedule_unknown": (404, "Schedule {schedule_id} not found."),
|
||||||
|
"signage.not_a_video": (422, "Pick a video for this slide."),
|
||||||
|
"signage.too_many_widgets": (422, "A slide holds at most {max} widgets (Signage → Message & settings → Performance)."),
|
||||||
|
"signage.content_invalid": (422, "This slide's setting isn't valid ({field}: {reason})."),
|
||||||
|
"signage.order_mismatch": (409, "The playlist changed in the meantime. Reload it and try again."),
|
||||||
|
"signage.weather_offline": (503, "The weather service can't be reached: the venue's server needs internet for it."),
|
||||||
|
"menu_tablet.no_table": (409, "This tablet isn't at a table, so it can't call a waiter."),
|
||||||
|
"menu_tablet.call_too_soon": (429, "A waiter was just called. Try again in {seconds} seconds."),
|
||||||
|
"menu_tablet.no_ordering": (409, "Ordering isn't on for this tablet."),
|
||||||
|
"menu_tablet.too_many": (422, "At most {most} items in one order."),
|
||||||
|
"menu_tablet.too_many_of": (422, "At most {most} of \"{name}\" in one order."),
|
||||||
|
"menu_tablet.too_soon": (429, "An order was just sent. Try again in {seconds} seconds."),
|
||||||
|
"menu_tablet.table_closed": (409, "Please ask a waiter to open your table first."),
|
||||||
|
"menu_tablet.day_closed": (409, "The venue isn't taking orders right now. Please ask a waiter."),
|
||||||
|
"menu_tablet.no_staff": (409, "There is no staff account to place the order with."),
|
||||||
|
"menu_tablet.order_not_found": (404, "This order was not found."),
|
||||||
|
"menu_tablet.order_answered": (409, "This order was already answered."),
|
||||||
|
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
|
||||||
|
"media.folder_unknown": (404, "That folder isn't in the media library any more."),
|
||||||
|
"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_kept": (409, "That table is already kept for {name} at {time}."),
|
||||||
|
"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."),
|
||||||
|
"catalog.allergen": (422, "Unknown allergen or level: {allergen}."),
|
||||||
|
"catalog.translation": (422, "The menu can't be translated like that: {what}."),
|
||||||
|
# converted from HTTPException (plan step 6.1)
|
||||||
|
"auth.password_current_required": (400, "Enter your current password to set a new one."),
|
||||||
|
"auth.no_password": (400, "This account has no password yet."),
|
||||||
|
"auth.password_wrong": (400, "The current password is wrong."),
|
||||||
|
"auth.password_too_short": (400, "The password must be at least {min} characters long."),
|
||||||
|
"auth.pin_too_short": (400, "The PIN must be at least {min} digits long."),
|
||||||
|
"license.locked": (423, "The system was locked by the administrator. Contact support."),
|
||||||
|
"settings.invalid_json": (422, "The settings must be valid JSON."),
|
||||||
|
"settings.unknown_key": (400, "There is no setting {key}."),
|
||||||
|
"business_day.already_open": (400, "A business day is already open."),
|
||||||
|
"business_day.none_open": (404, "No business day is open."),
|
||||||
|
"business_day.closed": (403, "The venue isn't open: a manager must open the business day first."),
|
||||||
|
"business_day.orders_open": (409, "{open_orders} table(s) still open, {partially_paid} with unpaid items."),
|
||||||
|
"business_day.not_found": (404, "Business day not found."),
|
||||||
|
"business_day.not_closed": (400, "Only a closed business day can be edited."),
|
||||||
|
"business_day.close_in_future": (400, "The closing time can't be in the future."),
|
||||||
|
"business_day.close_before_last_order": (400, "The closing time can't be earlier than the last order's close ({time})."),
|
||||||
|
"business_day.delete_open": (400, "An open business day can't be deleted. Close it first."),
|
||||||
|
"business_day.has_shifts": (409, "This business day has {count} shift(s). Delete those first."),
|
||||||
|
"validation.datetime": (422, "That date or time isn't valid."),
|
||||||
|
"validation.choice": (400, "{field} can't be {value}."),
|
||||||
|
"validation.range": (400, "{field} must be between {min} and {max}."),
|
||||||
|
"validation.positive": (400, "{field} must be more than zero."),
|
||||||
|
"validation.missing": (400, "{field} is required."),
|
||||||
|
"validation.lan_ip": (422, "Enter a local network IPv4 address (e.g. 192.168.1.50 or 10.0.0.5)."),
|
||||||
|
"chat.not_found": (404, "Conversation not found."),
|
||||||
|
"chat.not_participant": (403, "You're not in this conversation."),
|
||||||
|
"chat.empty_message": (400, "The message is empty."),
|
||||||
|
"chat.system_group": (403, "You can't leave the staff group."),
|
||||||
|
"chat.leave_direct": (400, "A one-to-one conversation can't be left."),
|
||||||
|
"chat.direct_two": (400, "A one-to-one conversation has exactly two people."),
|
||||||
|
"chat.group_name": (400, "A group conversation needs a name."),
|
||||||
|
"customer.not_found": (404, "Customer not found."),
|
||||||
|
"transfer.wrong_type": (400, "This file isn't a {expected} export."),
|
||||||
|
"transfer.version": (400, "This export's version isn't supported."),
|
||||||
|
"contact.not_found": (404, "Contact not found."),
|
||||||
|
"expense.not_found": (404, "Expense not found."),
|
||||||
|
"expense.over_due": (400, "That's more than what is still due ({due})."),
|
||||||
|
"expense.below_paid": (400, "{paid} has been paid already: the total can't be less."),
|
||||||
|
"expense.document_not_found": (404, "Document not found."),
|
||||||
|
"channel_price.not_found": (404, "Channel price not found."),
|
||||||
|
"channel_price.set_one_product": (400, "A set price is for one product: pick one product (and no categories), or change the price by an amount or a percentage."),
|
||||||
|
"scene.not_found": (404, "Scene {scene_id} not found."),
|
||||||
|
"scene.until_past": (400, "That time has already passed: pick a later one."),
|
||||||
|
"signage.scene_unknown": (404, "Scene {scene_id} not found."),
|
||||||
|
"signage.screen_unknown": (404, "Screen {device_id} not found."),
|
||||||
|
"expense.document_type": (422, "Upload a PDF or a photo (JPG, PNG, WebP or HEIC)."),
|
||||||
|
"expense.document_too_big": (413, "The file is too big (at most {max_mb} MB)."),
|
||||||
|
"flag.not_found": (404, "Mark not found."),
|
||||||
|
"flag.in_use": (409, "This mark is on {count} table(s). Remove it there first."),
|
||||||
|
"flag.invalid_ids": (400, "Some of these marks don't exist."),
|
||||||
|
"staff_message.template_not_found": (404, "Message template not found."),
|
||||||
|
"staff_message.not_found": (404, "Message not found."),
|
||||||
|
"note.not_found": (404, "Note not found."),
|
||||||
|
"todo.not_found": (404, "To-do not found."),
|
||||||
|
"order.not_yours": (403, "This order isn't one of your tables."),
|
||||||
|
"order.not_open": (400, "This order isn't open any more."),
|
||||||
|
"order.item_not_found": (404, "That item isn't on the order any more."),
|
||||||
|
"order.item_paid": (400, "This item is already paid."),
|
||||||
|
"order.item_not_active": (400, "Only items still on the order can be changed."),
|
||||||
|
"order.price_change_off": (403, "Changing prices by hand is turned off for this venue."),
|
||||||
|
"order.one_more_off": (400, "\"One more\" isn't turned on for this product."),
|
||||||
|
"order.one_more_line": (400, "This line can't be ordered again with one tap."),
|
||||||
|
"order.quantity_change_off": (403, "Changing quantities is turned off for this venue."),
|
||||||
|
"order.quantity_remove_off": (403, "Quantities can only go up at this venue."),
|
||||||
|
"order.quantity_invalid": (400, "Choose a whole number from 1 to {max}."),
|
||||||
|
"order.quantity_line": (400, "This line's quantity can't be changed here."),
|
||||||
|
"order.price_change_sent_off": (403, "Prices can only be changed before the items are sent."),
|
||||||
|
"order.price_reason_required": (400, "Say why the price changes."),
|
||||||
|
"split.not_allowed": (403, "Splitting a bill this way isn't turned on for this venue."),
|
||||||
|
"split.lines_changed": (409, "Some of these items were paid or changed meanwhile. Look again."),
|
||||||
|
"split.amount_invalid": (400, "Each part must be more than 0 and less than the total ({total})."),
|
||||||
|
"split.part_locked": (400, "This is part of a split bill: undo the split to change it."),
|
||||||
|
"split.not_found": (404, "That split bill isn't there any more."),
|
||||||
|
"split.paid_already": (409, "A part is already paid or on a tab: the split can't be undone."),
|
||||||
|
"split.parts_unpaid": (400, "Parts of a split bill are still unpaid: take their payment first."),
|
||||||
|
"order.nothing_paid": (404, "There are no paid items to undo."),
|
||||||
|
"order.cannot_close": (400, "This order can't be closed now ({status})."),
|
||||||
|
"order.no_active_items": (400, "None of these items are on the order any more."),
|
||||||
|
"order.waiter_assigned": (400, "That waiter is already on this order."),
|
||||||
|
"order.assignment_not_found": (404, "That waiter isn't on this order."),
|
||||||
|
"order.same_table": (400, "The order is already on that table."),
|
||||||
|
"order.same_order": (400, "An order can't be joined with itself."),
|
||||||
|
"order.target_not_found": (404, "The other order isn't there any more."),
|
||||||
|
"order.split_quantity": (400, "Split into 1 to {max} pieces."),
|
||||||
|
"order.discounts_off": (403, "Discounts are turned off for this venue."),
|
||||||
|
"order.no_customer": (400, "Give the order a customer first."),
|
||||||
|
"order.item_not_tabbable": (400, "This item is already {status}: it can't go on a tab."),
|
||||||
|
"order.product_unavailable": (400, "Product {product_id} isn't available."),
|
||||||
|
"printer.not_found": (404, "That printer isn't there or is turned off."),
|
||||||
|
"print_job.not_found": (404, "That print job isn't there any more."),
|
||||||
|
"print_job.not_pending": (400, "Only tickets still waiting to print can be cancelled."),
|
||||||
|
"print_job.done": (409, "That ticket isn't waiting any more: it was printed or dealt with on another screen."),
|
||||||
|
"print.printer_off": (409, "The printer {printer} is turned off in the settings."),
|
||||||
|
"print.redirect_failed": (502, "{printer} didn't print it either ({error}). The ticket is still waiting."),
|
||||||
|
"table.not_found": (404, "Table not found."),
|
||||||
|
"floor_plan.not_found": (404, "Floor plan not found."),
|
||||||
|
"floor_plan.bad_outline": (422, "The floor's shape needs 3 to 100 corners, all inside the plan."),
|
||||||
|
"floor_plan.bad_zone": (422, "That zone no longer exists."),
|
||||||
|
"floor_plan.bad_background": (422, "The background must be a picture from the media library."),
|
||||||
|
"floor_plan.bad_layout": (422, "The layout has a table twice or a place that is not a number."),
|
||||||
|
"table.busy": (400, "That table already has an open order."),
|
||||||
|
"table.has_order": (400, "A table with an open order can't be deleted or turned off."),
|
||||||
|
"table.name_too_long": (400, "The table names would be too long ({name}: at most {max} characters). Shorten the prefix or make fewer."),
|
||||||
|
"table_group.name_taken": (400, "There is already a group with that name."),
|
||||||
|
"table_group.not_found": (404, "Table group not found."),
|
||||||
|
"prep_zone.not_found": (404, "Prep zone not found."),
|
||||||
|
"price_group.not_found": (404, "Price group not found."),
|
||||||
|
"modifier.not_found": (404, "Price rule not found."),
|
||||||
|
"deal.not_found": (404, "Deal not found."),
|
||||||
|
"pricing.bad_condition": (422, "A condition is incomplete: fill in all its values."),
|
||||||
|
"pricing.bad_limit": (422, "A discount limit must be a number of 0 or more, or empty for no limit."),
|
||||||
|
"catalog.category_not_found": (404, "Category not found."),
|
||||||
|
"catalog.parent_not_found": (404, "The parent category doesn't exist."),
|
||||||
|
"catalog.nest_has_children": (400, "A category with sub-categories can't go under another one."),
|
||||||
|
"catalog.too_deep": (400, "Categories go at most two levels deep."),
|
||||||
|
"catalog.own_parent": (400, "A category can't be its own parent."),
|
||||||
|
"catalog.group_not_found": (404, "Option group not found."),
|
||||||
|
"product.not_found": (404, "Product not found."),
|
||||||
|
"product.in_past_orders": (400, "This product is in past orders, so it can't be deleted. Archive it instead."),
|
||||||
|
"staff.not_found": (404, "Staff member not found."),
|
||||||
|
"staff.username_taken": (409, "That username is already taken."),
|
||||||
|
"staff.superadmin_protected": (403, "A superadmin account can't be changed."),
|
||||||
|
"staff.superadmin_only": (403, "Only a superadmin can give the superadmin role."),
|
||||||
|
"staff.role_invalid": (400, "There is no role {role}."),
|
||||||
|
"staff.avatar_type": (400, "The photo must be a picture file."),
|
||||||
|
"staff.assignment_exists": (400, "That assignment already exists."),
|
||||||
|
"staff.pin_invalid": (422, "A PIN is {min} to {max} digits."),
|
||||||
|
"staff.username_needed": (422, "Every person needs a username."),
|
||||||
|
"staff.password_own": (409, "Change your own password from your profile."),
|
||||||
|
"staff.delete_self": (409, "You can't delete yourself."),
|
||||||
|
"staff.has_history": (409, "{name} has orders or shifts on record, so they can't be deleted. Block them instead: they can't sign in, and the reports keep their name."),
|
||||||
|
"staff.assignment_not_found": (404, "Assignment not found."),
|
||||||
|
"schedule.shift_not_found": (404, "Scheduled shift not found."),
|
||||||
|
"schedule.bad_time": (422, "Times are written like 09:30."),
|
||||||
|
"schedule.overlap": (409, "{name} already has a shift from {start} to {end} that day."),
|
||||||
|
"setup.done": (409, "Setup is already done: a manager account exists."),
|
||||||
|
"shift.already_active": (400, "This person already has a shift going."),
|
||||||
|
"shift.start_needs_manager": (403, "Starting the shift needs a manager's approval."),
|
||||||
|
"shift.end_needs_manager": (403, "Ending the shift needs a manager's approval."),
|
||||||
|
"shift.others_need_manager": (403, "Only managers can start shifts for other staff."),
|
||||||
|
"shift.none_active": (404, "No shift is going."),
|
||||||
|
"shift.not_found": (404, "Shift not found."),
|
||||||
|
"shift.not_yours": (403, "This shift belongs to someone else."),
|
||||||
|
"shift.ended": (400, "This shift has already ended."),
|
||||||
|
"shift.on_break": (400, "A break is already going."),
|
||||||
|
"shift.no_break": (404, "No break is going."),
|
||||||
|
"shift.delete_active": (400, "A shift that is still going can't be deleted. End it first."),
|
||||||
|
"tab.not_found": (404, "Tab not found."),
|
||||||
|
"tab.already_open": (400, "This customer already has an open tab."),
|
||||||
|
"tab.over_balance": (400, "That's more than the balance ({balance})."),
|
||||||
|
"tab.has_balance": (400, "The tab still owes {balance}. Pay it or forgive it first."),
|
||||||
|
"waste.not_found": (404, "Throwaway entry not found."),
|
||||||
|
"waste.not_today": (403, "Only throwaways of the open business day can be deleted."),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
@@ -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))
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
{
|
||||||
|
"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": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ",
|
||||||
|
"split": "ΔΙΑΧΩΡΙΣΜΟΣ (ΕΞΟΦΛΕΙΤΑΙ ΑΠΟ ΤΑ ΜΕΡΗ):"
|
||||||
|
},
|
||||||
|
"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}· συνεχίζει να προσπαθεί). Ελέγξτε τον εκτυπωτή."
|
||||||
|
},
|
||||||
|
"business_day": {
|
||||||
|
"not_open": "Είναι {time} και η ημέρα δεν έχει ανοίξει.",
|
||||||
|
"open_blocked": "Η ημέρα δεν άνοιξε μόνη της στις {time}: η άδεια δεν το επιτρέπει ({reason}).",
|
||||||
|
"tables_open": "Είναι ώρα κλεισίματος ({time}) αλλά {count} παραγγελίες είναι ακόμα ανοιχτές. Η ημέρα κλείνει μόνη της μόλις κλείσουν.",
|
||||||
|
"not_closed": "Η ημέρα έπρεπε να κλείσει στις {time} και είναι ακόμα ανοιχτή."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"system_product": {
|
||||||
|
"delivery_fee": "Μεταφορικά",
|
||||||
|
"split_part": "Διαχωρισμός λογαριασμού"
|
||||||
|
},
|
||||||
|
"qr": {
|
||||||
|
"order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.",
|
||||||
|
"sender": "QR μενού"
|
||||||
|
},
|
||||||
|
"tablet": {
|
||||||
|
"call_message": "Τραπεζι {table}: οι πελατες καλουν σερβιτορο.",
|
||||||
|
"sender": "Tablet μενου",
|
||||||
|
"order_sent": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), στάλθηκε στην κουζίνα.",
|
||||||
|
"order_waiting": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), επιβεβαιώστε τη στο τραπέζι.",
|
||||||
|
"bill_message": "Τραπέζι {table}: οι πελάτες ζητούν τον λογαριασμό."
|
||||||
|
},
|
||||||
|
"split": {
|
||||||
|
"part_name": "Μέρος λογαριασμού {n}/{of}"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
{
|
||||||
|
"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",
|
||||||
|
"split": "SPLIT BILL (SETTLED BY THE PARTS):"
|
||||||
|
},
|
||||||
|
"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."
|
||||||
|
},
|
||||||
|
"business_day": {
|
||||||
|
"not_open": "It's {time} and the day isn't open.",
|
||||||
|
"open_blocked": "The day didn't open by itself at {time}: the license doesn't allow it ({reason}).",
|
||||||
|
"tables_open": "It's closing time ({time}) but {count} orders are still open. The day closes by itself once they are closed.",
|
||||||
|
"not_closed": "The day should have closed at {time} and is still open."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"system_product": {
|
||||||
|
"delivery_fee": "Delivery fee",
|
||||||
|
"split_part": "Split bill"
|
||||||
|
},
|
||||||
|
"qr": {
|
||||||
|
"order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.",
|
||||||
|
"sender": "QR menu"
|
||||||
|
},
|
||||||
|
"tablet": {
|
||||||
|
"call_message": "Table {table}: the guests call a waiter.",
|
||||||
|
"sender": "Menu tablet",
|
||||||
|
"order_sent": "Table {table} ordered from the tablet ({count} items): sent to the kitchen.",
|
||||||
|
"order_waiting": "Table {table} ordered from the tablet ({count} items): confirm it on the table.",
|
||||||
|
"bill_message": "Table {table}: the guests ask for the bill."
|
||||||
|
},
|
||||||
|
"split": {
|
||||||
|
"part_name": "Split bill {n}/{of}"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
"""The menu in other languages (plan step 6.4, owner decisions 2026-11-18, D-29; every text per
|
||||||
|
language, owner 2026-11-21).
|
||||||
|
|
||||||
|
Since 2026-11-21 (Alembic 0042) every text of the menu is kept **per language**, the venue's own
|
||||||
|
language included: a product's name and description, a category's name, and every choice's name
|
||||||
|
(quick options, ingredients, extras and their sub-choices, preference sets, their choices,
|
||||||
|
sub-choices and shared sub-set, choice groups). The editor's "Default" is the venue's language
|
||||||
|
(`venue.language`). The row's own `name` / `description` is the text shown when a language has
|
||||||
|
none: the venue language's, else the first language that has one. So when the venue changes its
|
||||||
|
language, the new language starts empty ("Default" is empty) but the item keeps showing its only
|
||||||
|
text everywhere; languages are never mixed.
|
||||||
|
|
||||||
|
products.translations {"el": {"name": "…", "description": "…"}, "en": {…}}
|
||||||
|
categories.translations {"el": {"name": "…"}, …}
|
||||||
|
a choice's translations {"el": "…", "en": "…"} (the rows' column; sub-choices inside their JSON)
|
||||||
|
|
||||||
|
Before 0042 the base text had no language and quick options were translated on the product
|
||||||
|
(`"quick": {"<quick option's name>": "…"}`); 0042 moved those onto the quick options.
|
||||||
|
|
||||||
|
The menu's languages are English and Greek (fixed for now). A product's own name and
|
||||||
|
description are its base text, in whatever language the venue typed them (usually the venue's
|
||||||
|
language). Translations add the other language:
|
||||||
|
|
||||||
|
products.translations {"en": {"name": "…", "description": "…", "quick": {"<quick option's name>": "…"}}}
|
||||||
|
categories.translations {"en": {"name": "…"}}
|
||||||
|
|
||||||
|
Quick options are kept by their base name (they are recreated on every product save, so ids
|
||||||
|
change). A missing translation shows the base text, whatever its language — never Latin letters,
|
||||||
|
never a machine translation (owner). Who sees translations: the customer-facing screens (QR menu,
|
||||||
|
order app, menu tablet, signage menu boards). Tickets, the kitchen display, the counter and the
|
||||||
|
waiters' phones keep the base text (the staff's).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
MENU_LANGUAGES: tuple[str, ...] = ("el", "en")
|
||||||
|
PRODUCT_FIELDS = ("name", "description")
|
||||||
|
|
||||||
|
|
||||||
|
def _load(value):
|
||||||
|
if value in (None, "", {}):
|
||||||
|
return {}
|
||||||
|
if isinstance(value, str):
|
||||||
|
try:
|
||||||
|
value = json.loads(value)
|
||||||
|
except ValueError:
|
||||||
|
return {}
|
||||||
|
return value if isinstance(value, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def _bad(what):
|
||||||
|
from core.errors import XeniaError
|
||||||
|
return XeniaError("catalog.translation", what=what)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_product(value) -> dict:
|
||||||
|
"""API input → the stored shape; empty texts dropped; unknown languages or fields refused."""
|
||||||
|
data = _load(value)
|
||||||
|
out = {}
|
||||||
|
for lang, fields in data.items():
|
||||||
|
if lang not in MENU_LANGUAGES or not isinstance(fields, dict):
|
||||||
|
raise _bad(lang)
|
||||||
|
clean = {}
|
||||||
|
for k, v in fields.items():
|
||||||
|
if k in PRODUCT_FIELDS:
|
||||||
|
if v is not None and not isinstance(v, str):
|
||||||
|
raise _bad(f"{lang}.{k}")
|
||||||
|
if (v or "").strip():
|
||||||
|
clean[k] = v.strip()
|
||||||
|
elif k == "quick":
|
||||||
|
if not isinstance(v, dict):
|
||||||
|
raise _bad(f"{lang}.quick")
|
||||||
|
quick = {str(base): str(text).strip() for base, text in v.items() if str(text or "").strip()}
|
||||||
|
if quick:
|
||||||
|
clean["quick"] = quick
|
||||||
|
else:
|
||||||
|
raise _bad(f"{lang}.{k}")
|
||||||
|
if clean:
|
||||||
|
out[lang] = clean
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_category(value) -> dict:
|
||||||
|
data = _load(value)
|
||||||
|
out = {}
|
||||||
|
for lang, fields in data.items():
|
||||||
|
if lang not in MENU_LANGUAGES or not isinstance(fields, dict) or set(fields) - {"name"}:
|
||||||
|
raise _bad(lang)
|
||||||
|
if (fields.get("name") or "").strip():
|
||||||
|
out[lang] = {"name": fields["name"].strip()}
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def dump(data: dict) -> str | None:
|
||||||
|
return json.dumps(data, ensure_ascii=False) if data else None
|
||||||
|
|
||||||
|
|
||||||
|
def of(row) -> dict:
|
||||||
|
"""A product's or category's stored translations, read safely."""
|
||||||
|
return _load(getattr(row, "translations", None))
|
||||||
|
|
||||||
|
|
||||||
|
def texts(base: str | None, translations: dict, field: str) -> dict:
|
||||||
|
"""{language: text} for every menu language: the translation, else the base text."""
|
||||||
|
return {lang: (translations.get(lang) or {}).get(field) or base for lang in MENU_LANGUAGES}
|
||||||
|
|
||||||
|
|
||||||
|
def quick_texts(base: str, translations: dict, own: dict | None = None) -> dict:
|
||||||
|
"""A quick option's texts: its own translations (since 0042), else the product's old
|
||||||
|
`quick` map, else the base text."""
|
||||||
|
own = own or {}
|
||||||
|
return {lang: own.get(lang) or ((translations.get(lang) or {}).get("quick") or {}).get(base) or base for lang in MENU_LANGUAGES}
|
||||||
|
|
||||||
|
|
||||||
|
def product_texts(product, customer: bool = True) -> dict:
|
||||||
|
"""{"names": {lang: …}, "descriptions": {lang: …}} for a customer-facing screen. `customer`:
|
||||||
|
the customer apps' own name / description (digital_*) are the base when set."""
|
||||||
|
tr = of(product)
|
||||||
|
name = (product.digital_name if customer else None) or product.name
|
||||||
|
desc = (product.digital_description if customer else None) or product.description
|
||||||
|
return {"names": texts(name, tr, "name"), "descriptions": texts(desc or None, tr, "description")}
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_names(value) -> dict:
|
||||||
|
"""A choice's translations {language: text}: API input → stored; empty texts dropped."""
|
||||||
|
data = _load(value)
|
||||||
|
out = {}
|
||||||
|
for lang, text in data.items():
|
||||||
|
if text is not None and not isinstance(text, str):
|
||||||
|
raise _bad(str(lang))
|
||||||
|
if not (text or "").strip():
|
||||||
|
continue # empty: nothing to keep, whatever the language
|
||||||
|
if lang not in MENU_LANGUAGES:
|
||||||
|
raise _bad(str(lang))
|
||||||
|
out[lang] = text.strip()
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def names_of(row) -> dict:
|
||||||
|
"""A choice row's translations {language: text}, read safely."""
|
||||||
|
return {k: v for k, v in _load(getattr(row, "translations", None)).items() if isinstance(v, str)}
|
||||||
|
|
||||||
|
|
||||||
|
def name_texts(base: str, names: dict) -> dict:
|
||||||
|
"""{language: text} of a choice for every menu language: its own, else the base text."""
|
||||||
|
return {lang: names.get(lang) or base for lang in MENU_LANGUAGES}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Module system: manifests, registry, enablement, gating, workers (APPS_PLATFORM §4, §5.3, D-19)."""
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
"""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 _identity_brief(db) -> dict:
|
||||||
|
"""What every app needs of the venue's identity (6R.20): its first colour (the accent when
|
||||||
|
venue.theme is "identity"), the slogan and the logos' addresses. Public, like the venue's name."""
|
||||||
|
try:
|
||||||
|
from routers.identity import identity_out
|
||||||
|
ident = identity_out(db)
|
||||||
|
except Exception:
|
||||||
|
return {"colour": None, "slogan": None, "logo": None, "logo_light": None, "logo_dark": None, "icon": None}
|
||||||
|
logos = ident.get("logos") or {}
|
||||||
|
|
||||||
|
def card(k):
|
||||||
|
return (logos.get(k) or {}).get("card")
|
||||||
|
return {"colour": (ident.get("colours") or [{}])[0].get("colour"), "slogan": ident.get("slogan"),
|
||||||
|
"logo": card("main"), "logo_light": card("light"), "logo_dark": card("dark"), "icon": (logos.get("icon") or {}).get("thumb")}
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
"identity": _identity_brief(db), # 6R.20: its colour and logos for the apps
|
||||||
|
"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)
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
"""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 == "signage_playlists":
|
||||||
|
from models.signage import SignagePlaylist
|
||||||
|
return db.get(SignagePlaylist, value) is not None
|
||||||
|
if source == "signage_slides":
|
||||||
|
from models.signage import SignageSavedSlide
|
||||||
|
return db.get(SignageSavedSlide, value) is not None
|
||||||
|
if source == "tables":
|
||||||
|
from models.table import Table
|
||||||
|
t = db.get(Table, value)
|
||||||
|
return t is not None and bool(t.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]
|
||||||
@@ -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)
|
||||||
@@ -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}},
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
@@ -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}
|
||||||
@@ -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
|
||||||
@@ -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()
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
"""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),
|
||||||
|
Notification.resolved_at.is_(None),
|
||||||
|
).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()
|
||||||
|
|
||||||
|
|
||||||
|
def resolve(db, dedupe_keys) -> int:
|
||||||
|
"""Sticky alerts whose cause is gone (6F.8): hide the live rows with these dedupe keys.
|
||||||
|
Sends `platform_notification` {id, resolved: true} so open bells refresh. Commits."""
|
||||||
|
from models.notification import Notification
|
||||||
|
rows = db.query(Notification).filter(Notification.dedupe_key.in_(list(dedupe_keys)),
|
||||||
|
Notification.resolved_at.is_(None)).all()
|
||||||
|
if not rows:
|
||||||
|
return 0
|
||||||
|
now = utcnow()
|
||||||
|
for r in rows:
|
||||||
|
r.resolved_at = now
|
||||||
|
db.commit()
|
||||||
|
try:
|
||||||
|
from services.ws_bus import broadcast_sync
|
||||||
|
for r in rows:
|
||||||
|
broadcast_sync(EVENT, {"id": r.id, "resolved": True}, user_ids=recipients(db, r.audience))
|
||||||
|
except Exception:
|
||||||
|
logger.exception("notification.resolve_event_failed")
|
||||||
|
return len(rows)
|
||||||
|
|
||||||
|
|
||||||
|
# ── 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)
|
||||||
@@ -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])
|
||||||
@@ -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()
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
"""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 | ask).
|
||||||
|
`ask` (waiters, the default since 6F.7): a login while signed in elsewhere is refused with
|
||||||
|
auth.session_elsewhere (where, since when) until the app retries with replace=True; then
|
||||||
|
the old sessions end with reason "replaced" (their sockets get session.ended at once).
|
||||||
|
Only the waiter's phones count: a terminal session (the counter) is its own client.
|
||||||
|
- 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:
|
||||||
|
if client == "waiter":
|
||||||
|
return _setting(db, "auth.single_session_waiter", "ask") # 6F.7: ask is the default
|
||||||
|
return _setting(db, "auth.single_session_manager", "off") if client == "manager" else "off"
|
||||||
|
|
||||||
|
|
||||||
|
# ── lifecycle ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def device_label(user_agent: str | None) -> str:
|
||||||
|
"""A short, language-neutral name for where a session runs ("Android · Chrome")."""
|
||||||
|
ua = user_agent or ""
|
||||||
|
system = next((name for key, name in (("iPhone", "iPhone"), ("iPad", "iPad"), ("Android", "Android"),
|
||||||
|
("Windows", "Windows"), ("Macintosh", "Mac"), ("Linux", "Linux"))
|
||||||
|
if key in ua), "")
|
||||||
|
browser = next((name for key, name in (("EdgA", "Edge"), ("Edg/", "Edge"), ("Firefox", "Firefox"), ("FxiOS", "Firefox"),
|
||||||
|
("CriOS", "Chrome"), ("Chrome", "Chrome"), ("Safari", "Safari"))
|
||||||
|
if key in ua), "")
|
||||||
|
if "; wv)" in ua:
|
||||||
|
browser = "app"
|
||||||
|
return " · ".join(x for x in (system, browser) if x)
|
||||||
|
|
||||||
|
|
||||||
|
def start(db, user, client: str, request=None, *, device=None, expires_at=None, replace: bool = False):
|
||||||
|
"""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). `replace`: the person said yes to signing
|
||||||
|
out their other session (rule `ask`)."""
|
||||||
|
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)
|
||||||
|
if active and rule == "ask" and not replace:
|
||||||
|
last = max(active, key=lambda s: s.created_at)
|
||||||
|
from core.timeutil import iso_z
|
||||||
|
raise XeniaError("auth.session_elsewhere", client=client, since=iso_z(last.created_at),
|
||||||
|
device=device_label(last.user_agent) or "?", ip=last.ip or "")
|
||||||
|
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)
|
||||||
|
# why it ended (replaced, logout, idle...): the app can say "you signed in elsewhere"
|
||||||
|
raise XeniaError("auth.session_ended", reason=(row.end_reason if row is not None else None) or "unknown")
|
||||||
|
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"
|
||||||
|
|
||||||
|
|
||||||
|
def terminal_requires_username(db, device=None) -> bool:
|
||||||
|
"""Paired screens (6F.7): type a username instead of picking a name. The device's own
|
||||||
|
choice (Device.require_username) wins over the venue's auth.terminal_require_username."""
|
||||||
|
own = getattr(device, "require_username", None)
|
||||||
|
if own is not None:
|
||||||
|
return bool(own)
|
||||||
|
return _setting(db, "auth.terminal_require_username", "false") == "true"
|
||||||
@@ -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))
|
||||||
@@ -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)
|
||||||
+555
-95
@@ -4,24 +4,33 @@ Populates the POS database with realistic demo data for customer presentations.
|
|||||||
|
|
||||||
Generates:
|
Generates:
|
||||||
- 1 manager account (username: manager / PIN: 1234 / password: password)
|
- 1 manager account (username: manager / PIN: 1234 / password: password)
|
||||||
- 4 demo waiters
|
- 4 waiters with real Greek names
|
||||||
- 2 table groups with 12 tables total
|
- 2 table groups with 13 tables total
|
||||||
- A full menu: 3 categories, ~20 products
|
- A full menu: 3 categories, ~20 products with costs
|
||||||
- 45 days of backdated history (business days, shifts, orders, payments)
|
- 120 days of backdated history with realistic time distribution
|
||||||
|
- Online orders (source="online") scattered through history
|
||||||
|
- Order cancellations (~10% of items)
|
||||||
|
- Site notes and todos
|
||||||
|
- Contacts (suppliers) and expenses over the period
|
||||||
|
- Customers and tabs
|
||||||
|
- Scheduled shifts for the next 3 weeks
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
python demo_seed.py
|
python demo_seed.py
|
||||||
|
|
||||||
Must be run from the local_backend directory. Designed to run on a clean DB
|
Must be run from the local_backend directory. Designed to run on a clean DB
|
||||||
(after wipe_database.py), but safe to run multiple times — checks for the
|
(after wipe_database.py), but safe to run multiple times — checks for the
|
||||||
[DEMO] marker before inserting anything.
|
DEMO guard before inserting anything.
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import random
|
import random
|
||||||
import sys
|
import sys
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, date, timezone
|
||||||
|
|
||||||
import bcrypt
|
import bcrypt
|
||||||
|
|
||||||
|
from core.timeutil import business_date_of, utcnow
|
||||||
|
from core.access.templates import apply_role_template
|
||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
|
|
||||||
from database import engine, Base, SessionLocal
|
from database import engine, Base, SessionLocal
|
||||||
@@ -30,21 +39,38 @@ import models.user
|
|||||||
import models.table
|
import models.table
|
||||||
import models.printer
|
import models.printer
|
||||||
import models.product
|
import models.product
|
||||||
|
import models.customers # noqa: F401 — must be before models.order (orders.customer_id FK)
|
||||||
import models.order
|
import models.order
|
||||||
import models.business_day
|
import models.business_day
|
||||||
import models.shift
|
import models.shift
|
||||||
import models.settings
|
import models.settings
|
||||||
import models.flag
|
import models.flag
|
||||||
import models.message
|
import models.message
|
||||||
|
import models.notes # noqa: F401 — registers tables with Base.metadata
|
||||||
|
import models.expenses # noqa: F401
|
||||||
|
import models.tabs # noqa: F401
|
||||||
|
import models.schedule # noqa: F401
|
||||||
|
import models.waste # noqa: F401
|
||||||
|
import models.reservation # noqa: F401
|
||||||
|
import models.pricing # noqa: F401 — order_items.deal_id → deals
|
||||||
|
import models.prep_zone # noqa: F401
|
||||||
|
import models.chat # noqa: F401
|
||||||
|
import models.recovery_code # noqa: F401
|
||||||
|
|
||||||
from models.user import User, WaiterZone
|
from models.user import User, WaiterZone
|
||||||
from models.table import TableGroup, Table
|
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.order import Order, OrderItem, OrderWaiter, OrderAuditLog
|
||||||
from models.business_day import BusinessDay
|
from models.business_day import BusinessDay
|
||||||
from models.shift import WaiterShift
|
from models.shift import WaiterShift
|
||||||
|
from models.notes import SiteNote, SiteTodo
|
||||||
|
from models.expenses import Contact, Expense, ExpensePayment
|
||||||
|
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 ────────────────────────────────────────────────────────────────────
|
# ── Config ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -83,34 +109,58 @@ def _audit(db, order_id, event_type, waiter_id=None, item_ids=None,
|
|||||||
db.add(log)
|
db.add(log)
|
||||||
|
|
||||||
|
|
||||||
|
def _random_time_in_day(day_date: date, hour_weights: list) -> datetime:
|
||||||
|
"""
|
||||||
|
Returns a random datetime in day_date, biased toward peak hours.
|
||||||
|
hour_weights: list of (hour, weight) tuples covering the operating hours.
|
||||||
|
"""
|
||||||
|
hours = [h for h, _ in hour_weights]
|
||||||
|
weights = [w for _, w in hour_weights]
|
||||||
|
h = random.choices(hours, weights=weights)[0]
|
||||||
|
m = random.randint(0, 59)
|
||||||
|
return datetime(day_date.year, day_date.month, day_date.day, h, m)
|
||||||
|
|
||||||
|
|
||||||
|
# Operating hours weighted toward lunch (12-14) and dinner peaks (19-22),
|
||||||
|
# with lighter morning coffee traffic (10-11) and afternoon lulls (15-18).
|
||||||
|
HOUR_WEIGHTS = [
|
||||||
|
(10, 3), (11, 5),
|
||||||
|
(12, 12), (13, 15), (14, 10),
|
||||||
|
(15, 4), (16, 3), (17, 4),
|
||||||
|
(18, 6), (19, 14), (20, 16), (21, 13), (22, 8),
|
||||||
|
]
|
||||||
|
|
||||||
|
# Day-of-week multipliers (Mon=0 … Sun=6) — weekends busier
|
||||||
|
DOW_MULTIPLIER = {0: 0.75, 1: 0.75, 2: 0.80, 3: 0.85, 4: 1.00, 5: 1.20, 6: 1.10}
|
||||||
|
|
||||||
# ── Menu definition ───────────────────────────────────────────────────────────
|
# ── Menu definition ───────────────────────────────────────────────────────────
|
||||||
# (category_name, color, [(product_name, price), ...])
|
# (category_name, color, [(product_name, price, cost), ...])
|
||||||
MENU = [
|
MENU = [
|
||||||
("Ορεκτικά", "#f97316", [
|
("Ορεκτικά", "#f97316", [
|
||||||
("Τζατζίκι", 4.50),
|
("Τζατζίκι", 4.50, 1.20),
|
||||||
("Ταραμοσαλάτα", 4.50),
|
("Ταραμοσαλάτα", 4.50, 1.10),
|
||||||
("Χωριάτικη Σαλάτα", 7.50),
|
("Χωριάτικη Σαλάτα",7.50, 2.00),
|
||||||
("Κεφτεδάκια", 8.00),
|
("Κεφτεδάκια", 8.00, 2.80),
|
||||||
("Σαγανάκι", 6.50),
|
("Σαγανάκι", 6.50, 2.20),
|
||||||
("Χούμους", 5.00),
|
("Χούμους", 5.00, 1.40),
|
||||||
]),
|
]),
|
||||||
("Κυρίως Πιάτα", "#ef4444", [
|
("Κυρίως Πιάτα", "#ef4444", [
|
||||||
("Μπριζόλα Χοιρινή", 12.00),
|
("Μπριζόλα Χοιρινή", 12.00, 4.50),
|
||||||
("Μπριζόλα Μοσχαρίσια", 16.00),
|
("Μπριζόλα Μοσχαρίσια", 16.00, 7.00),
|
||||||
("Σουβλάκι Κοτόπουλο", 10.00),
|
("Σουβλάκι Κοτόπουλο", 10.00, 3.20),
|
||||||
("Μουσακάς", 11.00),
|
("Μουσακάς", 11.00, 3.80),
|
||||||
("Παστίτσιο", 10.00),
|
("Παστίτσιο", 10.00, 3.50),
|
||||||
("Σπαγγέτι Μπολονέζ", 9.50),
|
("Σπαγγέτι Μπολονέζ", 9.50, 3.00),
|
||||||
("Γύρος Χοιρινός", 8.50),
|
("Γύρος Χοιρινός", 8.50, 2.60),
|
||||||
]),
|
]),
|
||||||
("Ποτά & Αναψυκτικά", "#3b82f6", [
|
("Ποτά & Αναψυκτικά", "#3b82f6", [
|
||||||
("Νερό 500ml", 1.00),
|
("Νερό 500ml", 1.00, 0.20),
|
||||||
("Αναψυκτικό", 2.50),
|
("Αναψυκτικό", 2.50, 0.60),
|
||||||
("Μπύρα Φιάλη", 4.00),
|
("Μπύρα Φιάλη", 4.00, 1.20),
|
||||||
("Κρασί (ποτήρι)", 4.50),
|
("Κρασί (ποτήρι)", 4.50, 1.00),
|
||||||
("Καφές Ελληνικός", 2.50),
|
("Καφές Ελληνικός", 2.50, 0.45),
|
||||||
("Φραπέ", 3.00),
|
("Φραπέ", 3.00, 0.50),
|
||||||
("Χυμός Πορτοκάλι", 3.50),
|
("Χυμός Πορτοκάλι", 3.50, 0.90),
|
||||||
]),
|
]),
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -118,23 +168,30 @@ MENU = [
|
|||||||
CATEGORY_WEIGHTS = [0.25, 0.35, 0.40]
|
CATEGORY_WEIGHTS = [0.25, 0.35, 0.40]
|
||||||
|
|
||||||
WAITER_NAMES = [
|
WAITER_NAMES = [
|
||||||
("Νίκος", "Νίκος Π."),
|
("Νίκος", "Νίκος Παπαδόπουλος", "demo_nikos", "2201"),
|
||||||
("Μαρία", "Μαρία Κ."),
|
("Μαρία", "Μαρία Κωνσταντίνου", "demo_maria", "3302"),
|
||||||
("Πέτρος", "Πέτρος Α."),
|
("Πέτρος", "Πέτρος Αναστασίου", "demo_petros", "4403"),
|
||||||
("Έλενα", "Έλενα Μ."),
|
("Έλενα", "Έλενα Μιχαηλίδου", "demo_elena", "5504"),
|
||||||
]
|
]
|
||||||
|
|
||||||
PAYMENT_METHODS = ["cash", "cash", "cash", "card", "card"] # 60% cash / 40% card
|
PAYMENT_METHODS = ["cash", "cash", "cash", "card", "card"] # 60% cash / 40% card
|
||||||
|
|
||||||
|
CANCEL_REASONS = [
|
||||||
|
"Λάθος παραγγελία",
|
||||||
|
"Ο πελάτης άλλαξε γνώμη",
|
||||||
|
"Το προϊόν δεν είναι διαθέσιμο",
|
||||||
|
"Λάθος τραπέζι",
|
||||||
|
]
|
||||||
|
|
||||||
# ── Main ──────────────────────────────────────────────────────────────────────
|
# ── Main ──────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
db = SessionLocal()
|
db = SessionLocal()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# ── Guard: abort if demo data already present ─────────────────────────────
|
# ── Guard: abort if demo data already present ─────────────────────────────
|
||||||
existing = db.query(User).filter(User.full_name.like("[DEMO]%")).first()
|
existing = db.query(User).filter(User.username == "demo_nikos").first()
|
||||||
if existing:
|
if existing:
|
||||||
print("Demo data already present (found [DEMO] user). Nothing to do.")
|
print("Demo data already present (found demo_nikos user). Nothing to do.")
|
||||||
print("Run python wipe_database.py first if you want a fresh seed.")
|
print("Run python wipe_database.py first if you want a fresh seed.")
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
@@ -147,15 +204,15 @@ try:
|
|||||||
username="manager",
|
username="manager",
|
||||||
pin_hash=_hash_pin("1234"),
|
pin_hash=_hash_pin("1234"),
|
||||||
password_hash=_hash_password("password"),
|
password_hash=_hash_password("password"),
|
||||||
role="manager",
|
role="owner", # the demo "manager" can do everything, as in v1
|
||||||
full_name="Manager",
|
full_name="Manager",
|
||||||
is_active=True,
|
is_active=True,
|
||||||
)
|
)
|
||||||
|
apply_role_template(manager)
|
||||||
db.add(manager)
|
db.add(manager)
|
||||||
db.flush()
|
db.flush()
|
||||||
print(" created manager (username: manager / PIN: 1234 / password: password)")
|
print(" created manager (username: manager / PIN: 1234 / password: password)")
|
||||||
else:
|
else:
|
||||||
# Ensure password_hash is set on existing manager
|
|
||||||
if not manager.password_hash:
|
if not manager.password_hash:
|
||||||
manager.password_hash = _hash_password("password")
|
manager.password_hash = _hash_password("password")
|
||||||
db.flush()
|
db.flush()
|
||||||
@@ -163,22 +220,22 @@ try:
|
|||||||
|
|
||||||
# ── Waiters ───────────────────────────────────────────────────────────────
|
# ── Waiters ───────────────────────────────────────────────────────────────
|
||||||
waiters = []
|
waiters = []
|
||||||
for nickname, full_name in WAITER_NAMES:
|
for nickname, full_name, username, pin in WAITER_NAMES:
|
||||||
username = f"demo_{nickname.lower()}"
|
|
||||||
w = db.query(User).filter(User.username == username).first()
|
w = db.query(User).filter(User.username == username).first()
|
||||||
if not w:
|
if not w:
|
||||||
w = User(
|
w = User(
|
||||||
username=username,
|
username=username,
|
||||||
pin_hash=_hash_pin(str(random.randint(1000, 9999))),
|
pin_hash=_hash_pin(pin),
|
||||||
role="waiter",
|
role="waiter",
|
||||||
full_name=f"[DEMO] {full_name}",
|
full_name=full_name,
|
||||||
nickname=nickname,
|
nickname=nickname,
|
||||||
is_active=True,
|
is_active=True,
|
||||||
)
|
)
|
||||||
|
apply_role_template(w)
|
||||||
db.add(w)
|
db.add(w)
|
||||||
db.flush()
|
db.flush()
|
||||||
waiters.append(w)
|
waiters.append(w)
|
||||||
print(f" created {len(waiters)} demo waiters")
|
print(f" created {len(waiters)} waiters")
|
||||||
|
|
||||||
# ── Table groups & tables ─────────────────────────────────────────────────
|
# ── Table groups & tables ─────────────────────────────────────────────────
|
||||||
group_configs = [
|
group_configs = [
|
||||||
@@ -201,7 +258,7 @@ try:
|
|||||||
all_tables.append(tbl)
|
all_tables.append(tbl)
|
||||||
print(f" created {len(all_tables)} tables across {len(group_configs)} groups")
|
print(f" created {len(all_tables)} tables across {len(group_configs)} groups")
|
||||||
|
|
||||||
# ── Waiter zone assignments (all waiters → all zones) ─────────────────────
|
# ── Waiter zone assignments ───────────────────────────────────────────────
|
||||||
for w in waiters:
|
for w in waiters:
|
||||||
existing_zone = db.query(WaiterZone).filter(
|
existing_zone = db.query(WaiterZone).filter(
|
||||||
WaiterZone.waiter_id == w.id, WaiterZone.group_id.is_(None)
|
WaiterZone.waiter_id == w.id, WaiterZone.group_id.is_(None)
|
||||||
@@ -212,8 +269,8 @@ try:
|
|||||||
|
|
||||||
# ── Menu ──────────────────────────────────────────────────────────────────
|
# ── Menu ──────────────────────────────────────────────────────────────────
|
||||||
categories = []
|
categories = []
|
||||||
all_products = [] # flat list for random picks
|
all_products = []
|
||||||
category_product_map = [] # parallel list of product sub-lists (for weighted pick)
|
category_product_map = []
|
||||||
|
|
||||||
for sort_idx, (cat_name, cat_color, items) in enumerate(MENU):
|
for sort_idx, (cat_name, cat_color, items) in enumerate(MENU):
|
||||||
cat = db.query(Category).filter(Category.name == cat_name).first()
|
cat = db.query(Category).filter(Category.name == cat_name).first()
|
||||||
@@ -224,38 +281,101 @@ try:
|
|||||||
categories.append(cat)
|
categories.append(cat)
|
||||||
|
|
||||||
cat_products = []
|
cat_products = []
|
||||||
for prod_sort, (prod_name, prod_price) in enumerate(items):
|
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:
|
if not p:
|
||||||
p = Product(
|
p = Product(
|
||||||
name=prod_name,
|
name=prod_name,
|
||||||
category_id=cat.id,
|
primary_category_id=cat.id,
|
||||||
base_price=prod_price,
|
base_price=prod_price,
|
||||||
|
cost_simple=prod_cost,
|
||||||
is_available=True,
|
is_available=True,
|
||||||
lifecycle_status="active",
|
lifecycle_status="active",
|
||||||
sort_order=prod_sort,
|
sort_order=prod_sort,
|
||||||
)
|
)
|
||||||
|
p.memberships.append(ProductCategory(category_id=cat.id, sort_order=prod_sort))
|
||||||
db.add(p)
|
db.add(p)
|
||||||
db.flush()
|
db.flush()
|
||||||
|
else:
|
||||||
|
p.cost_simple = prod_cost
|
||||||
|
db.flush()
|
||||||
cat_products.append(p)
|
cat_products.append(p)
|
||||||
all_products.append(p)
|
all_products.append(p)
|
||||||
category_product_map.append(cat_products)
|
category_product_map.append(cat_products)
|
||||||
|
|
||||||
print(f" created {len(categories)} categories with {len(all_products)} products")
|
print(f" created {len(categories)} categories with {len(all_products)} products (with costs)")
|
||||||
|
|
||||||
|
# ── Contacts (suppliers & utilities) ─────────────────────────────────────
|
||||||
|
contact_defs = [
|
||||||
|
("Κρεοπωλείο Παπαδόπουλος", "supplier", "+30 22310 41234", None, "Πιερία 12, Κατερίνη", "Κύριος προμηθευτής κρέατος"),
|
||||||
|
("Αλιεύματα Κόκκαλης", "supplier", "+30 22310 55678", None, "Λιμάνι, Κατερίνη", "Φρέσκα ψάρια και θαλασσινά"),
|
||||||
|
("Χονδρικό Ελαιόλαδο", "supplier", "+30 23310 22100", "oil@agrofarm.gr","Αγροτική Οδός 5", "Ελαιόλαδο και τυρί χύμα"),
|
||||||
|
("Αναψυκτικά ΑΕΒΕ", "supplier", "+30 210 9012345", "orders@aeve.gr", "Βιομηχανική Ζώνη, Αθήνα","Αναψυκτικά, νερά, μπύρες"),
|
||||||
|
("ΔΕΗ", "utility", "11500", None, None, "Ηλεκτρισμός"),
|
||||||
|
("ΕΥΔΑΠ / Τοπικό Δίκτυο", "utility", "11888", None, None, "Νερό"),
|
||||||
|
("Cosmote Επαγγελματικό", "utility", "13888", None, None, "Τηλεφωνία & internet"),
|
||||||
|
]
|
||||||
|
contacts = []
|
||||||
|
for c_name, c_type, c_phone, c_email, c_addr, c_notes in contact_defs:
|
||||||
|
c = db.query(Contact).filter(Contact.name == c_name).first()
|
||||||
|
if not c:
|
||||||
|
c = Contact(
|
||||||
|
name=c_name,
|
||||||
|
type=c_type,
|
||||||
|
phone=c_phone,
|
||||||
|
email=c_email,
|
||||||
|
address=c_addr,
|
||||||
|
notes=c_notes,
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
db.add(c)
|
||||||
|
db.flush()
|
||||||
|
contacts.append(c)
|
||||||
|
print(f" created {len(contacts)} contacts")
|
||||||
|
|
||||||
|
# ── Customers ─────────────────────────────────────────────────────────────
|
||||||
|
customer_defs = [
|
||||||
|
("Γιώργος Σταθόπουλος", "Γιώργης", "+30 6944 111222", None, "Τακτικός πελάτης, κάθε Παρασκευή βράδυ"),
|
||||||
|
("Ελευθερία Νικολάου", "Ελευθερία","+30 6977 334455", "eleftheria@gmail.com", "Αλλεργία στη γλουτένη"),
|
||||||
|
("Δημήτρης Παππάς", "Μήτσος", "+30 6955 667788", None, "Προτιμά τραπέζι στη βεράντα"),
|
||||||
|
("Σοφία Αλεξίου", "Σοφία", "+30 6933 998877", "sofia.alex@hotmail.com", "VIP πελάτης"),
|
||||||
|
("Ομάδα Εργατών", None, "+30 6900 123456", None, "Ομάδα οικοδόμων — συχνά μεσημέρι"),
|
||||||
|
]
|
||||||
|
customers = []
|
||||||
|
for c_name, c_nick, c_phone, c_email, c_notes in customer_defs:
|
||||||
|
c = db.query(Customer).filter(Customer.name == c_name).first()
|
||||||
|
if not c:
|
||||||
|
c = Customer(
|
||||||
|
name=c_name,
|
||||||
|
nickname=c_nick,
|
||||||
|
phone=c_phone,
|
||||||
|
email=c_email,
|
||||||
|
notes=c_notes,
|
||||||
|
is_active=True,
|
||||||
|
created_by_id=manager.id,
|
||||||
|
)
|
||||||
|
db.add(c)
|
||||||
|
db.flush()
|
||||||
|
customers.append(c)
|
||||||
|
print(f" created {len(customers)} customers")
|
||||||
|
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
# ── Historical days ───────────────────────────────────────────────────────
|
# ── Historical days ───────────────────────────────────────────────────────
|
||||||
today = datetime.now(timezone.utc).date()
|
today = utcnow().date()
|
||||||
total_orders = 0
|
total_orders = 0
|
||||||
total_revenue = 0.0
|
total_revenue = 0.0
|
||||||
|
|
||||||
print(f"\nGenerating {DEMO_DAYS} days of history...")
|
print(f"\nGenerating {DEMO_DAYS} days of history...")
|
||||||
|
|
||||||
|
# Keep track of created business days (date → BusinessDay) for expense linking
|
||||||
|
bday_by_date: dict[date, BusinessDay] = {}
|
||||||
|
|
||||||
for days_ago in range(DEMO_DAYS, 0, -1):
|
for days_ago in range(DEMO_DAYS, 0, -1):
|
||||||
day_date = today - timedelta(days=days_ago)
|
day_date = today - timedelta(days=days_ago)
|
||||||
|
dow = day_date.weekday()
|
||||||
|
multiplier = DOW_MULTIPLIER[dow]
|
||||||
|
|
||||||
# Business day: opens at ~10:00, closes at ~23:30
|
|
||||||
open_time = _utc(datetime(day_date.year, day_date.month, day_date.day,
|
open_time = _utc(datetime(day_date.year, day_date.month, day_date.day,
|
||||||
10, random.randint(0, 30)))
|
10, random.randint(0, 30)))
|
||||||
close_time = _utc(datetime(day_date.year, day_date.month, day_date.day,
|
close_time = _utc(datetime(day_date.year, day_date.month, day_date.day,
|
||||||
@@ -264,18 +384,20 @@ try:
|
|||||||
bday = BusinessDay(
|
bday = BusinessDay(
|
||||||
status="closed",
|
status="closed",
|
||||||
opened_at=open_time,
|
opened_at=open_time,
|
||||||
|
business_date=business_date_of(open_time),
|
||||||
opened_by_id=manager.id,
|
opened_by_id=manager.id,
|
||||||
closed_at=close_time,
|
closed_at=close_time,
|
||||||
closed_by_id=manager.id,
|
closed_by_id=manager.id,
|
||||||
)
|
)
|
||||||
db.add(bday)
|
db.add(bday)
|
||||||
db.flush()
|
db.flush()
|
||||||
|
bday_by_date[day_date] = bday
|
||||||
|
|
||||||
# 2-4 waiters work each day
|
# 2-4 waiters work each day
|
||||||
working_waiters = random.sample(waiters, k=random.randint(2, len(waiters)))
|
working_waiters = random.sample(waiters, k=random.randint(2, len(waiters)))
|
||||||
STARTING_CASH_OPTIONS = [50.0, 80.0, 100.0, 110.0, 120.0, 150.0, 200.0]
|
STARTING_CASH_OPTIONS = [50.0, 80.0, 100.0, 110.0, 120.0, 150.0, 200.0]
|
||||||
shifts = {}
|
shifts = {}
|
||||||
shift_totals = {} # shift_id → running revenue total, filled during order loop
|
shift_totals = {}
|
||||||
for w in working_waiters:
|
for w in working_waiters:
|
||||||
shift_start = open_time + timedelta(minutes=random.randint(0, 30))
|
shift_start = open_time + timedelta(minutes=random.randint(0, 30))
|
||||||
shift_end = close_time - timedelta(minutes=random.randint(0, 20))
|
shift_end = close_time - timedelta(minutes=random.randint(0, 20))
|
||||||
@@ -291,51 +413,53 @@ try:
|
|||||||
shifts[w.id] = shift
|
shifts[w.id] = shift
|
||||||
shift_totals[shift.id] = 0.0
|
shift_totals[shift.id] = 0.0
|
||||||
|
|
||||||
# Orders — two rushes: lunch (12-15h) and dinner (19-23h)
|
# Orders distributed realistically across the day
|
||||||
n_orders = random.randint(*ORDERS_PER_DAY)
|
base_n = random.randint(*ORDERS_PER_DAY)
|
||||||
lunch_count = int(n_orders * 0.4)
|
n_orders = max(5, int(base_n * multiplier))
|
||||||
dinner_count = n_orders - lunch_count
|
|
||||||
|
# ~8% of days have 1-2 online orders
|
||||||
|
n_online = random.choices([0, 1, 2], weights=[0.60, 0.28, 0.12])[0]
|
||||||
|
n_pos = n_orders - n_online
|
||||||
|
|
||||||
order_times = []
|
order_times = []
|
||||||
for _ in range(lunch_count):
|
for _ in range(n_pos):
|
||||||
h = random.randint(12, 14)
|
order_times.append(_random_time_in_day(day_date, HOUR_WEIGHTS))
|
||||||
m = random.randint(0, 59)
|
|
||||||
order_times.append(datetime(day_date.year, day_date.month, day_date.day, h, m))
|
|
||||||
for _ in range(dinner_count):
|
|
||||||
h = random.randint(19, 22)
|
|
||||||
m = random.randint(0, 59)
|
|
||||||
order_times.append(datetime(day_date.year, day_date.month, day_date.day, h, m))
|
|
||||||
order_times.sort()
|
order_times.sort()
|
||||||
|
|
||||||
# Track which tables are "busy" at each point in time so we don't double-seat
|
# Online orders land at lunch or dinner time
|
||||||
# Format: {table_id: release_time}
|
online_order_times = []
|
||||||
|
for _ in range(n_online):
|
||||||
|
h = random.choices([12, 13, 19, 20, 21], weights=[2, 2, 3, 3, 2])[0]
|
||||||
|
online_order_times.append(datetime(day_date.year, day_date.month, day_date.day,
|
||||||
|
h, random.randint(0, 59)))
|
||||||
|
|
||||||
table_busy_until: dict[int, datetime] = {}
|
table_busy_until: dict[int, datetime] = {}
|
||||||
|
|
||||||
|
# ── POS orders ────────────────────────────────────────────────────────
|
||||||
for opened_at_naive in order_times:
|
for opened_at_naive in order_times:
|
||||||
opened_at = _utc(opened_at_naive)
|
opened_at = _utc(opened_at_naive)
|
||||||
|
|
||||||
# Pick a free table
|
|
||||||
free_tables = [
|
free_tables = [
|
||||||
t for t in all_tables
|
t for t in all_tables
|
||||||
if table_busy_until.get(t.id, datetime.min.replace(tzinfo=timezone.utc)) <= opened_at
|
if table_busy_until.get(t.id, datetime.min.replace(tzinfo=timezone.utc)) <= opened_at
|
||||||
]
|
]
|
||||||
if not free_tables:
|
if not free_tables:
|
||||||
free_tables = all_tables # all busy → just reuse (edge case)
|
free_tables = all_tables
|
||||||
table = random.choice(free_tables)
|
table = random.choice(free_tables)
|
||||||
|
|
||||||
# Pick a waiter who is working today
|
|
||||||
waiter = random.choice(working_waiters)
|
waiter = random.choice(working_waiters)
|
||||||
shift = shifts[waiter.id]
|
shift = shifts[waiter.id]
|
||||||
|
|
||||||
# Order duration: 20-70 min
|
|
||||||
duration_min = random.randint(20, 70)
|
duration_min = random.randint(20, 70)
|
||||||
closed_at = opened_at + timedelta(minutes=duration_min)
|
closed_at = opened_at + timedelta(minutes=duration_min)
|
||||||
# Cap to close_time
|
|
||||||
if closed_at > close_time:
|
if closed_at > close_time:
|
||||||
closed_at = close_time - timedelta(minutes=2)
|
closed_at = close_time - timedelta(minutes=2)
|
||||||
|
|
||||||
table_busy_until[table.id] = closed_at
|
table_busy_until[table.id] = closed_at
|
||||||
|
|
||||||
|
# ~15% of orders linked to a known customer
|
||||||
|
order_customer = random.choice(customers) if random.random() < 0.15 else None
|
||||||
|
|
||||||
order = Order(
|
order = Order(
|
||||||
table_id=table.id,
|
table_id=table.id,
|
||||||
opened_by=waiter.id,
|
opened_by=waiter.id,
|
||||||
@@ -344,21 +468,16 @@ try:
|
|||||||
closed_by=manager.id,
|
closed_by=manager.id,
|
||||||
notes=None,
|
notes=None,
|
||||||
source="pos",
|
source="pos",
|
||||||
|
customer_id=order_customer.id if order_customer else None,
|
||||||
)
|
)
|
||||||
order.opened_at = opened_at
|
order.opened_at = opened_at
|
||||||
order.closed_at = closed_at
|
order.closed_at = closed_at
|
||||||
db.add(order)
|
db.add(order)
|
||||||
db.flush()
|
db.flush()
|
||||||
|
|
||||||
db.add(OrderWaiter(
|
db.add(OrderWaiter(order_id=order.id, waiter_id=waiter.id, assigned_at=opened_at))
|
||||||
order_id=order.id,
|
|
||||||
waiter_id=waiter.id,
|
|
||||||
assigned_at=opened_at,
|
|
||||||
))
|
|
||||||
|
|
||||||
_audit(db, order.id, "ORDER_OPENED", waiter_id=waiter.id, created_at=opened_at)
|
_audit(db, order.id, "ORDER_OPENED", waiter_id=waiter.id, created_at=opened_at)
|
||||||
|
|
||||||
# Items: 2-6 items, weighted by category
|
|
||||||
n_items = random.randint(2, 6)
|
n_items = random.randint(2, 6)
|
||||||
chosen_category_lists = random.choices(category_product_map, weights=CATEGORY_WEIGHTS, k=n_items)
|
chosen_category_lists = random.choices(category_product_map, weights=CATEGORY_WEIGHTS, k=n_items)
|
||||||
items_added = []
|
items_added = []
|
||||||
@@ -368,10 +487,11 @@ try:
|
|||||||
for prod_list in chosen_category_lists:
|
for prod_list in chosen_category_lists:
|
||||||
product = random.choice(prod_list)
|
product = random.choice(prod_list)
|
||||||
qty = random.choices([1, 2, 3], weights=[0.7, 0.2, 0.1])[0]
|
qty = random.choices([1, 2, 3], weights=[0.7, 0.2, 0.1])[0]
|
||||||
payment_method = random.choice(PAYMENT_METHODS)
|
|
||||||
|
# ~10% chance the item gets cancelled
|
||||||
|
is_cancelled = random.random() < 0.10
|
||||||
paid_at = closed_at - timedelta(minutes=random.randint(1, 5))
|
paid_at = closed_at - timedelta(minutes=random.randint(1, 5))
|
||||||
line_total = product.base_price * qty
|
line_total = product.base_price * qty
|
||||||
order_total += line_total
|
|
||||||
|
|
||||||
item = OrderItem(
|
item = OrderItem(
|
||||||
order_id=order.id,
|
order_id=order.id,
|
||||||
@@ -379,44 +499,384 @@ try:
|
|||||||
added_by=waiter.id,
|
added_by=waiter.id,
|
||||||
quantity=qty,
|
quantity=qty,
|
||||||
unit_price=product.base_price,
|
unit_price=product.base_price,
|
||||||
status="paid",
|
unit_cost=product.cost_simple,
|
||||||
|
status="cancelled" if is_cancelled else "paid",
|
||||||
printed=True,
|
printed=True,
|
||||||
paid_by=waiter.id,
|
|
||||||
paid_at=_utc(paid_at),
|
|
||||||
payment_method=payment_method,
|
|
||||||
paid_in_shift_id=shift.id,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if is_cancelled:
|
||||||
|
cancel_at = items_added_at + timedelta(minutes=random.randint(1, 10))
|
||||||
|
item.cancelled_by = waiter.id
|
||||||
|
item.cancelled_at = _utc(cancel_at)
|
||||||
|
item.cancel_reason = random.choice(CANCEL_REASONS)
|
||||||
|
else:
|
||||||
|
payment_method = random.choice(PAYMENT_METHODS)
|
||||||
|
item.paid_by = waiter.id
|
||||||
|
item.paid_at = _utc(paid_at)
|
||||||
|
item.payment_method = payment_method
|
||||||
|
item.paid_in_shift_id = shift.id
|
||||||
|
order_total += line_total
|
||||||
|
shift_totals[shift.id] = round(shift_totals[shift.id] + line_total, 2)
|
||||||
|
|
||||||
item.added_at = _utc(items_added_at)
|
item.added_at = _utc(items_added_at)
|
||||||
db.add(item)
|
db.add(item)
|
||||||
db.flush()
|
db.flush()
|
||||||
items_added.append(item.id)
|
items_added.append(item.id)
|
||||||
shift_totals[shift.id] = round(shift_totals[shift.id] + line_total, 2)
|
|
||||||
|
|
||||||
_audit(db, order.id, "ITEMS_ADDED",
|
_audit(db, order.id, "ITEMS_ADDED",
|
||||||
waiter_id=waiter.id, item_ids=items_added,
|
waiter_id=waiter.id, item_ids=items_added, created_at=items_added_at)
|
||||||
created_at=items_added_at)
|
|
||||||
|
|
||||||
# Payment audit (single payment per order for simplicity)
|
|
||||||
payment_method = random.choice(PAYMENT_METHODS)
|
payment_method = random.choice(PAYMENT_METHODS)
|
||||||
pay_at = closed_at - timedelta(minutes=1)
|
pay_at = closed_at - timedelta(minutes=1)
|
||||||
_audit(db, order.id, "PAYMENT",
|
_audit(db, order.id, "PAYMENT",
|
||||||
waiter_id=waiter.id, item_ids=items_added,
|
waiter_id=waiter.id, item_ids=items_added,
|
||||||
amount=round(order_total, 2), payment_method=payment_method,
|
amount=round(order_total, 2), payment_method=payment_method,
|
||||||
created_at=pay_at)
|
created_at=pay_at)
|
||||||
|
_audit(db, order.id, "ORDER_CLOSED", waiter_id=waiter.id, created_at=closed_at)
|
||||||
_audit(db, order.id, "ORDER_CLOSED",
|
|
||||||
waiter_id=waiter.id, created_at=closed_at)
|
|
||||||
|
|
||||||
total_orders += 1
|
total_orders += 1
|
||||||
total_revenue += order_total
|
total_revenue += order_total
|
||||||
|
|
||||||
# Write total_collected snapshot onto each ended shift
|
# ── Online orders ─────────────────────────────────────────────────────
|
||||||
|
online_ref_counter = days_ago * 10 # rough unique ref per day
|
||||||
|
for ot in online_order_times:
|
||||||
|
opened_at = _utc(ot)
|
||||||
|
duration_min = random.randint(25, 50)
|
||||||
|
closed_at = opened_at + timedelta(minutes=duration_min)
|
||||||
|
if closed_at > close_time:
|
||||||
|
closed_at = close_time - timedelta(minutes=2)
|
||||||
|
|
||||||
|
online_type = random.choice(["delivery", "dine_in"])
|
||||||
|
online_names = ["Αλέξης Κ.", "Μαρία Π.", "Νίκος Σ.", "Αθηνά Λ.", "Θανάσης Β.", "Γιώτα Δ."]
|
||||||
|
online_phones = ["+30 694 111 0000", "+30 697 222 1111", "+30 693 333 2222",
|
||||||
|
"+30 699 444 3333", "+30 698 555 4444"]
|
||||||
|
o_name = random.choice(online_names)
|
||||||
|
o_phone = random.choice(online_phones)
|
||||||
|
o_status = random.choices(
|
||||||
|
["delivered", "delivered", "delivered", "rejected"],
|
||||||
|
weights=[0.85, 0.05, 0.05, 0.05]
|
||||||
|
)[0]
|
||||||
|
|
||||||
|
ref = f"ORD-{online_ref_counter:04d}"
|
||||||
|
online_ref_counter += 1
|
||||||
|
|
||||||
|
order = Order(
|
||||||
|
table_id=None,
|
||||||
|
opened_by=manager.id,
|
||||||
|
business_day_id=bday.id,
|
||||||
|
status="closed" if o_status == "delivered" else "cancelled",
|
||||||
|
closed_by=manager.id,
|
||||||
|
source="online",
|
||||||
|
online_order_ref=ref,
|
||||||
|
online_status=o_status,
|
||||||
|
online_customer_name=o_name,
|
||||||
|
online_customer_phone=o_phone,
|
||||||
|
online_order_type=online_type,
|
||||||
|
online_customer_notes=random.choice([None, None, "Χωρίς κρεμμύδι", "Γρήγορα παρακαλώ", None]),
|
||||||
|
order_type="delivery" if online_type == "delivery" else "here",
|
||||||
|
)
|
||||||
|
order.opened_at = opened_at
|
||||||
|
order.closed_at = closed_at
|
||||||
|
db.add(order)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
_audit(db, order.id, "ORDER_OPENED", waiter_id=manager.id, created_at=opened_at)
|
||||||
|
|
||||||
|
n_items = random.randint(1, 4)
|
||||||
|
chosen_category_lists = random.choices(category_product_map, weights=CATEGORY_WEIGHTS, k=n_items)
|
||||||
|
items_added = []
|
||||||
|
order_total = 0.0
|
||||||
|
items_added_at = opened_at + timedelta(minutes=2)
|
||||||
|
|
||||||
|
for prod_list in chosen_category_lists:
|
||||||
|
product = random.choice(prod_list)
|
||||||
|
qty = random.choices([1, 2], weights=[0.8, 0.2])[0]
|
||||||
|
line_total = product.base_price * qty
|
||||||
|
order_total += line_total
|
||||||
|
|
||||||
|
item = OrderItem(
|
||||||
|
order_id=order.id,
|
||||||
|
product_id=product.id,
|
||||||
|
added_by=manager.id,
|
||||||
|
quantity=qty,
|
||||||
|
unit_price=product.base_price,
|
||||||
|
unit_cost=product.cost_simple,
|
||||||
|
status="paid" if o_status == "delivered" else "cancelled",
|
||||||
|
printed=True,
|
||||||
|
paid_by=manager.id if o_status == "delivered" else None,
|
||||||
|
paid_at=_utc(closed_at) if o_status == "delivered" else None,
|
||||||
|
payment_method="card" if o_status == "delivered" else None,
|
||||||
|
)
|
||||||
|
item.added_at = _utc(items_added_at)
|
||||||
|
db.add(item)
|
||||||
|
db.flush()
|
||||||
|
items_added.append(item.id)
|
||||||
|
|
||||||
|
if o_status == "delivered":
|
||||||
|
_audit(db, order.id, "PAYMENT",
|
||||||
|
waiter_id=manager.id, item_ids=items_added,
|
||||||
|
amount=round(order_total, 2), payment_method="card",
|
||||||
|
created_at=closed_at - timedelta(minutes=1))
|
||||||
|
total_revenue += order_total
|
||||||
|
_audit(db, order.id, "ORDER_CLOSED", waiter_id=manager.id, created_at=closed_at)
|
||||||
|
total_orders += 1
|
||||||
|
|
||||||
|
# Write total_collected onto shifts
|
||||||
for w in working_waiters:
|
for w in working_waiters:
|
||||||
s = shifts[w.id]
|
s = shifts[w.id]
|
||||||
s.total_collected = shift_totals[s.id]
|
s.total_collected = shift_totals[s.id]
|
||||||
|
|
||||||
db.commit()
|
db.commit()
|
||||||
print(f" {day_date} {n_orders:2d} orders {len(working_waiters)} waiters")
|
print(f" {day_date} {n_orders:2d} orders {len(working_waiters)} waiters (dow={dow})")
|
||||||
|
|
||||||
|
# ── Expenses ──────────────────────────────────────────────────────────────
|
||||||
|
print("\nAdding expenses...")
|
||||||
|
|
||||||
|
supplier_meat = contacts[0]
|
||||||
|
supplier_fish = contacts[1]
|
||||||
|
supplier_olive = contacts[2]
|
||||||
|
supplier_bev = contacts[3]
|
||||||
|
util_power = contacts[4]
|
||||||
|
util_water = contacts[5]
|
||||||
|
util_phone = contacts[6]
|
||||||
|
|
||||||
|
def _add_expense(description, category, contact, amount, paid_amount,
|
||||||
|
days_back, notes=None):
|
||||||
|
exp_date = today - timedelta(days=days_back)
|
||||||
|
bday_obj = bday_by_date.get(exp_date)
|
||||||
|
due = _utc(datetime(exp_date.year, exp_date.month, exp_date.day, 9, 0))
|
||||||
|
exp = Expense(
|
||||||
|
description=description,
|
||||||
|
category=category,
|
||||||
|
contact_id=contact.id if contact else None,
|
||||||
|
total_amount=amount,
|
||||||
|
paid_amount=paid_amount,
|
||||||
|
due_date=due,
|
||||||
|
business_day_id=bday_obj.id if bday_obj else None,
|
||||||
|
created_by_id=manager.id,
|
||||||
|
notes=notes,
|
||||||
|
)
|
||||||
|
exp.created_at = due
|
||||||
|
db.add(exp)
|
||||||
|
db.flush()
|
||||||
|
if paid_amount > 0:
|
||||||
|
pmt = ExpensePayment(
|
||||||
|
expense_id=exp.id,
|
||||||
|
amount=paid_amount,
|
||||||
|
paid_by_id=manager.id,
|
||||||
|
notes=None,
|
||||||
|
)
|
||||||
|
pmt.paid_at = due + timedelta(hours=1)
|
||||||
|
db.add(pmt)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
# Recurring weekly: meat supplier (~every 5 days)
|
||||||
|
for i in range(0, DEMO_DAYS, 5):
|
||||||
|
_add_expense("Κρέας εβδομάδας", "supplier", supplier_meat,
|
||||||
|
round(random.uniform(180, 280), 2), 0,
|
||||||
|
DEMO_DAYS - i, "Παράδοση Δευτέρα πρωί")
|
||||||
|
|
||||||
|
# Recurring bi-weekly: fish
|
||||||
|
for i in range(0, DEMO_DAYS, 10):
|
||||||
|
_add_expense("Ψάρια & θαλασσινά", "supplier", supplier_fish,
|
||||||
|
round(random.uniform(90, 160), 2), 0,
|
||||||
|
DEMO_DAYS - i)
|
||||||
|
|
||||||
|
# Olive oil once a month
|
||||||
|
for i in range(0, DEMO_DAYS, 30):
|
||||||
|
_add_expense("Ελαιόλαδο & τυρί", "supplier", supplier_olive,
|
||||||
|
round(random.uniform(120, 200), 2), 0,
|
||||||
|
DEMO_DAYS - i)
|
||||||
|
|
||||||
|
# Beverages every 2 weeks
|
||||||
|
for i in range(0, DEMO_DAYS, 14):
|
||||||
|
amt = round(random.uniform(200, 350), 2)
|
||||||
|
_add_expense("Αναψυκτικά & μπύρες", "supplier", supplier_bev,
|
||||||
|
amt, amt, # fully paid
|
||||||
|
DEMO_DAYS - i)
|
||||||
|
|
||||||
|
# Monthly utility bills
|
||||||
|
for month_offset in range(4):
|
||||||
|
days_back = 30 * (month_offset + 1)
|
||||||
|
_add_expense("ΔΕΗ — μηνιαίος λογαριασμός", "utilities", util_power,
|
||||||
|
round(random.uniform(280, 420), 2), 0, days_back)
|
||||||
|
_add_expense("Νερό — μηνιαίος λογαριασμός", "utilities", util_water,
|
||||||
|
round(random.uniform(45, 90), 2), 0, days_back + 2)
|
||||||
|
_add_expense("Τηλεφωνία & Internet", "utilities", util_phone,
|
||||||
|
49.90, 49.90, days_back + 1)
|
||||||
|
|
||||||
|
# Rent once a month
|
||||||
|
for month_offset in range(4):
|
||||||
|
days_back = 30 * (month_offset + 1) - 5
|
||||||
|
_add_expense("Ενοίκιο καταστήματος", "rent", None,
|
||||||
|
1200.0, 1200.0, days_back,
|
||||||
|
"Πάντα στις αρχές του μήνα")
|
||||||
|
|
||||||
|
# One maintenance expense
|
||||||
|
_add_expense("Επισκευή ψυγείου", "maintenance", None,
|
||||||
|
320.0, 320.0, 45, "Συμπιεστής — Τεχνίτης Σωτήρης")
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
print(" expenses done")
|
||||||
|
|
||||||
|
# ── Tabs ──────────────────────────────────────────────────────────────────
|
||||||
|
print("Adding tabs...")
|
||||||
|
|
||||||
|
def _add_tab(customer, entries_desc, payments, is_closed=False):
|
||||||
|
"""entries_desc: list of (amount, description). payments: list of amounts."""
|
||||||
|
tab_opened = _utc(utcnow() - timedelta(days=random.randint(5, 30)))
|
||||||
|
tab = Tab(
|
||||||
|
customer_id=customer.id,
|
||||||
|
status="closed" if is_closed else "open",
|
||||||
|
opened_at=tab_opened,
|
||||||
|
closed_by_id=manager.id if is_closed else None,
|
||||||
|
closed_at=tab_opened + timedelta(days=random.randint(3, 15)) if is_closed else None,
|
||||||
|
notes=None,
|
||||||
|
)
|
||||||
|
db.add(tab)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
entry_time = tab_opened
|
||||||
|
for amount, desc in entries_desc:
|
||||||
|
entry_time += timedelta(days=random.randint(1, 3))
|
||||||
|
e = TabEntry(
|
||||||
|
tab_id=tab.id,
|
||||||
|
order_id=None,
|
||||||
|
order_item_id=None,
|
||||||
|
amount=amount,
|
||||||
|
description=desc,
|
||||||
|
created_by_id=manager.id,
|
||||||
|
)
|
||||||
|
e.created_at = entry_time
|
||||||
|
db.add(e)
|
||||||
|
|
||||||
|
pay_time = entry_time + timedelta(days=1)
|
||||||
|
for pay_amount in payments:
|
||||||
|
pay_time += timedelta(hours=random.randint(1, 24))
|
||||||
|
p = TabPayment(
|
||||||
|
tab_id=tab.id,
|
||||||
|
amount=pay_amount,
|
||||||
|
payment_method=random.choice(["cash", "card"]),
|
||||||
|
received_by_id=manager.id,
|
||||||
|
notes=None,
|
||||||
|
)
|
||||||
|
p.created_at = pay_time
|
||||||
|
db.add(p)
|
||||||
|
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
# Open tab: Γιώργης hasn't settled his tab yet
|
||||||
|
_add_tab(customers[0], [
|
||||||
|
(35.50, "Δείπνο 3 ατόμων — 15/05"),
|
||||||
|
(28.00, "Μεσημεριανό — 22/05"),
|
||||||
|
(42.00, "Δείπνο 4 ατόμων — 28/05"),
|
||||||
|
], [20.00]) # partial payment
|
||||||
|
|
||||||
|
# Closed tab: Σοφία settled hers
|
||||||
|
_add_tab(customers[3], [
|
||||||
|
(55.00, "Εταιρικό δείπνο — 10/04"),
|
||||||
|
(30.00, "Μεσημεριανό — 18/04"),
|
||||||
|
], [85.00], is_closed=True)
|
||||||
|
|
||||||
|
# Open tab: Ομάδα εργατών — running tab
|
||||||
|
_add_tab(customers[4], [
|
||||||
|
(22.00, "Μεσημεριανό ομάδα — 01/06"),
|
||||||
|
(25.50, "Μεσημεριανό ομάδα — 05/06"),
|
||||||
|
(19.00, "Μεσημεριανό ομάδα — 09/06"),
|
||||||
|
], [30.00])
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
print(" tabs done")
|
||||||
|
|
||||||
|
# ── Site Notes & Todos ────────────────────────────────────────────────────
|
||||||
|
print("Adding notes & todos...")
|
||||||
|
|
||||||
|
notes_data = [
|
||||||
|
("Ο φούρνος χρειάζεται σέρβις — να κλείσουμε ραντεβού με τεχνίτη.", True),
|
||||||
|
("Νέα τιμή μπύρας από 1 Ιουλίου: Heineken 4.50€ (από 4.00€).", False),
|
||||||
|
("Παραγγελία ελαιολάδου: 10 κιλά εξαιρετικό παρθένο από Αλεξόπουλο.", False),
|
||||||
|
("ΔΕΗ: η επόμενη πληρωμή λήγει στις 20 Ιουλίου. Να μην ξεχαστεί!", True),
|
||||||
|
("Το κλιματιστικό βεράντας λειτουργεί πάλι μετά την επισκευή (Παρ. 07/06).", False),
|
||||||
|
]
|
||||||
|
for body, pinned in notes_data:
|
||||||
|
note = SiteNote(
|
||||||
|
body=body,
|
||||||
|
created_by_id=manager.id,
|
||||||
|
is_pinned=pinned,
|
||||||
|
)
|
||||||
|
db.add(note)
|
||||||
|
|
||||||
|
todos_data = [
|
||||||
|
("Ανανέωση τιμοκαταλόγου για καλοκαίρι", "high", False),
|
||||||
|
("Αγορά νέων ποτηριών κρασιού (χάλασαν 4)", "normal", False),
|
||||||
|
("Έλεγχος πυροσβεστήρων — Ιούλιος", "high", False),
|
||||||
|
("Εκπαίδευση νέου σερβιτόρου στο σύστημα", "normal", False),
|
||||||
|
("Ανανέωση άδειας λειτουργίας", "high", False),
|
||||||
|
("Παραγγελία νέων χαρτοπετσετών και υλικών bar", "normal", True),
|
||||||
|
("Φωτογράφιση νέων πιάτων για online menu", "normal", False),
|
||||||
|
]
|
||||||
|
for body, priority, is_done in todos_data:
|
||||||
|
todo = SiteTodo(
|
||||||
|
body=body,
|
||||||
|
priority=priority,
|
||||||
|
is_done=is_done,
|
||||||
|
created_by_id=manager.id,
|
||||||
|
done_by_id=manager.id if is_done else None,
|
||||||
|
done_at=_utc(utcnow() - timedelta(days=2)) if is_done else None,
|
||||||
|
)
|
||||||
|
db.add(todo)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
print(" notes & todos done")
|
||||||
|
|
||||||
|
# ── Schedule (next 3 weeks) ───────────────────────────────────────────────
|
||||||
|
print("Adding schedule for next 3 weeks...")
|
||||||
|
|
||||||
|
# Each waiter works 5 days out of 7, with realistic shift patterns
|
||||||
|
# Mon-Fri: full shifts, Sat: both sessions, Sun: afternoon/evening only
|
||||||
|
shift_patterns = {
|
||||||
|
0: [("10:00", "16:00"), ("16:00", "23:30")], # Mon — two shifts
|
||||||
|
1: [("10:00", "16:00"), ("16:00", "23:30")], # Tue
|
||||||
|
2: [("10:00", "16:00"), ("16:00", "23:30")], # Wed
|
||||||
|
3: [("10:00", "16:00"), ("16:00", "23:30")], # Thu
|
||||||
|
4: [("10:00", "17:00"), ("17:00", "23:30")], # Fri
|
||||||
|
5: [("10:00", "16:00"), ("16:00", "23:30")], # Sat — busy day
|
||||||
|
6: [("11:00", "16:00"), ("16:00", "23:00")], # Sun
|
||||||
|
}
|
||||||
|
|
||||||
|
# Assign waiters to shifts: each day, 2 waiters per slot
|
||||||
|
for weeks_ahead in range(3):
|
||||||
|
for day_offset in range(7):
|
||||||
|
sched_date = today + timedelta(weeks=weeks_ahead, days=day_offset)
|
||||||
|
dow = sched_date.weekday()
|
||||||
|
day_patterns = shift_patterns[dow]
|
||||||
|
|
||||||
|
# Shuffle waiters and assign 2 per slot
|
||||||
|
waiter_pool = waiters[:]
|
||||||
|
random.shuffle(waiter_pool)
|
||||||
|
for slot_idx, (start_t, end_t) in enumerate(day_patterns):
|
||||||
|
# Pick 2 waiters per slot (rotate through pool)
|
||||||
|
slot_waiters = [waiter_pool[slot_idx % len(waiter_pool)],
|
||||||
|
waiter_pool[(slot_idx + 1) % len(waiter_pool)]]
|
||||||
|
for w in slot_waiters:
|
||||||
|
# Don't double-schedule same waiter on same day
|
||||||
|
already = db.query(ScheduledShift).filter(
|
||||||
|
ScheduledShift.user_id == w.id,
|
||||||
|
ScheduledShift.scheduled_date == sched_date,
|
||||||
|
).first()
|
||||||
|
if not already:
|
||||||
|
sched = ScheduledShift(
|
||||||
|
user_id=w.id,
|
||||||
|
scheduled_date=sched_date,
|
||||||
|
start_time=start_t,
|
||||||
|
end_time=end_t,
|
||||||
|
notes=None,
|
||||||
|
created_by_id=manager.id,
|
||||||
|
)
|
||||||
|
db.add(sched)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
print(" schedule done")
|
||||||
|
|
||||||
print(f"\nDone.")
|
print(f"\nDone.")
|
||||||
print(f" Total orders : {total_orders}")
|
print(f" Total orders : {total_orders}")
|
||||||
@@ -424,7 +884,7 @@ try:
|
|||||||
print(f"\nLogin credentials:")
|
print(f"\nLogin credentials:")
|
||||||
print(f" Manager — username: manager | password: password | PIN: 1234")
|
print(f" Manager — username: manager | password: password | PIN: 1234")
|
||||||
for w in waiters:
|
for w in waiters:
|
||||||
print(f" Waiter — username: {w.username}")
|
print(f" Waiter — username: {w.username} | nickname: {w.nickname}")
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
db.close()
|
db.close()
|
||||||
|
|||||||
+121
-440
@@ -1,478 +1,159 @@
|
|||||||
|
"""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 os
|
||||||
|
import logging
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
from database import engine, Base
|
from core.logging import setup_logging, apply_retention_setting, RequestContextMiddleware
|
||||||
from middleware.license_check import LicenseCheckMiddleware
|
|
||||||
|
# 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
|
from services.cloud_sync import start_cloud_sync
|
||||||
|
|
||||||
# Import all models so SQLAlchemy can create their tables
|
# Every model must be registered before the routers import them (see models/all.py).
|
||||||
import models.user # noqa: F401 — also registers WaiterZone
|
import models.all # noqa: F401
|
||||||
import models.table # noqa: F401
|
|
||||||
import models.printer # noqa: F401
|
|
||||||
import models.product # noqa: F401
|
|
||||||
import models.order # noqa: F401 — also registers OrderAuditLog, OrderDiscount
|
|
||||||
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
|
|
||||||
|
|
||||||
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 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
|
|
||||||
|
|
||||||
|
|
||||||
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 = [
|
def _init_chat():
|
||||||
"ALTER TABLE product_ingredients ADD COLUMN extra_cost REAL NOT NULL DEFAULT 0.0",
|
"""Bootstrap the system group chat and sync all active users into it."""
|
||||||
"ALTER TABLE products ADD COLUMN image_url VARCHAR",
|
from services.chat_service import ensure_system_group, add_user_to_system_group
|
||||||
"ALTER TABLE tables ADD COLUMN group_id INTEGER REFERENCES table_groups(id)",
|
from models.user import User
|
||||||
"ALTER TABLE table_groups ADD COLUMN prefix VARCHAR",
|
from database import SessionLocal
|
||||||
"ALTER TABLE table_groups ADD COLUMN color VARCHAR",
|
db = SessionLocal()
|
||||||
"ALTER TABLE products ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0",
|
try:
|
||||||
"ALTER TABLE product_preference_sets ADD COLUMN default_choice_id INTEGER",
|
ensure_system_group(db)
|
||||||
"ALTER TABLE product_preference_choices ADD COLUMN sub_choices TEXT",
|
active_users = db.query(User).filter(User.is_active == True).all() # noqa: E712
|
||||||
"ALTER TABLE product_preference_choices ADD COLUMN disables_subset INTEGER NOT NULL DEFAULT 0",
|
for u in active_users:
|
||||||
"ALTER TABLE product_preference_sets ADD COLUMN shared_subset TEXT",
|
add_user_to_system_group(db, u.id)
|
||||||
"ALTER TABLE product_options ADD COLUMN sub_choices TEXT",
|
finally:
|
||||||
# Zone-based access control
|
db.close()
|
||||||
"""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
|
|
||||||
)""",
|
|
||||||
# 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'
|
|
||||||
)""",
|
|
||||||
]
|
|
||||||
for sql in migrations:
|
|
||||||
try:
|
|
||||||
with engine.connect() as conn:
|
|
||||||
conn.execute(text(sql))
|
|
||||||
conn.commit()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
import asyncio
|
import asyncio
|
||||||
from services.sse_bus import 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.reservation_tasks import start_reservation_tasks
|
||||||
init_loop(asyncio.get_running_loop())
|
from services.printer_service import start_print_retry_thread
|
||||||
Base.metadata.create_all(bind=engine)
|
loop = asyncio.get_running_loop()
|
||||||
_run_migrations()
|
ws_init_loop(loop)
|
||||||
sync_task = await start_cloud_sync()
|
# 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)
|
||||||
|
from services.media import import_builtin
|
||||||
|
try:
|
||||||
|
import_builtin(_db) # pictures shipped with the server (5.4a)
|
||||||
|
except Exception as e: # never blocks the start
|
||||||
|
logger.warning("built-in pictures not imported: %s", e)
|
||||||
|
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()
|
||||||
|
from services.video import start_worker as start_video_worker
|
||||||
|
start_video_worker() # videos' still frames and playable versions (5.4e)
|
||||||
|
pruned = prune_old_events(hours=24)
|
||||||
|
if pruned:
|
||||||
|
logger.info("ws_bus: pruned %d old sync_events", pruned)
|
||||||
|
_init_chat()
|
||||||
|
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()
|
reservation_task = await start_reservation_tasks()
|
||||||
|
from services import day_auto
|
||||||
|
day_task = await day_auto.start() # the day opens / closes by itself (6F.8)
|
||||||
yield
|
yield
|
||||||
|
day_task.cancel()
|
||||||
|
supervisor.stop_all()
|
||||||
sync_task.cancel()
|
sync_task.cancel()
|
||||||
reservation_task.cancel()
|
reservation_task.cancel()
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(title="POS Local Backend", lifespan=lifespan)
|
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(
|
app.add_middleware(
|
||||||
CORSMiddleware,
|
CORSMiddleware,
|
||||||
allow_origins=["*"],
|
allow_origins=["*"],
|
||||||
allow_methods=["*"],
|
allow_methods=["*"],
|
||||||
allow_headers=["*"],
|
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"
|
@app.middleware("http")
|
||||||
os.makedirs(IMAGE_DIR, exist_ok=True)
|
async def _menu_change_push(request, call_next):
|
||||||
app.mount("/static/product_images", StaticFiles(directory=IMAGE_DIR), name="product_images")
|
"""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()
|
||||||
|
from starlette.concurrency import run_in_threadpool
|
||||||
|
await run_in_threadpool(_signage_menu_changed)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
def _signage_menu_changed() -> None:
|
||||||
|
"""The signage screens showing a menu board (5.4b) and the menu tablets (5.7a) read their menu again."""
|
||||||
|
try:
|
||||||
|
from routers.menu_tablet import menu_changed as tablet_menu_changed
|
||||||
|
from routers.signage import menu_changed as signage_menu_changed
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
signage_menu_changed(db)
|
||||||
|
tablet_menu_changed(db) # the menu tablets read their menu again (5.7a)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
except Exception as e: # never breaks the request that changed the menu
|
||||||
|
logger.warning("signage: menu change not sent: %s", e)
|
||||||
|
|
||||||
|
|
||||||
|
# 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
|
# Serve waiter avatars as static files
|
||||||
AVATAR_DIR = "/app/data/avatars"
|
AVATAR_DIR = "/app/data/avatars"
|
||||||
os.makedirs(AVATAR_DIR, exist_ok=True)
|
os.makedirs(AVATAR_DIR, exist_ok=True)
|
||||||
app.mount("/static/avatars", StaticFiles(directory=AVATAR_DIR), name="avatars")
|
app.mount("/static/avatars", StaticFiles(directory=AVATAR_DIR), name="avatars")
|
||||||
|
|
||||||
app.include_router(setup_router.router, prefix="/api/setup", tags=["setup"])
|
# Routers come from the module manifests (modules/<key>/manifest.py, APPS_PLATFORM D-19).
|
||||||
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
|
# All are always mounted; non-core ones answer `module.disabled` while their module is off.
|
||||||
app.include_router(tables.router, prefix="/api/tables", tags=["tables"])
|
def _mount_module_routers(app: FastAPI) -> None:
|
||||||
app.include_router(products.router, prefix="/api/products", tags=["products"])
|
import importlib
|
||||||
app.include_router(orders.router, prefix="/api/orders", tags=["orders"])
|
from fastapi import Depends
|
||||||
app.include_router(waiters.router, prefix="/api/waiters", tags=["waiters"])
|
from core.modules.registry import registry
|
||||||
app.include_router(reports.router, prefix="/api/reports", tags=["reports"])
|
from core.modules.state import module_required
|
||||||
app.include_router(system.router, prefix="/api/system", tags=["system"])
|
for m in registry().values():
|
||||||
app.include_router(business_day_router.router, prefix="/api/business-day", tags=["business-day"])
|
deps = [] if m.kind == "core" else [Depends(module_required(m.key))]
|
||||||
app.include_router(shifts_router.router, prefix="/api/shifts", tags=["shifts"])
|
for mt in m.routers:
|
||||||
app.include_router(settings_router.router, prefix="/api/settings", tags=["settings"])
|
r = getattr(importlib.import_module(mt.module), mt.attr)
|
||||||
app.include_router(flags_router.router, prefix="/api/flags", tags=["flags"])
|
app.include_router(r, prefix=mt.prefix, tags=list(mt.tags) or [m.key], dependencies=deps)
|
||||||
app.include_router(messages_router.router, prefix="/api/messages", tags=["messages"])
|
|
||||||
app.include_router(sse_router.router, prefix="/api/sse", tags=["sse"])
|
|
||||||
app.include_router(data_transfer_router.router, prefix="/api/data-transfer", tags=["data-transfer"])
|
_mount_module_routers(app)
|
||||||
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"])
|
|
||||||
|
|||||||
@@ -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)
|
|
||||||
EXEMPT_PATHS = {"/api/system/health"}
|
|
||||||
|
|
||||||
# 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)
|
|
||||||
@@ -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()
|
||||||
@@ -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')
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""Signage playlists and slides (plan step 5.4a); media.builtin for pictures shipped with the server.
|
||||||
|
|
||||||
|
Revision ID: 0029_signage
|
||||||
|
Revises: 0028_display_looks
|
||||||
|
Create Date: 2026-11-17 20:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0029_signage'
|
||||||
|
down_revision = '0028_display_looks'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table('signage_playlists',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('orientation', sa.String(), nullable=False),
|
||||||
|
sa.Column('transition', sa.String(), nullable=False),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('updated_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('signage_playlists', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_signage_playlists_id'), ['id'], unique=False)
|
||||||
|
|
||||||
|
op.create_table('signage_slides',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('playlist_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('position', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('kind', sa.String(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=True),
|
||||||
|
sa.Column('duration_s', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('transition', sa.String(), nullable=True),
|
||||||
|
sa.Column('video_to_end', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('enabled', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('days', sa.JSON(), nullable=True),
|
||||||
|
sa.Column('time_from', sa.String(), nullable=True),
|
||||||
|
sa.Column('time_to', sa.String(), nullable=True),
|
||||||
|
sa.Column('date_from', sa.String(), nullable=True),
|
||||||
|
sa.Column('date_to', sa.String(), nullable=True),
|
||||||
|
sa.Column('content', sa.JSON(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['playlist_id'], ['signage_playlists.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('signage_slides', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_signage_slides_id'), ['id'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_signage_slides_playlist_id'), ['playlist_id'], unique=False)
|
||||||
|
|
||||||
|
with op.batch_alter_table('media', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('builtin', sa.Boolean(), server_default='0', nullable=False))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('media', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('builtin')
|
||||||
|
|
||||||
|
with op.batch_alter_table('signage_slides', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_signage_slides_playlist_id'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_signage_slides_id'))
|
||||||
|
|
||||||
|
op.drop_table('signage_slides')
|
||||||
|
with op.batch_alter_table('signage_playlists', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_signage_playlists_id'))
|
||||||
|
|
||||||
|
op.drop_table('signage_playlists')
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Signage schedules (plan step 5.4d): which playlist a screen plays when.
|
||||||
|
|
||||||
|
Revision ID: 0030_signage_schedules
|
||||||
|
Revises: 0029_signage
|
||||||
|
Create Date: 2026-11-17 21:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0030_signage_schedules'
|
||||||
|
down_revision = '0029_signage'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table('signage_schedules',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('fallback_playlist_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('entries', sa.JSON(), nullable=False),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('updated_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['fallback_playlist_id'], ['signage_playlists.id'], ondelete='SET NULL'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('signage_schedules', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_signage_schedules_id'), ['id'], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('signage_schedules', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_signage_schedules_id'))
|
||||||
|
|
||||||
|
op.drop_table('signage_schedules')
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Video versions (plan step 5.4e): a video's still frame and a version every screen plays are
|
||||||
|
made in the background after the upload; the library shows how far it got.
|
||||||
|
|
||||||
|
Videos already in the library are queued (`waiting`) so they get theirs too.
|
||||||
|
|
||||||
|
Revision ID: 0031_video_versions
|
||||||
|
Revises: 0030_signage_schedules
|
||||||
|
Create Date: 2026-11-18 09:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0031_video_versions'
|
||||||
|
down_revision = '0030_signage_schedules'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('media', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('processing', sa.String(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('progress', sa.Integer(), nullable=True))
|
||||||
|
op.execute("UPDATE media SET processing = 'waiting' WHERE kind = 'video'")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('media', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('progress')
|
||||||
|
batch_op.drop_column('processing')
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""Allergens (plan step 6.3): the 14 EU allergens per product, each "contains" or
|
||||||
|
"may contain" (core/allergens.py), as JSON {key: level}; null = none declared.
|
||||||
|
|
||||||
|
Revision ID: 0032_product_allergens
|
||||||
|
Revises: 0031_video_versions
|
||||||
|
Create Date: 2026-11-18 12:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0032_product_allergens'
|
||||||
|
down_revision = '0031_video_versions'
|
||||||
|
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('allergens', sa.Text(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('products', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('allergens')
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""The menu in other languages (plan step 6.4, core/menu_languages.py): a product's and a
|
||||||
|
category's translations as JSON {language: {field: text}}; null = none.
|
||||||
|
|
||||||
|
Revision ID: 0033_menu_translations
|
||||||
|
Revises: 0032_product_allergens
|
||||||
|
Create Date: 2026-11-18 15:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0033_menu_translations'
|
||||||
|
down_revision = '0032_product_allergens'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
for table in ('products', 'categories'):
|
||||||
|
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('translations', sa.Text(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for table in ('products', 'categories'):
|
||||||
|
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('translations')
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Orders from a menu tablet at a table (plan step 6.6, D-30, models/tablet_order.py).
|
||||||
|
|
||||||
|
Revision ID: 0034_tablet_orders
|
||||||
|
Revises: 0033_menu_translations
|
||||||
|
Create Date: 2026-11-18 16:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0034_tablet_orders'
|
||||||
|
down_revision = '0033_menu_translations'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
'tablet_orders',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('device_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('table_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('lines', sa.JSON(), nullable=False),
|
||||||
|
sa.Column('note', sa.Text(), nullable=True),
|
||||||
|
sa.Column('total', sa.Float(), nullable=False),
|
||||||
|
sa.Column('status', sa.String(), nullable=False),
|
||||||
|
sa.Column('order_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('reason', sa.String(), nullable=True),
|
||||||
|
sa.Column('decided_by_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('decided_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['decided_by_id'], ['users.id'], ondelete='SET NULL'),
|
||||||
|
sa.ForeignKeyConstraint(['device_id'], ['devices.id'], ondelete='SET NULL'),
|
||||||
|
sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ondelete='SET NULL'),
|
||||||
|
sa.ForeignKeyConstraint(['table_id'], ['tables.id'], ondelete='SET NULL'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('tablet_orders', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_tablet_orders_created_at'), ['created_at'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_tablet_orders_device_id'), ['device_id'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_tablet_orders_id'), ['id'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_tablet_orders_status'), ['status'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_tablet_orders_table_id'), ['table_id'], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table('tablet_orders')
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"""Floor plans, their walls / bar / labels / areas, and the tables' place on a plan
|
||||||
|
(plan step 6.8, D-31, models/floor_plan.py). Existing tables stay off any plan.
|
||||||
|
|
||||||
|
Revision ID: 0035_floor_plans
|
||||||
|
Revises: 0034_tablet_orders
|
||||||
|
Create Date: 2026-11-18 16:05:26
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0035_floor_plans'
|
||||||
|
down_revision = '0034_tablet_orders'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
'floor_plans',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('group_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('width', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('height', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('outline', sa.JSON(), nullable=True),
|
||||||
|
sa.Column('grid_on', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('grid_size', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('media_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('background_opacity', sa.Float(), nullable=False),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['group_id'], ['table_groups.id'], ondelete='SET NULL'),
|
||||||
|
sa.ForeignKeyConstraint(['media_id'], ['media.id'], ondelete='SET NULL'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('floor_plans', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_floor_plans_group_id'), ['group_id'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_floor_plans_id'), ['id'], unique=False)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
'floor_items',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('plan_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('kind', sa.String(), nullable=False),
|
||||||
|
sa.Column('x', sa.Float(), nullable=False),
|
||||||
|
sa.Column('y', sa.Float(), nullable=False),
|
||||||
|
sa.Column('width', sa.Float(), nullable=False),
|
||||||
|
sa.Column('height', sa.Float(), nullable=False),
|
||||||
|
sa.Column('rotation', sa.Float(), nullable=False),
|
||||||
|
sa.Column('text', sa.String(), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['plan_id'], ['floor_plans.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
with op.batch_alter_table('floor_items', schema=None) as batch_op:
|
||||||
|
batch_op.create_index(batch_op.f('ix_floor_items_id'), ['id'], unique=False)
|
||||||
|
batch_op.create_index(batch_op.f('ix_floor_items_plan_id'), ['plan_id'], unique=False)
|
||||||
|
|
||||||
|
with op.batch_alter_table('tables', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('plan_id', sa.Integer(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('width', sa.Float(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('height', sa.Float(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('rotation', sa.Float(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('shape', sa.String(), nullable=True))
|
||||||
|
batch_op.create_index(batch_op.f('ix_tables_plan_id'), ['plan_id'], unique=False)
|
||||||
|
batch_op.create_foreign_key('fk_tables_plan_id_floor_plans', 'floor_plans', ['plan_id'], ['id'], ondelete='SET NULL')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('tables', schema=None) as batch_op:
|
||||||
|
batch_op.drop_constraint('fk_tables_plan_id_floor_plans', type_='foreignkey')
|
||||||
|
batch_op.drop_index(batch_op.f('ix_tables_plan_id'))
|
||||||
|
batch_op.drop_column('shape')
|
||||||
|
batch_op.drop_column('rotation')
|
||||||
|
batch_op.drop_column('height')
|
||||||
|
batch_op.drop_column('width')
|
||||||
|
batch_op.drop_column('plan_id')
|
||||||
|
with op.batch_alter_table('floor_items', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_floor_items_plan_id'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_floor_items_id'))
|
||||||
|
op.drop_table('floor_items')
|
||||||
|
with op.batch_alter_table('floor_plans', schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f('ix_floor_plans_id'))
|
||||||
|
batch_op.drop_index(batch_op.f('ix_floor_plans_group_id'))
|
||||||
|
op.drop_table('floor_plans')
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""A print job's way out besides printing (plan step 6.10): who resolved it and, when the
|
||||||
|
ticket was sent to another printer, which one. `status` gains no new value: a ticket sent
|
||||||
|
elsewhere ends as 'success' (redirected_to set), one marked as handled as 'cancelled' with
|
||||||
|
cancel_reason 'handled'.
|
||||||
|
|
||||||
|
Revision ID: 0036_print_job_resolution
|
||||||
|
Revises: 0035_floor_plans
|
||||||
|
Create Date: 2026-11-19 09:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0036_print_job_resolution'
|
||||||
|
down_revision = '0035_floor_plans'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('print_jobs', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('resolved_by', sa.Integer(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('redirected_to', sa.Integer(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('print_jobs', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('redirected_to')
|
||||||
|
batch_op.drop_column('resolved_by')
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Tabs in the books (plan step 6.13c, KI-018): a line put on a tab and a payment on a tab
|
||||||
|
record the business day and the shift they happened in (the shift of whoever did it, if they
|
||||||
|
were on one), so a shift shows what it put on tabs and the tab money it received, and the
|
||||||
|
day shows both. Existing rows get their business day from when they happened.
|
||||||
|
|
||||||
|
Revision ID: 0037_tab_books
|
||||||
|
Revises: 0036_print_job_resolution
|
||||||
|
Create Date: 2026-11-19 12:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0037_tab_books'
|
||||||
|
down_revision = '0036_print_job_resolution'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
TABLES = ('tab_entries', 'tab_payments')
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
for t in TABLES:
|
||||||
|
with op.batch_alter_table(t, schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('business_day_id', sa.Integer(), nullable=True))
|
||||||
|
batch_op.add_column(sa.Column('shift_id', sa.Integer(), nullable=True))
|
||||||
|
batch_op.create_index(f'ix_{t}_business_day_id', ['business_day_id'])
|
||||||
|
batch_op.create_index(f'ix_{t}_shift_id', ['shift_id'])
|
||||||
|
batch_op.create_foreign_key(f'fk_{t}_business_day_id_business_days', 'business_days', ['business_day_id'], ['id'])
|
||||||
|
batch_op.create_foreign_key(f'fk_{t}_shift_id_waiter_shifts', 'waiter_shifts', ['shift_id'], ['id'])
|
||||||
|
# the day each existing row happened in (a closed day's window, or the open one)
|
||||||
|
op.execute(f"""
|
||||||
|
UPDATE {t} SET business_day_id = (
|
||||||
|
SELECT d.id FROM business_days d
|
||||||
|
WHERE d.opened_at <= {t}.created_at AND (d.closed_at IS NULL OR d.closed_at >= {t}.created_at)
|
||||||
|
ORDER BY d.opened_at DESC LIMIT 1)
|
||||||
|
""")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for t in TABLES:
|
||||||
|
with op.batch_alter_table(t, schema=None) as batch_op:
|
||||||
|
batch_op.drop_constraint(f'fk_{t}_shift_id_waiter_shifts', type_='foreignkey')
|
||||||
|
batch_op.drop_constraint(f'fk_{t}_business_day_id_business_days', type_='foreignkey')
|
||||||
|
batch_op.drop_index(f'ix_{t}_shift_id')
|
||||||
|
batch_op.drop_index(f'ix_{t}_business_day_id')
|
||||||
|
batch_op.drop_column('shift_id')
|
||||||
|
batch_op.drop_column('business_day_id')
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
"""Indexes on the columns the screens look rows up by (UI review 2026-11-20).
|
||||||
|
|
||||||
|
The order lines had no index on their order, the orders none on their day or customer, and so
|
||||||
|
on: every report and the customers list read whole tables once per order, so a few thousand
|
||||||
|
orders made Customers take ~2 s and Reports → Days ~15 s (and time out). One index per column
|
||||||
|
below; the models carry index=True so new databases get them too.
|
||||||
|
|
||||||
|
Revision ID: 0038_lookup_indexes
|
||||||
|
Revises: 0037_tab_books
|
||||||
|
Create Date: 2026-11-20 15:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0038_lookup_indexes'
|
||||||
|
down_revision = '0037_tab_books'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
INDEXES = [
|
||||||
|
('orders', 'table_id'),
|
||||||
|
('orders', 'business_day_id'),
|
||||||
|
('orders', 'customer_id'),
|
||||||
|
('orders', 'status'),
|
||||||
|
('orders', 'opened_at'),
|
||||||
|
('order_items', 'order_id'),
|
||||||
|
('order_items', 'product_id'),
|
||||||
|
('order_items', 'paid_in_shift_id'),
|
||||||
|
('order_items', 'status'),
|
||||||
|
('order_waiters', 'order_id'),
|
||||||
|
('order_waiters', 'waiter_id'),
|
||||||
|
('order_audit_log', 'order_id'),
|
||||||
|
('order_discounts', 'order_id'),
|
||||||
|
('print_jobs', 'order_id'),
|
||||||
|
('print_log', 'order_id'),
|
||||||
|
('waiter_shifts', 'waiter_id'),
|
||||||
|
('waiter_shifts', 'business_day_id'),
|
||||||
|
('tab_entries', 'tab_id'),
|
||||||
|
('tab_entries', 'order_id'),
|
||||||
|
('tab_entries', 'order_item_id'),
|
||||||
|
('tab_payments', 'tab_id'),
|
||||||
|
('tabs', 'customer_id'),
|
||||||
|
('expenses', 'business_day_id'),
|
||||||
|
('expenses', 'contact_id'),
|
||||||
|
('expense_payments', 'expense_id'),
|
||||||
|
('reservations', 'order_id'),
|
||||||
|
('reservations', 'table_id'),
|
||||||
|
('phone_calls', 'customer_id'),
|
||||||
|
('waste_log', 'business_day_id'),
|
||||||
|
('waste_log', 'product_id'),
|
||||||
|
('tables', 'group_id'),
|
||||||
|
('scheduled_shifts', 'user_id'),
|
||||||
|
('shift_breaks', 'shift_id'),
|
||||||
|
('chat_messages', 'conversation_id'),
|
||||||
|
('conversation_participants', 'conversation_id'),
|
||||||
|
('conversation_participants', 'user_id'),
|
||||||
|
('staff_message_acks', 'message_id'),
|
||||||
|
('price_modifier_conditions', 'modifier_id'),
|
||||||
|
('price_modifier_targets', 'modifier_id'),
|
||||||
|
('deal_conditions', 'deal_id'),
|
||||||
|
('deal_targets', 'deal_id'),
|
||||||
|
('product_ingredients', 'product_id'),
|
||||||
|
('product_modifier_groups', 'product_id'),
|
||||||
|
('product_options', 'product_id'),
|
||||||
|
('product_preference_sets', 'product_id'),
|
||||||
|
('product_preference_choices', 'set_id'),
|
||||||
|
('product_quick_options', 'product_id'),
|
||||||
|
('tablet_orders', 'order_id'),
|
||||||
|
]
|
||||||
|
|
||||||
|
# what a person did in a time window (a shift's orders and lines)
|
||||||
|
PAIRS = [
|
||||||
|
('orders', ('opened_by', 'opened_at')),
|
||||||
|
('order_items', ('added_by', 'added_at')),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _existing(table: str) -> set[str]:
|
||||||
|
return {ix['name'] for ix in sa.inspect(op.get_bind()).get_indexes(table)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
for table, column in INDEXES:
|
||||||
|
name = f'ix_{table}_{column}'
|
||||||
|
if name not in _existing(table):
|
||||||
|
op.create_index(name, table, [column])
|
||||||
|
for table, columns in PAIRS:
|
||||||
|
name = f'ix_{table}_{"_".join(columns)}'
|
||||||
|
if name not in _existing(table):
|
||||||
|
op.create_index(name, table, list(columns))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for table, columns in PAIRS:
|
||||||
|
name = f'ix_{table}_{"_".join(columns)}'
|
||||||
|
if name in _existing(table):
|
||||||
|
op.drop_index(name, table_name=table)
|
||||||
|
for table, column in reversed(INDEXES):
|
||||||
|
name = f'ix_{table}_{column}'
|
||||||
|
if name in _existing(table):
|
||||||
|
op.drop_index(name, table_name=table)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Expense lines and documents (UI review 2026-11-20): what an expense bought (quantity, price
|
||||||
|
before VAT, VAT rate; the lines make the total) and the files kept with it (the invoice as a
|
||||||
|
PDF, a photo of the receipt).
|
||||||
|
|
||||||
|
Revision ID: 0039_expense_lines_documents
|
||||||
|
Revises: 0038_lookup_indexes
|
||||||
|
Create Date: 2026-11-20 16:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0039_expense_lines_documents'
|
||||||
|
down_revision = '0038_lookup_indexes'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
'expense_lines',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('expense_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('position', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('description', sa.String(), nullable=False),
|
||||||
|
sa.Column('quantity', sa.Float(), nullable=False),
|
||||||
|
sa.Column('unit_price', sa.Float(), nullable=False),
|
||||||
|
sa.Column('vat_rate', sa.Float(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['expense_id'], ['expenses.id']),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
op.create_index('ix_expense_lines_id', 'expense_lines', ['id'])
|
||||||
|
op.create_index('ix_expense_lines_expense_id', 'expense_lines', ['expense_id'])
|
||||||
|
op.create_table(
|
||||||
|
'expense_documents',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('expense_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('filename', sa.String(), nullable=False),
|
||||||
|
sa.Column('stored_name', sa.String(), nullable=False),
|
||||||
|
sa.Column('content_type', sa.String(), nullable=False),
|
||||||
|
sa.Column('size', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('uploaded_by_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('uploaded_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['expense_id'], ['expenses.id']),
|
||||||
|
sa.ForeignKeyConstraint(['uploaded_by_id'], ['users.id']),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
op.create_index('ix_expense_documents_id', 'expense_documents', ['id'])
|
||||||
|
op.create_index('ix_expense_documents_expense_id', 'expense_documents', ['expense_id'])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table('expense_documents')
|
||||||
|
op.drop_table('expense_lines')
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""Order channel prices (UI review 2026-11-20): a product's price at a sales point, set per
|
||||||
|
product, per category or for the whole channel (services/channel_prices.py).
|
||||||
|
|
||||||
|
Revision ID: 0040_channel_prices
|
||||||
|
Revises: 0039_expense_lines_documents
|
||||||
|
Create Date: 2026-11-20 17:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0040_channel_prices'
|
||||||
|
down_revision = '0039_expense_lines_documents'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
'channel_prices',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=True),
|
||||||
|
sa.Column('sales_points', sa.Text(), nullable=False),
|
||||||
|
sa.Column('product_ids', sa.Text(), nullable=False),
|
||||||
|
sa.Column('category_ids', sa.Text(), nullable=False),
|
||||||
|
sa.Column('action_type', sa.String(), nullable=False),
|
||||||
|
sa.Column('value', sa.Float(), nullable=False),
|
||||||
|
sa.Column('round_to', sa.String(), nullable=True),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.Column('updated_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.Column('updated_by', sa.Integer(), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['updated_by'], ['users.id']),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
op.create_index('ix_channel_prices_id', 'channel_prices', ['id'])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table('channel_prices')
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""A floor area's colour (UI review 2026-11-20): "#rrggbb", drawn see-through on the plan.
|
||||||
|
|
||||||
|
Revision ID: 0041_floor_item_color
|
||||||
|
Revises: 0040_channel_prices
|
||||||
|
Create Date: 2026-11-20 18:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0041_floor_item_color'
|
||||||
|
down_revision = '0040_channel_prices'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('floor_items', schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('color', sa.String(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('floor_items', schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('color')
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""Every menu text per language (owner 2026-11-21, core/menu_languages.py).
|
||||||
|
|
||||||
|
- Every choice gets its own `translations` {language: text}: choice groups, quick options,
|
||||||
|
extras, ingredients, preference sets and their choices (sub-choices and a set's shared
|
||||||
|
sub-set keep theirs inside their JSON).
|
||||||
|
- The texts typed so far had no language: they become the text **in their language**: Greek
|
||||||
|
letters → "el", else the venue's language (`venue.language`, default "en"). A language that
|
||||||
|
already had a translation keeps it.
|
||||||
|
- The product's old `"quick": {"<quick option's name>": "…"}` translations move onto the quick
|
||||||
|
options.
|
||||||
|
|
||||||
|
Revision ID: 0042_menu_texts_per_language
|
||||||
|
Revises: 0041_floor_item_color
|
||||||
|
Create Date: 2026-11-21 12:00:00
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0042_menu_texts_per_language'
|
||||||
|
down_revision = '0041_floor_item_color'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
CHOICE_TABLES = ('product_modifier_groups', 'product_quick_options', 'product_options', 'product_ingredients',
|
||||||
|
'product_preference_sets', 'product_preference_choices')
|
||||||
|
GREEK = re.compile('[Ͱ-Ͽἀ-]')
|
||||||
|
LANGS = ('el', 'en')
|
||||||
|
|
||||||
|
|
||||||
|
def _load(v):
|
||||||
|
if not v:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
d = json.loads(v)
|
||||||
|
except ValueError:
|
||||||
|
return {}
|
||||||
|
return d if isinstance(d, (dict, list)) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def _dump(d):
|
||||||
|
return json.dumps(d, ensure_ascii=False) if d else None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
for table in CHOICE_TABLES:
|
||||||
|
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column('translations', sa.Text(), nullable=True))
|
||||||
|
|
||||||
|
bind = op.get_bind()
|
||||||
|
row = bind.execute(sa.text("SELECT value FROM pos_settings WHERE key = 'venue.language'")).first()
|
||||||
|
venue = (row[0] if row else None) or 'en'
|
||||||
|
venue = venue if venue in LANGS else 'en'
|
||||||
|
|
||||||
|
def lang_of(text):
|
||||||
|
return 'el' if GREEK.search(text or '') else venue
|
||||||
|
|
||||||
|
def names(text, current=None):
|
||||||
|
out = dict(current or {})
|
||||||
|
if (text or '').strip():
|
||||||
|
out.setdefault(lang_of(text), text.strip())
|
||||||
|
return out
|
||||||
|
|
||||||
|
def subs(raw):
|
||||||
|
"""Sub-choices (a JSON list of dicts) with their names per language."""
|
||||||
|
data = _load(raw)
|
||||||
|
if not isinstance(data, list) or not data:
|
||||||
|
return raw
|
||||||
|
for s in data:
|
||||||
|
if isinstance(s, dict):
|
||||||
|
s['translations'] = names(s.get('name'), s.get('translations') if isinstance(s.get('translations'), dict) else None)
|
||||||
|
return json.dumps(data, ensure_ascii=False)
|
||||||
|
|
||||||
|
# products: name / description in their language; the quick options' translations move out
|
||||||
|
quick_moved = {}
|
||||||
|
for pid, name, desc, tr in bind.execute(sa.text("SELECT id, name, description, translations FROM products")).fetchall():
|
||||||
|
data = _load(tr)
|
||||||
|
data = data if isinstance(data, dict) else {}
|
||||||
|
for lang, fields in list(data.items()):
|
||||||
|
if not isinstance(fields, dict):
|
||||||
|
data.pop(lang)
|
||||||
|
continue
|
||||||
|
for base, text in (fields.pop('quick', None) or {}).items():
|
||||||
|
quick_moved.setdefault(pid, {}).setdefault(base, {})[lang] = text
|
||||||
|
for field, text in (('name', name), ('description', desc)):
|
||||||
|
if (text or '').strip():
|
||||||
|
data.setdefault(lang_of(text), {}).setdefault(field, text.strip())
|
||||||
|
data = {k: v for k, v in data.items() if v}
|
||||||
|
bind.execute(sa.text("UPDATE products SET translations = :t WHERE id = :id"), {'t': _dump(data), 'id': pid})
|
||||||
|
|
||||||
|
for cid, name, tr in bind.execute(sa.text("SELECT id, name, translations FROM categories")).fetchall():
|
||||||
|
data = _load(tr)
|
||||||
|
data = data if isinstance(data, dict) else {}
|
||||||
|
if (name or '').strip():
|
||||||
|
data.setdefault(lang_of(name), {}).setdefault('name', name.strip())
|
||||||
|
bind.execute(sa.text("UPDATE categories SET translations = :t WHERE id = :id"), {'t': _dump(data), 'id': cid})
|
||||||
|
|
||||||
|
for qid, pid, name in bind.execute(sa.text("SELECT id, product_id, name FROM product_quick_options")).fetchall():
|
||||||
|
bind.execute(sa.text("UPDATE product_quick_options SET translations = :t WHERE id = :id"),
|
||||||
|
{'t': _dump(names(name, quick_moved.get(pid, {}).get(name))), 'id': qid})
|
||||||
|
for table in ('product_modifier_groups', 'product_ingredients'):
|
||||||
|
for rid, name in bind.execute(sa.text(f"SELECT id, name FROM {table}")).fetchall():
|
||||||
|
bind.execute(sa.text(f"UPDATE {table} SET translations = :t WHERE id = :id"), {'t': _dump(names(name)), 'id': rid})
|
||||||
|
for table in ('product_options', 'product_preference_choices'):
|
||||||
|
for rid, name, sub in bind.execute(sa.text(f"SELECT id, name, sub_choices FROM {table}")).fetchall():
|
||||||
|
bind.execute(sa.text(f"UPDATE {table} SET translations = :t, sub_choices = :s WHERE id = :id"),
|
||||||
|
{'t': _dump(names(name)), 's': subs(sub), 'id': rid})
|
||||||
|
for rid, name, shared in bind.execute(sa.text("SELECT id, name, shared_subset FROM product_preference_sets")).fetchall():
|
||||||
|
data = _load(shared)
|
||||||
|
if isinstance(data, dict) and data:
|
||||||
|
data['translations'] = names(data.get('name'))
|
||||||
|
data['choices'] = json.loads(subs(json.dumps(data.get('choices') or [])) or '[]')
|
||||||
|
shared = json.dumps(data, ensure_ascii=False)
|
||||||
|
bind.execute(sa.text("UPDATE product_preference_sets SET translations = :t, shared_subset = :s WHERE id = :id"),
|
||||||
|
{'t': _dump(names(name)), 's': shared, 'id': rid})
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for table in CHOICE_TABLES:
|
||||||
|
with op.batch_alter_table(table, schema=None) as batch_op:
|
||||||
|
batch_op.drop_column('translations')
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
"""Scenes, and signage schedule lines that name their screens (owner 2026-11-21).
|
||||||
|
|
||||||
|
- `scenes`: named modes of the venue (party mode…) that are on or off (models/scene.py).
|
||||||
|
- `signage_schedule_items` replaces the named schedules of 5.4d: each line has its playlist, its
|
||||||
|
screens ([] = every screen), its priority, days, hours, dates, smart days and an optional scene.
|
||||||
|
A schedule's lines become lines for the screens that had that schedule (a schedule no screen
|
||||||
|
used: its lines are kept, turned off). A screen's own playlist is its default; a screen on a
|
||||||
|
schedule without its own playlist gets the schedule's "otherwise" playlist as its default.
|
||||||
|
The device config key `schedule` is gone.
|
||||||
|
- The key `core.scenes.manage` for owners and store managers.
|
||||||
|
|
||||||
|
Revision ID: 0043_scenes_and_schedule_items
|
||||||
|
Revises: 0042_menu_texts_per_language
|
||||||
|
Create Date: 2026-11-21 16:00:00
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0043_scenes_and_schedule_items'
|
||||||
|
down_revision = '0042_menu_texts_per_language'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
'scenes',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('color', sa.String(), nullable=True),
|
||||||
|
sa.Column('description', sa.String(), nullable=True),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('activated_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.Column('until', UTCDateTime(), nullable=True),
|
||||||
|
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
op.create_index('ix_scenes_id', 'scenes', ['id'])
|
||||||
|
op.create_table(
|
||||||
|
'signage_schedule_items',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=True),
|
||||||
|
sa.Column('playlist_id', sa.Integer(), sa.ForeignKey('signage_playlists.id', ondelete='CASCADE'), nullable=False),
|
||||||
|
sa.Column('screen_ids', sa.JSON(), nullable=False),
|
||||||
|
sa.Column('priority', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('enabled', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('days', sa.JSON(), nullable=False),
|
||||||
|
sa.Column('month_days', sa.JSON(), nullable=False),
|
||||||
|
sa.Column('time_from', sa.String(), nullable=True),
|
||||||
|
sa.Column('time_to', sa.String(), nullable=True),
|
||||||
|
sa.Column('date_from', sa.String(), nullable=True),
|
||||||
|
sa.Column('date_to', sa.String(), nullable=True),
|
||||||
|
sa.Column('scene_id', sa.Integer(), sa.ForeignKey('scenes.id', ondelete='SET NULL'), nullable=True),
|
||||||
|
sa.Column('position', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('updated_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
op.create_index('ix_signage_schedule_items_id', 'signage_schedule_items', ['id'])
|
||||||
|
op.create_index('ix_signage_schedule_items_playlist_id', 'signage_schedule_items', ['playlist_id'])
|
||||||
|
op.create_index('ix_signage_schedule_items_scene_id', 'signage_schedule_items', ['scene_id'])
|
||||||
|
|
||||||
|
bind = op.get_bind()
|
||||||
|
playlists = {r[0] for r in bind.execute(sa.text("SELECT id FROM signage_playlists")).fetchall()}
|
||||||
|
screens = []
|
||||||
|
for did, cfg in bind.execute(sa.text("SELECT id, config FROM devices WHERE app_key = 'signage'")).fetchall():
|
||||||
|
c = json.loads(cfg) if isinstance(cfg, str) and cfg else (cfg or {})
|
||||||
|
screens.append((did, c if isinstance(c, dict) else {}))
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
stamp = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')
|
||||||
|
pos = 0
|
||||||
|
for sid, name, fallback, entries in bind.execute(sa.text("SELECT id, name, fallback_playlist_id, entries FROM signage_schedules ORDER BY id")).fetchall():
|
||||||
|
entries = json.loads(entries) if isinstance(entries, str) and entries else (entries or [])
|
||||||
|
on = [did for did, c in screens if c.get('schedule') == sid]
|
||||||
|
for e in entries:
|
||||||
|
if e.get('playlist_id') not in playlists:
|
||||||
|
continue
|
||||||
|
bind.execute(sa.text(
|
||||||
|
"INSERT INTO signage_schedule_items (name, playlist_id, screen_ids, priority, enabled, days, month_days, time_from, time_to, "
|
||||||
|
"date_from, date_to, scene_id, position, created_at, updated_at) VALUES (:name, :pl, :scr, :pri, :en, :days, '[]', :tf, :tt, :df, :dt, "
|
||||||
|
"NULL, :pos, :now, :now)"),
|
||||||
|
{'name': name, 'pl': e['playlist_id'], 'scr': json.dumps(on), 'pri': int(e.get('priority') or 0), 'en': bool(on),
|
||||||
|
'days': json.dumps(e.get('days') or []), 'tf': e.get('time_from'), 'tt': e.get('time_to'),
|
||||||
|
'df': e.get('date_from'), 'dt': e.get('date_to'), 'pos': pos, 'now': stamp})
|
||||||
|
pos += 1
|
||||||
|
for did, c in screens:
|
||||||
|
if c.get('schedule') == sid and not c.get('playlist') and fallback in playlists:
|
||||||
|
c['playlist'] = fallback
|
||||||
|
for did, c in screens:
|
||||||
|
if 'schedule' in c:
|
||||||
|
c.pop('schedule')
|
||||||
|
bind.execute(sa.text("UPDATE devices SET config = :c WHERE id = :id"), {'c': json.dumps(c) if c else None, 'id': did})
|
||||||
|
elif c.get('playlist'):
|
||||||
|
bind.execute(sa.text("UPDATE devices SET config = :c WHERE id = :id"), {'c': json.dumps(c), 'id': did})
|
||||||
|
op.drop_table('signage_schedules')
|
||||||
|
# the new key core.scenes.manage for owners and store managers (their role's template)
|
||||||
|
bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
|
||||||
|
"select id, 'core.scenes.manage' from users where role in ('owner', 'store_manager')"))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
'signage_schedules',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('fallback_playlist_id', sa.Integer(), sa.ForeignKey('signage_playlists.id', ondelete='SET NULL'), nullable=True),
|
||||||
|
sa.Column('entries', sa.JSON(), nullable=False),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('updated_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
op.drop_table('signage_schedule_items')
|
||||||
|
op.drop_table('scenes')
|
||||||
|
op.get_bind().execute(sa.text("delete from user_permissions where key = 'core.scenes.manage'"))
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""The signage Slides library (owner 2026-11-21): slides kept with a name and a description, added
|
||||||
|
to playlists as copies or shown alone as a screen's default (device config `slide`).
|
||||||
|
|
||||||
|
Revision ID: 0044_signage_saved_slides
|
||||||
|
Revises: 0043_scenes_and_schedule_items
|
||||||
|
Create Date: 2026-11-21 22:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0044_signage_saved_slides'
|
||||||
|
down_revision = '0043_scenes_and_schedule_items'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
'signage_saved_slides',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('description', sa.String(), nullable=True),
|
||||||
|
sa.Column('orientation', sa.String(), nullable=False),
|
||||||
|
sa.Column('kind', sa.String(), nullable=False),
|
||||||
|
sa.Column('duration_s', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('transition', sa.String(), nullable=True),
|
||||||
|
sa.Column('video_to_end', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('enabled', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('days', sa.JSON(), nullable=True),
|
||||||
|
sa.Column('time_from', sa.String(), nullable=True),
|
||||||
|
sa.Column('time_to', sa.String(), nullable=True),
|
||||||
|
sa.Column('date_from', sa.String(), nullable=True),
|
||||||
|
sa.Column('date_to', sa.String(), nullable=True),
|
||||||
|
sa.Column('content', sa.JSON(), nullable=False),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('updated_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
op.create_index('ix_signage_saved_slides_id', 'signage_saved_slides', ['id'])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index('ix_signage_saved_slides_id', table_name='signage_saved_slides')
|
||||||
|
op.drop_table('signage_saved_slides')
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Signage slide shapes (6R.13, owner 2026-11-22): a playlist or a library slide may be built for a
|
||||||
|
custom shape ("21:9", "16:10", …) besides landscape / portrait. NULL = its orientation's 16:9 / 9:16.
|
||||||
|
|
||||||
|
Revision ID: 0045_signage_shapes
|
||||||
|
Revises: 0044_signage_saved_slides
|
||||||
|
Create Date: 2026-11-22 10:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0045_signage_shapes'
|
||||||
|
down_revision = '0044_signage_saved_slides'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('signage_playlists') as b:
|
||||||
|
b.add_column(sa.Column('aspect', sa.String(), nullable=True))
|
||||||
|
with op.batch_alter_table('signage_saved_slides') as b:
|
||||||
|
b.add_column(sa.Column('aspect', sa.String(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('signage_saved_slides') as b:
|
||||||
|
b.drop_column('aspect')
|
||||||
|
with op.batch_alter_table('signage_playlists') as b:
|
||||||
|
b.drop_column('aspect')
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""Media folders (6R.16, owner 2026-11-22): the Media page groups files in folders. Only a grouping in
|
||||||
|
the database (media.folder_id); the files stay where they are on disk. A gallery widget can show a folder.
|
||||||
|
|
||||||
|
Revision ID: 0046_media_folders
|
||||||
|
Revises: 0045_signage_shapes
|
||||||
|
Create Date: 2026-11-22 16:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0046_media_folders'
|
||||||
|
down_revision = '0045_signage_shapes'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
'media_folders',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('position', sa.Integer(), nullable=False, server_default='0'),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
op.create_index('ix_media_folders_id', 'media_folders', ['id'])
|
||||||
|
with op.batch_alter_table('media') as b:
|
||||||
|
b.add_column(sa.Column('folder_id', sa.Integer(), nullable=True))
|
||||||
|
b.create_index('ix_media_folder_id', ['folder_id'])
|
||||||
|
b.create_foreign_key('fk_media_folder', 'media_folders', ['folder_id'], ['id'], ondelete='SET NULL')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('media') as b:
|
||||||
|
b.drop_constraint('fk_media_folder', type_='foreignkey')
|
||||||
|
b.drop_index('ix_media_folder_id')
|
||||||
|
b.drop_column('folder_id')
|
||||||
|
op.drop_index('ix_media_folders_id', 'media_folders')
|
||||||
|
op.drop_table('media_folders')
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Prices changed by hand, on the record (owner 2026-11-23, plan 6F.3).
|
||||||
|
|
||||||
|
- price_event_log: approved_by_user_id, stage (cart | sent | served), quantity, for the new
|
||||||
|
event type manual_price (services/price_changes.py).
|
||||||
|
- The keys ordering.prices.modify_sent (everyone who holds ordering.prices.modify today: nobody
|
||||||
|
loses what they could do) and ordering.prices.view_changes (owners and store managers).
|
||||||
|
|
||||||
|
Revision ID: 0047_price_changes
|
||||||
|
Revises: 0046_media_folders
|
||||||
|
Create Date: 2026-11-23 12:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0047_price_changes'
|
||||||
|
down_revision = '0046_media_folders'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('price_event_log') as b:
|
||||||
|
b.add_column(sa.Column('approved_by_user_id', sa.Integer(), nullable=True))
|
||||||
|
b.add_column(sa.Column('stage', sa.String(), nullable=True))
|
||||||
|
b.add_column(sa.Column('quantity', sa.Float(), nullable=True))
|
||||||
|
b.create_foreign_key('fk_price_event_approved_by', 'users', ['approved_by_user_id'], ['id'])
|
||||||
|
bind = op.get_bind()
|
||||||
|
bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
|
||||||
|
"select user_id, 'ordering.prices.modify_sent' from user_permissions where key = 'ordering.prices.modify'"))
|
||||||
|
# a venue that changed a role's default for modify gets the same for modify_sent
|
||||||
|
bind.execute(sa.text("insert or ignore into role_permissions (role, key, granted) "
|
||||||
|
"select role, 'ordering.prices.modify_sent', granted from role_permissions where key = 'ordering.prices.modify'"))
|
||||||
|
bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
|
||||||
|
"select id, 'ordering.prices.view_changes' from users where role in ('owner', 'store_manager')"))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
bind = op.get_bind()
|
||||||
|
bind.execute(sa.text("delete from user_permissions where key in ('ordering.prices.modify_sent', 'ordering.prices.view_changes')"))
|
||||||
|
bind.execute(sa.text("delete from role_permissions where key = 'ordering.prices.modify_sent'"))
|
||||||
|
with op.batch_alter_table('price_event_log') as b:
|
||||||
|
b.drop_constraint('fk_price_event_approved_by', type_='foreignkey')
|
||||||
|
b.drop_column('quantity')
|
||||||
|
b.drop_column('stage')
|
||||||
|
b.drop_column('approved_by_user_id')
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
"""Moves on the record (owner 2026-11-23, plan 6F.4, services/moves.py).
|
||||||
|
|
||||||
|
- order_moves / order_move_items: every table transfer, lines moved, orders merged, with its lines.
|
||||||
|
- order_items.split_from_id: the line a line was cut from (a split), so its path follows it.
|
||||||
|
- Backfill from the audit log written before 6F.4 (notes "Transferred from table A to table B",
|
||||||
|
"Moved to order #N (table T)", "Items merged from order #N (table T)"): one move each, marked
|
||||||
|
note='backfill'. A transfer's lines are the order's lines added before it; quantities unknown.
|
||||||
|
|
||||||
|
Revision ID: 0048_order_moves
|
||||||
|
Revises: 0047_price_changes
|
||||||
|
Create Date: 2026-11-23 15:00:00
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0048_order_moves'
|
||||||
|
down_revision = '0047_price_changes'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
_TABLE = r"(?:table )?(\d+|None)"
|
||||||
|
|
||||||
|
|
||||||
|
def _int(v):
|
||||||
|
return int(v) if v not in (None, "None", "") else None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
'order_moves',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('kind', sa.String(), nullable=False),
|
||||||
|
sa.Column('from_order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=True),
|
||||||
|
sa.Column('to_order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=True),
|
||||||
|
sa.Column('from_table_id', sa.Integer(), sa.ForeignKey('tables.id'), nullable=True),
|
||||||
|
sa.Column('to_table_id', sa.Integer(), sa.ForeignKey('tables.id'), nullable=True),
|
||||||
|
sa.Column('by_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||||
|
sa.Column('approved_by_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||||
|
sa.Column('business_day_id', sa.Integer(), sa.ForeignKey('business_days.id'), nullable=True),
|
||||||
|
sa.Column('at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('note', sa.Text(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
for col in ('id', 'kind', 'from_order_id', 'to_order_id', 'business_day_id', 'at'):
|
||||||
|
op.create_index(f'ix_order_moves_{col}', 'order_moves', [col])
|
||||||
|
op.create_table(
|
||||||
|
'order_move_items',
|
||||||
|
sa.Column('move_id', sa.Integer(), sa.ForeignKey('order_moves.id', ondelete='CASCADE'), nullable=False),
|
||||||
|
sa.Column('item_id', sa.Integer(), sa.ForeignKey('order_items.id'), nullable=False),
|
||||||
|
sa.Column('quantity', sa.Float(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('move_id', 'item_id'),
|
||||||
|
)
|
||||||
|
op.create_index('ix_order_move_items_item_id', 'order_move_items', ['item_id'])
|
||||||
|
with op.batch_alter_table('order_items') as b:
|
||||||
|
b.add_column(sa.Column('split_from_id', sa.Integer(), nullable=True))
|
||||||
|
b.create_index('ix_order_items_split_from_id', ['split_from_id'])
|
||||||
|
b.create_foreign_key('fk_order_items_split_from', 'order_items', ['split_from_id'], ['id'])
|
||||||
|
_backfill(op.get_bind())
|
||||||
|
|
||||||
|
|
||||||
|
def _backfill(bind) -> None:
|
||||||
|
rows = bind.execute(sa.text(
|
||||||
|
"select a.id, a.order_id, a.event_type, a.waiter_id, a.item_ids, a.note, a.created_at, o.table_id, o.business_day_id "
|
||||||
|
"from order_audit_log a join orders o on o.id = a.order_id "
|
||||||
|
"where a.event_type in ('TABLE_TRANSFER', 'ITEMS_MOVED_OUT', 'ITEMS_ADDED') and a.note is not null order by a.id")).fetchall()
|
||||||
|
existing_items = {r[0] for r in bind.execute(sa.text("select id from order_items")).fetchall()}
|
||||||
|
existing_orders = {r[0] for r in bind.execute(sa.text("select id from orders")).fetchall()}
|
||||||
|
|
||||||
|
def add(kind, frm, to, ft, tt, by, at, day, items):
|
||||||
|
res = bind.execute(sa.text(
|
||||||
|
"insert into order_moves (kind, from_order_id, to_order_id, from_table_id, to_table_id, by_user_id, business_day_id, at, note) "
|
||||||
|
"values (:k, :fo, :to, :ft, :tt, :by, :day, :at, 'backfill')"),
|
||||||
|
{'k': kind, 'fo': frm if frm in existing_orders else None, 'to': to if to in existing_orders else None,
|
||||||
|
'ft': ft, 'tt': tt, 'by': by, 'day': day, 'at': at})
|
||||||
|
mid = res.lastrowid
|
||||||
|
for iid in sorted({i for i in items if i in existing_items}):
|
||||||
|
bind.execute(sa.text("insert or ignore into order_move_items (move_id, item_id, quantity) values (:m, :i, null)"),
|
||||||
|
{'m': mid, 'i': iid})
|
||||||
|
|
||||||
|
def ids(raw):
|
||||||
|
try:
|
||||||
|
v = json.loads(raw or '[]')
|
||||||
|
return [int(x) for x in v if isinstance(x, int)]
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return []
|
||||||
|
|
||||||
|
for (_id, order_id, kind, by, item_ids, note, at, table_id, day) in rows:
|
||||||
|
if kind == 'TABLE_TRANSFER':
|
||||||
|
m = re.match(rf"Transferred from table (\d+|None) to table (\d+|None)", note)
|
||||||
|
if not m:
|
||||||
|
continue
|
||||||
|
items = [r[0] for r in bind.execute(sa.text(
|
||||||
|
"select id from order_items where order_id = :o and added_at <= :at"), {'o': order_id, 'at': at}).fetchall()]
|
||||||
|
add('table_transfer', order_id, order_id, _int(m.group(1)), _int(m.group(2)), by, at, day, items)
|
||||||
|
elif kind == 'ITEMS_MOVED_OUT':
|
||||||
|
m = re.match(rf"Moved to order #(\d+) \({_TABLE}\)", note)
|
||||||
|
if not m:
|
||||||
|
continue
|
||||||
|
add('items_moved', order_id, int(m.group(1)), table_id, _int(m.group(2)), by, at, day, ids(item_ids))
|
||||||
|
elif kind == 'ITEMS_ADDED':
|
||||||
|
m = re.match(rf"Items merged from order #(\d+) \({_TABLE}\)", note)
|
||||||
|
if not m:
|
||||||
|
continue
|
||||||
|
add('orders_merged', int(m.group(1)), order_id, _int(m.group(2)), table_id, by, at, day, ids(item_ids))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('order_items') as b:
|
||||||
|
b.drop_constraint('fk_order_items_split_from', type_='foreignkey')
|
||||||
|
b.drop_index('ix_order_items_split_from_id')
|
||||||
|
b.drop_column('split_from_id')
|
||||||
|
op.drop_index('ix_order_move_items_item_id', 'order_move_items')
|
||||||
|
op.drop_table('order_move_items')
|
||||||
|
for col in ('id', 'kind', 'from_order_id', 'to_order_id', 'business_day_id', 'at'):
|
||||||
|
op.drop_index(f'ix_order_moves_{col}', 'order_moves')
|
||||||
|
op.drop_table('order_moves')
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""One more and quantity changes (owner 2026-11-23, plan 6F.5).
|
||||||
|
|
||||||
|
- products.one_more_enabled (off: the owner turns it on per product).
|
||||||
|
- The key ordering.items.change_quantity for owners and store managers (the venue's setting
|
||||||
|
orders.quantity_change starts 'off').
|
||||||
|
|
||||||
|
Revision ID: 0049_one_more
|
||||||
|
Revises: 0048_order_moves
|
||||||
|
Create Date: 2026-11-23 18:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0049_one_more'
|
||||||
|
down_revision = '0048_order_moves'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('products') as b:
|
||||||
|
b.add_column(sa.Column('one_more_enabled', sa.Boolean(), nullable=False, server_default='0'))
|
||||||
|
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
|
||||||
|
"select id, 'ordering.items.change_quantity' from users where role in ('owner', 'store_manager')"))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.get_bind().execute(sa.text("delete from user_permissions where key = 'ordering.items.change_quantity'"))
|
||||||
|
with op.batch_alter_table('products') as b:
|
||||||
|
b.drop_column('one_more_enabled')
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""Split the bill by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py).
|
||||||
|
|
||||||
|
- split_bills: chosen lines settled together and cut into parts paid on their own.
|
||||||
|
- order_items.split_bill_id: on the settled lines (status 'split') and on the part lines.
|
||||||
|
- The key ordering.payments.split_amount for everyone who takes payments (holds
|
||||||
|
ordering.orders.close); the venue's setting payments.split_amount starts 'off'.
|
||||||
|
|
||||||
|
Revision ID: 0050_split_bills
|
||||||
|
Revises: 0049_one_more
|
||||||
|
Create Date: 2026-11-23 21:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0050_split_bills'
|
||||||
|
down_revision = '0049_one_more'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
'split_bills',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=False),
|
||||||
|
sa.Column('total', sa.Float(), nullable=False),
|
||||||
|
sa.Column('mode', sa.String(), nullable=False),
|
||||||
|
sa.Column('parts', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('amounts', sa.Text(), nullable=False),
|
||||||
|
sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||||
|
sa.Column('created_at', UTCDateTime(), nullable=False),
|
||||||
|
sa.Column('business_day_id', sa.Integer(), sa.ForeignKey('business_days.id'), nullable=True),
|
||||||
|
sa.Column('undone_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.Column('undone_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||||
|
sa.Column('receipt_issued_at', UTCDateTime(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
for col in ('id', 'order_id', 'business_day_id'):
|
||||||
|
op.create_index(f'ix_split_bills_{col}', 'split_bills', [col])
|
||||||
|
with op.batch_alter_table('order_items') as b:
|
||||||
|
b.add_column(sa.Column('split_bill_id', sa.Integer(), nullable=True))
|
||||||
|
b.create_index('ix_order_items_split_bill_id', ['split_bill_id'])
|
||||||
|
b.create_foreign_key('fk_order_items_split_bill', 'split_bills', ['split_bill_id'], ['id'])
|
||||||
|
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
|
||||||
|
"select user_id, 'ordering.payments.split_amount' from user_permissions "
|
||||||
|
"where key = 'ordering.orders.close'"))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.get_bind().execute(sa.text("delete from user_permissions where key = 'ordering.payments.split_amount'"))
|
||||||
|
with op.batch_alter_table('order_items') as b:
|
||||||
|
b.drop_constraint('fk_order_items_split_bill', type_='foreignkey')
|
||||||
|
b.drop_index('ix_order_items_split_bill_id')
|
||||||
|
b.drop_column('split_bill_id')
|
||||||
|
for col in ('id', 'order_id', 'business_day_id'):
|
||||||
|
op.drop_index(f'ix_split_bills_{col}', 'split_bills')
|
||||||
|
op.drop_table('split_bills')
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user