Compare commits
141
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0840247768 | ||
|
|
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 |
@@ -19,3 +19,4 @@ logo.png
|
|||||||
waiter_pwa/android
|
waiter_pwa/android
|
||||||
waiter_pwa/releases
|
waiter_pwa/releases
|
||||||
waiter_pwa/tests
|
waiter_pwa/tests
|
||||||
|
terminal/tests
|
||||||
|
|||||||
@@ -26,3 +26,11 @@ services:
|
|||||||
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"
|
||||||
|
|||||||
@@ -53,6 +53,13 @@ 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:
|
||||||
@@ -60,6 +67,7 @@ services:
|
|||||||
- "443:443"
|
- "443:443"
|
||||||
- "4443:4443"
|
- "4443:4443"
|
||||||
- "8081:8081" # manager over plain HTTP (LAN only)
|
- "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)
|
- "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
|
||||||
@@ -72,6 +80,8 @@ services:
|
|||||||
condition: service_started
|
condition: service_started
|
||||||
manager_dashboard:
|
manager_dashboard:
|
||||||
condition: service_started
|
condition: service_started
|
||||||
|
terminal:
|
||||||
|
condition: service_started
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
+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.
|
||||||
+61
-15
File diff suppressed because one or more lines are too long
+49
-3
@@ -109,6 +109,7 @@ cat > "$SCRIPT_DIR/nginx-proxy/nginx.conf" << 'EOF'
|
|||||||
# :80 anything else (bare LAN IP) → waiter app over plain HTTP, LAN only
|
# :80 anything else (bare LAN IP) → waiter app over plain HTTP, LAN only
|
||||||
# /manager → redirect to :8081
|
# /manager → redirect to :8081
|
||||||
# :8081 → manager dashboard over plain HTTP, LAN only
|
# :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)
|
# :443 waiter.* / manager.* / bare IP → https (needs certs/cert.pem + key.pem)
|
||||||
# :4443 → manager over https
|
# :4443 → manager over https
|
||||||
# :8443 → native app over TLS (backend-managed key, pinned), LAN only
|
# :8443 → native app over TLS (backend-managed key, pinned), LAN only
|
||||||
@@ -122,6 +123,10 @@ map $http_upgrade $connection_upgrade {
|
|||||||
'' close;
|
'' 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 ────────────────────────────────────────────────────────────────
|
# ── Plain HTTP ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
server {
|
server {
|
||||||
@@ -196,6 +201,43 @@ server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 8082 default_server;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
# Terminal app for paired screens (KDS, counter POS, customer display; plan step 3.1b).
|
||||||
|
# LAN only: plain HTTP must never be reachable from the internet, even if the
|
||||||
|
# client forwards ports on their router. Relies on Docker preserving the real
|
||||||
|
# client IP (default iptables port publishing on Linux).
|
||||||
|
allow 10.0.0.0/8;
|
||||||
|
allow 172.16.0.0/12;
|
||||||
|
allow 192.168.0.0/16;
|
||||||
|
allow 127.0.0.0/8;
|
||||||
|
allow fc00::/7;
|
||||||
|
allow fe80::/10;
|
||||||
|
allow ::1;
|
||||||
|
deny all;
|
||||||
|
|
||||||
|
# Resolved per request (Docker DNS), so the proxy still starts on a stack that has no
|
||||||
|
# terminal container yet (an older docker-compose.yml): only :8082 fails then (502).
|
||||||
|
resolver 127.0.0.11 valid=30s ipv6=off;
|
||||||
|
set $terminal_upstream http://terminal:80;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass $terminal_upstream;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection $connection_upgrade;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_read_timeout 3600s;
|
||||||
|
proxy_send_timeout 3600s;
|
||||||
|
proxy_buffering off;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
# ── HTTPS ─────────────────────────────────────────────────────────────────────
|
# ── HTTPS ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
server {
|
server {
|
||||||
@@ -208,7 +250,8 @@ server {
|
|||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
||||||
location /api/devices/pair-request {
|
# 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 10.0.0.0/8;
|
||||||
allow 172.16.0.0/12;
|
allow 172.16.0.0/12;
|
||||||
allow 192.168.0.0/16;
|
allow 192.168.0.0/16;
|
||||||
@@ -250,7 +293,8 @@ server {
|
|||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
||||||
location /api/devices/pair-request {
|
# 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 10.0.0.0/8;
|
||||||
allow 172.16.0.0/12;
|
allow 172.16.0.0/12;
|
||||||
allow 192.168.0.0/16;
|
allow 192.168.0.0/16;
|
||||||
@@ -292,7 +336,8 @@ server {
|
|||||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
|
||||||
location /api/devices/pair-request {
|
# 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 10.0.0.0/8;
|
||||||
allow 172.16.0.0/12;
|
allow 172.16.0.0/12;
|
||||||
allow 192.168.0.0/16;
|
allow 192.168.0.0/16;
|
||||||
@@ -445,6 +490,7 @@ echo ""
|
|||||||
echo "Done! Services running. From any phone or PC on this network:"
|
echo "Done! Services running. From any phone or PC on this network:"
|
||||||
echo " Waiter app: http://${HOST_IP_NOW}"
|
echo " Waiter app: http://${HOST_IP_NOW}"
|
||||||
echo " Manager app: http://${HOST_IP_NOW}/manager (→ port 8081)"
|
echo " Manager app: http://${HOST_IP_NOW}/manager (→ port 8081)"
|
||||||
|
echo " Screens: http://${HOST_IP_NOW}:8082 (kitchen display, counter POS; pair them under Devices)"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Tip: reserve ${HOST_IP_NOW} for this machine in the router's DHCP settings"
|
echo "Tip: reserve ${HOST_IP_NOW} for this machine in the router's DHCP settings"
|
||||||
echo " so the address never changes."
|
echo " so the address never changes."
|
||||||
|
|||||||
@@ -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,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.
|
||||||
@@ -44,8 +44,9 @@ def can(user, key: str, db=None) -> bool:
|
|||||||
return is_effective(module_of(key), db) and holds(user, key)
|
return is_effective(module_of(key), db) and holds(user, key)
|
||||||
|
|
||||||
|
|
||||||
def check(ctx: AccessContext, key: str, db=None) -> None:
|
def check(ctx: AccessContext, key: str, db=None):
|
||||||
"""Raise the right XeniaError unless `key` is allowed for this request."""
|
"""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
|
from core.modules.state import blocked_error, is_effective
|
||||||
module = module_of(key)
|
module = module_of(key)
|
||||||
if not is_effective(module, db):
|
if not is_effective(module, db):
|
||||||
@@ -59,7 +60,6 @@ def check(ctx: AccessContext, key: str, db=None) -> None:
|
|||||||
from core.access.override import consume, is_overridable
|
from core.access.override import consume, is_overridable
|
||||||
if is_overridable(key):
|
if is_overridable(key):
|
||||||
if ctx.override_token:
|
if ctx.override_token:
|
||||||
consume(db, ctx.override_token, key, ctx.session, ctx.target)
|
return consume(db, ctx.override_token, key, ctx.session, ctx.target)
|
||||||
return
|
|
||||||
raise XeniaError("access.override_possible", key=key)
|
raise XeniaError("access.override_possible", key=key)
|
||||||
raise XeniaError("access.denied", key=key)
|
raise XeniaError("access.denied", key=key)
|
||||||
|
|||||||
@@ -17,8 +17,9 @@ Agent notes:
|
|||||||
- last_seen_at is written at most every LAST_SEEN_EVERY_S.
|
- 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.
|
- 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
|
get_current_user refuses it without that device's header (device.required), so scope
|
||||||
can't be escaped by dropping the header. SSE/WebSocket (token in the query, browsers
|
can't be escaped by dropping the header. The WebSocket (routers/ws.py, 3.1a) applies the
|
||||||
can't set headers there) only stream events and are not bound; revisit in phase 3.
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -126,13 +127,14 @@ def context_for(request: Request, user, db) -> AccessContext:
|
|||||||
target=f"{request.method} {request.url.path}")
|
target=f"{request.method} {request.url.path}")
|
||||||
|
|
||||||
|
|
||||||
def authorize(request: Request, db, user, key: str, target: str | None = None) -> None:
|
def authorize(request: Request, db, user, key: str, target: str | None = None):
|
||||||
"""check() from inside an endpoint (module, device scope, key, manager override)."""
|
"""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
|
from core.access.check import check
|
||||||
ctx = context_for(request, user, db)
|
ctx = context_for(request, user, db)
|
||||||
if target:
|
if target:
|
||||||
ctx.target = target
|
ctx.target = target
|
||||||
check(ctx, key, db)
|
return check(ctx, key, db)
|
||||||
|
|
||||||
|
|
||||||
def get_context(request: Request, db: Session = Depends(get_db),
|
def get_context(request: Request, db: Session = Depends(get_db),
|
||||||
|
|||||||
@@ -1,20 +1,69 @@
|
|||||||
"""Role templates (D-7): the default keys of each role, read from the module manifests.
|
"""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
|
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.
|
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 __future__ import annotations
|
||||||
|
|
||||||
from core.modules.registry import all_permissions
|
from core.modules.registry import all_permissions
|
||||||
|
|
||||||
|
|
||||||
def role_template(role: str) -> set[str]:
|
def manifest_template(role: str) -> set[str]:
|
||||||
"""Keys a new user with this role gets. Superadmin: none stored (implicit-all)."""
|
"""The role's keys as the manifests declare them. Superadmin: none (implicit-all)."""
|
||||||
if role == "superadmin":
|
if role == "superadmin":
|
||||||
return set()
|
return set()
|
||||||
return {k for k, (p, _m) in all_permissions().items() if role in p.roles}
|
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:
|
def set_user_keys(user, keys) -> None:
|
||||||
"""Replace a user's grants with `keys` (validated against the catalogue)."""
|
"""Replace a user's grants with `keys` (validated against the catalogue)."""
|
||||||
from models.user_permission import UserPermission
|
from models.user_permission import UserPermission
|
||||||
@@ -28,5 +77,5 @@ def set_user_keys(user, keys) -> None:
|
|||||||
[UserPermission(key=k) for k in sorted(wanted - {r.key for r in user.permission_rows})]
|
[UserPermission(key=k) for k in sorted(wanted - {r.key for r in user.permission_rows})]
|
||||||
|
|
||||||
|
|
||||||
def apply_role_template(user) -> None:
|
def apply_role_template(user, db=None) -> None:
|
||||||
set_user_keys(user, role_template(user.role))
|
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)
|
||||||
@@ -11,8 +11,8 @@ Every error response has this shape:
|
|||||||
New and converted code raises XeniaError:
|
New and converted code raises XeniaError:
|
||||||
raise XeniaError("order.not_found", order_id=order_id)
|
raise XeniaError("order.not_found", order_id=order_id)
|
||||||
The status comes from the registry below; pass status= only to override it.
|
The status comes from the registry below; pass status= only to override it.
|
||||||
Plain HTTPException (still in most v1 routers; converted gradually, plan step 6.x)
|
Plain HTTPException is wrapped as code "http.<status>" with its original `detail` untouched
|
||||||
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.
|
Request validation errors become "validation.invalid" with the field errors in params.
|
||||||
Unhandled exceptions become "internal.error" (500) with the request id in params.
|
Unhandled exceptions become "internal.error" (500) with the request id in params.
|
||||||
|
|
||||||
@@ -57,6 +57,7 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"auth.invalid_credentials": (401, "Wrong username or password."),
|
"auth.invalid_credentials": (401, "Wrong username or password."),
|
||||||
"auth.session_ended": (401, "Your session has ended. Please log in again."),
|
"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_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.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.mode_needs_device": (403, "Logging in by {mode} only works on a paired device."),
|
||||||
"auth.username_required": (422, "Enter your username."),
|
"auth.username_required": (422, "Enter your username."),
|
||||||
@@ -66,6 +67,75 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"auth.support_not_configured": (503, "Support access isn't set up on this site."),
|
"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_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."),
|
"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.revoked": (401, "This device was removed. Pair it again."),
|
||||||
"device.not_paired": (401, "This device isn't paired with the venue."),
|
"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.out_of_scope": (403, "A {app} device can't do this ({key})."),
|
||||||
@@ -81,6 +151,7 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"validation.unknown_language": (422, "Unsupported language: {language}."),
|
"validation.unknown_language": (422, "Unsupported language: {language}."),
|
||||||
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
|
"validation.unknown_timezone": (422, "Unknown time zone: {timezone}."),
|
||||||
"validation.setting_value": (422, "{key} can't be set to {value!r}."),
|
"validation.setting_value": (422, "{key} can't be set to {value!r}."),
|
||||||
|
"validation.device_config": (422, "This device setting is not valid: {key}."),
|
||||||
# server
|
# server
|
||||||
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
|
"internal.error": (500, "Something went wrong on the server (request {request_id})."),
|
||||||
# domain
|
# domain
|
||||||
@@ -89,6 +160,162 @@ CODES: dict[str, tuple[int, str]] = {
|
|||||||
"system.log_not_found": (404, "There is no log file for {date}."),
|
"system.log_not_found": (404, "There is no log file for {date}."),
|
||||||
"catalog.unknown_category": (422, "There is no category {category_id}."),
|
"catalog.unknown_category": (422, "There is no category {category_id}."),
|
||||||
"catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."),
|
"catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."),
|
||||||
|
"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."),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -53,7 +53,8 @@
|
|||||||
"paid_total": "Πληρωμενο: {value:.2f}e",
|
"paid_total": "Πληρωμενο: {value:.2f}e",
|
||||||
"pending": "ΕΚΚΡΕΜΗ:",
|
"pending": "ΕΚΚΡΕΜΗ:",
|
||||||
"remaining": "Εκκρεμει: {value:.2f}e",
|
"remaining": "Εκκρεμει: {value:.2f}e",
|
||||||
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ"
|
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ",
|
||||||
|
"split": "ΔΙΑΧΩΡΙΣΜΟΣ (ΕΞΟΦΛΕΙΤΑΙ ΑΠΟ ΤΑ ΜΕΡΗ):"
|
||||||
},
|
},
|
||||||
"ticket": {
|
"ticket": {
|
||||||
"compact_guests": " | {count}ατ.",
|
"compact_guests": " | {count}ατ.",
|
||||||
@@ -66,7 +67,16 @@
|
|||||||
"table_label": "Τραπεζι:",
|
"table_label": "Τραπεζι:",
|
||||||
"table_value": "Τραπεζι {table}",
|
"table_value": "Τραπεζι {table}",
|
||||||
"waiter_label": "Σερβιτορος:",
|
"waiter_label": "Σερβιτορος:",
|
||||||
"without": "ΧΩΡΙΣ:"
|
"without": "ΧΩΡΙΣ:",
|
||||||
|
"for_label": "Για:",
|
||||||
|
"asap": "Το συντομοτερο",
|
||||||
|
"online_label": "Online:",
|
||||||
|
"type": {
|
||||||
|
"delivery": "Διανομη",
|
||||||
|
"takeaway": "Παραλαβη",
|
||||||
|
"dine_in": "Τραπεζι",
|
||||||
|
"preorder": "Προπαραγγελια"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"notification": {
|
"notification": {
|
||||||
@@ -80,6 +90,30 @@
|
|||||||
"print": {
|
"print": {
|
||||||
"failed_final": "Ένα δελτίο της παραγγελίας #{order_id} δεν τυπώθηκε ποτέ στον εκτυπωτή {printer} ({attempts} προσπάθειες).",
|
"failed_final": "Ένα δελτίο της παραγγελίας #{order_id} δεν τυπώθηκε ποτέ στον εκτυπωτή {printer} ({attempts} προσπάθειες).",
|
||||||
"failing": "Ένα δελτίο της παραγγελίας #{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}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,8 @@
|
|||||||
"paid_total": "Paid: {value:.2f}e",
|
"paid_total": "Paid: {value:.2f}e",
|
||||||
"pending": "PENDING:",
|
"pending": "PENDING:",
|
||||||
"remaining": "Remaining: {value:.2f}e",
|
"remaining": "Remaining: {value:.2f}e",
|
||||||
"title": "ORDER SUMMARY"
|
"title": "ORDER SUMMARY",
|
||||||
|
"split": "SPLIT BILL (SETTLED BY THE PARTS):"
|
||||||
},
|
},
|
||||||
"ticket": {
|
"ticket": {
|
||||||
"compact_guests": " | {count}pax",
|
"compact_guests": " | {count}pax",
|
||||||
@@ -66,7 +67,16 @@
|
|||||||
"table_label": "Table:",
|
"table_label": "Table:",
|
||||||
"table_value": "Table {table}",
|
"table_value": "Table {table}",
|
||||||
"waiter_label": "Waiter:",
|
"waiter_label": "Waiter:",
|
||||||
"without": "NO:"
|
"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": {
|
"notification": {
|
||||||
@@ -80,6 +90,30 @@
|
|||||||
"print": {
|
"print": {
|
||||||
"failed_final": "A ticket for order #{order_id} never printed on {printer} ({attempts} attempts).",
|
"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."
|
"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,149 @@
|
|||||||
|
"""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), and since 6R.L the waiters' phones and the counter
|
||||||
|
show menu names in the staff member's language, for display only (`@xenia/access` useMenuText;
|
||||||
|
`routers/pos.py` sends every text per language). Order lines, tickets and the kitchen display keep
|
||||||
|
the base text (the venue's): apps send ids, and sub-choices by their stored name.
|
||||||
|
"""
|
||||||
|
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}
|
||||||
@@ -11,6 +11,8 @@ PUT /modules/{key} enable/disable a module; applies at once (D-19).
|
|||||||
Agent notes:
|
Agent notes:
|
||||||
- `permissions` = the keys the caller holds (user_permissions; superadmin: all, D-7),
|
- `permissions` = the keys the caller holds (user_permissions; superadmin: all, D-7),
|
||||||
limited in bootstrap to effective modules.
|
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).
|
- Access: PUT needs core.modules.manage (owner template).
|
||||||
- `entitled`/`entitlement`/limit `value` come from core/modules/entitlements.py (step 1.4).
|
- `entitled`/`entitlement`/limit `value` come from core/modules/entitlements.py (step 1.4).
|
||||||
"""
|
"""
|
||||||
@@ -26,7 +28,7 @@ from pydantic import BaseModel
|
|||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from core import i18n, timeutil
|
from core import i18n, timeutil
|
||||||
from core.modules import entitlements, state
|
from core.modules import device_config, entitlements, state
|
||||||
from core.modules.registry import all_permissions, registry
|
from core.modules.registry import all_permissions, registry
|
||||||
from database import get_db
|
from database import get_db
|
||||||
from core.access.deps import require
|
from core.access.deps import require
|
||||||
@@ -36,6 +38,22 @@ router = APIRouter()
|
|||||||
_optional_bearer = HTTPBearer(auto_error=False)
|
_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]:
|
def permission_keys_for(user) -> list[str]:
|
||||||
"""The keys a user holds (user_permissions; superadmin: every key)."""
|
"""The keys a user holds (user_permissions; superadmin: every key)."""
|
||||||
from core.access.check import user_keys
|
from core.access.check import user_keys
|
||||||
@@ -70,7 +88,8 @@ def _module_out(m, enabled: dict, effective: frozenset) -> dict:
|
|||||||
"value": ent.limit(m.key, lim.key)} for lim in m.limits],
|
"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}
|
"settings": [{"key": sd.key, "type": sd.type, "default": sd.default, "description": sd.description}
|
||||||
for sd in m.settings],
|
for sd in m.settings],
|
||||||
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope)}
|
"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),
|
if m.device_app else None),
|
||||||
"workers": len(m.workers),
|
"workers": len(m.workers),
|
||||||
}
|
}
|
||||||
@@ -81,6 +100,10 @@ def _login_info(db: Session) -> dict:
|
|||||||
from core import sessions
|
from core import sessions
|
||||||
return {
|
return {
|
||||||
"manager_mode": sessions.manager_login_mode(db), # password | pin
|
"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",
|
"autofill_username": _setting(db, "security.autofill_username", "true") == "true",
|
||||||
"support": bool(cfg.SUPPORT_SECRET and cfg.SITE_ID), # "Support access" is offered
|
"support": bool(cfg.SUPPORT_SECRET and cfg.SITE_ID), # "Support access" is offered
|
||||||
}
|
}
|
||||||
@@ -105,6 +128,8 @@ def bootstrap(
|
|||||||
"timezone": timeutil.venue_tz().key,
|
"timezone": timeutil.venue_tz().key,
|
||||||
"language": i18n.venue_language(),
|
"language": i18n.venue_language(),
|
||||||
"currency": _setting(db, "venue.currency", "EUR"),
|
"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(),
|
"business_day_rollover_hour": timeutil.rollover_hour(),
|
||||||
},
|
},
|
||||||
"modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective],
|
"modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective],
|
||||||
@@ -115,6 +140,7 @@ def bootstrap(
|
|||||||
"user": None,
|
"user": None,
|
||||||
"language": i18n.venue_language(),
|
"language": i18n.venue_language(),
|
||||||
"permissions": [],
|
"permissions": [],
|
||||||
|
"approvable": [],
|
||||||
}
|
}
|
||||||
if user is not None:
|
if user is not None:
|
||||||
out["user"] = {"id": user.id, "username": user.username, "full_name": user.full_name,
|
out["user"] = {"id": user.id, "username": user.username, "full_name": user.full_name,
|
||||||
@@ -122,6 +148,12 @@ def bootstrap(
|
|||||||
out["language"] = i18n.user_language(user)
|
out["language"] = i18n.user_language(user)
|
||||||
out["permissions"] = [k for k in permission_keys_for(user)
|
out["permissions"] = [k for k in permission_keys_for(user)
|
||||||
if all_permissions()[k][1] in effective]
|
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
|
return out
|
||||||
|
|
||||||
|
|
||||||
@@ -141,5 +173,7 @@ class ModuleToggle(BaseModel):
|
|||||||
def set_module(key: str, body: ModuleToggle, db: Session = Depends(get_db),
|
def set_module(key: str, body: ModuleToggle, db: Session = Depends(get_db),
|
||||||
user=Depends(require("core.modules.manage"))):
|
user=Depends(require("core.modules.manage"))):
|
||||||
effective = state.set_enabled(db, key, body.enabled, user_id=getattr(user, "id", None) or None)
|
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)
|
enabled = state.enabled_map(db)
|
||||||
return _module_out(registry()[key], enabled, effective)
|
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]
|
||||||
@@ -54,11 +54,33 @@ class SettingDef:
|
|||||||
choices: tuple[str, ...] = () # for type "enum"
|
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)
|
@dataclass(frozen=True)
|
||||||
class DeviceApp:
|
class DeviceApp:
|
||||||
"""For kind="app" modules that run on a paired device (step 1.8, D-8)."""
|
"""For kind="app" modules that run on a paired device (step 1.8, D-8)."""
|
||||||
login_modes: tuple[str, ...] = ("pin", "tap", "password")
|
login_modes: tuple[str, ...] = ("pin", "tap", "password")
|
||||||
scope: tuple[str, ...] = () # permission-key patterns the device token may use
|
scope: tuple[str, ...] = () # permission-key patterns the device token may use
|
||||||
|
config: tuple[ConfigField, ...] = () # per-device settings (3.1a)
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
|
|||||||
row = db.query(Notification).filter(
|
row = db.query(Notification).filter(
|
||||||
Notification.dedupe_key == dedupe_key,
|
Notification.dedupe_key == dedupe_key,
|
||||||
(Notification.expires_at.is_(None)) | (Notification.expires_at > now),
|
(Notification.expires_at.is_(None)) | (Notification.expires_at > now),
|
||||||
|
Notification.resolved_at.is_(None),
|
||||||
).order_by(Notification.id.desc()).first()
|
).order_by(Notification.id.desc()).first()
|
||||||
if row is not None:
|
if row is not None:
|
||||||
if not fold:
|
if not fold:
|
||||||
@@ -102,7 +103,7 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
|
|||||||
db.commit()
|
db.commit()
|
||||||
logger.info("notification.created id=%s key=%s audience=%s", row.id, key, audience)
|
logger.info("notification.created id=%s key=%s audience=%s", row.id, key, audience)
|
||||||
try:
|
try:
|
||||||
from services.sse_bus import broadcast_sync
|
from services.ws_bus import broadcast_sync
|
||||||
broadcast_sync(EVENT, {"id": row.id}, user_ids=recipients(db, audience))
|
broadcast_sync(EVENT, {"id": row.id}, user_ids=recipients(db, audience))
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception("notification.event_failed id=%s", row.id)
|
logger.exception("notification.event_failed id=%s", row.id)
|
||||||
@@ -119,6 +120,27 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
|
|||||||
db.close()
|
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 ───────────────────────────────────────
|
# ── producers that need a little logic ───────────────────────────────────────
|
||||||
|
|
||||||
EXPIRY_WARN_DAYS = (14, 7, 3, 1)
|
EXPIRY_WARN_DAYS = (14, 7, 3, 1)
|
||||||
|
|||||||
@@ -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])
|
||||||
@@ -2,7 +2,11 @@
|
|||||||
|
|
||||||
Sessions
|
Sessions
|
||||||
- start(db, user, client, request) creates a row and applies the client's single-session
|
- 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).
|
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).
|
- 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,
|
Results are cached for CACHE_TTL_S; end()/end_for_user() drop the cache entry at once,
|
||||||
so an ended session is refused on its very next request.
|
so an ended session is refused on its very next request.
|
||||||
@@ -21,6 +25,7 @@ Agent notes:
|
|||||||
device_id binds it to that device, and a new login on the device replaces the old one),
|
device_id binds it to that device, and a new login on the device replaces the old one),
|
||||||
"support" (1.10).
|
"support" (1.10).
|
||||||
- Never trust a JWT alone: always go through validate().
|
- 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
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -60,15 +65,32 @@ def _setting(db, key: str, default: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def single_session_rule(db, client: str) -> str:
|
def single_session_rule(db, client: str) -> str:
|
||||||
return _setting(db, f"auth.single_session_{client}", "off") if client in ("manager", "waiter") else "off"
|
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 ────────────────────────────────────────────────────────────────
|
# ── lifecycle ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def start(db, user, client: str, request=None, *, device=None, expires_at=None):
|
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.
|
"""Create a session for user (None user_id for the support account). Commits.
|
||||||
`device`: the paired device of a terminal login; its previous sessions are replaced
|
`device`: the paired device of a terminal login; its previous sessions are replaced
|
||||||
(a shared screen shows one user at a time)."""
|
(a shared screen shows one user at a time). `replace`: the person said yes to signing
|
||||||
|
out their other session (rule `ask`)."""
|
||||||
from models.session import LoginSession
|
from models.session import LoginSession
|
||||||
if client not in CLIENTS:
|
if client not in CLIENTS:
|
||||||
raise ValueError(f"unknown client {client!r}")
|
raise ValueError(f"unknown client {client!r}")
|
||||||
@@ -79,6 +101,11 @@ def start(db, user, client: str, request=None, *, device=None, expires_at=None):
|
|||||||
LoginSession.ended_at.is_(None)).all()
|
LoginSession.ended_at.is_(None)).all()
|
||||||
if active and rule == "refuse_new":
|
if active and rule == "refuse_new":
|
||||||
raise XeniaError("auth.session_exists", client=client)
|
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:
|
for s in active:
|
||||||
_end_row(s, "replaced")
|
_end_row(s, "replaced")
|
||||||
if device is not None:
|
if device is not None:
|
||||||
@@ -100,6 +127,8 @@ def _end_row(row, reason: str) -> None:
|
|||||||
row.end_reason = reason
|
row.end_reason = reason
|
||||||
with _lock:
|
with _lock:
|
||||||
_cache.pop(row.id, None)
|
_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)
|
logger.info("session.ended sid=%s user=%s client=%s reason=%s", row.id[:8], row.user_id, row.client, reason)
|
||||||
|
|
||||||
|
|
||||||
@@ -183,7 +212,8 @@ def validate(sid: str | None, db=None) -> Active:
|
|||||||
if row is None or row.ended_at is not None:
|
if row is None or row.ended_at is not None:
|
||||||
with _lock:
|
with _lock:
|
||||||
_cache.pop(sid, None)
|
_cache.pop(sid, None)
|
||||||
raise XeniaError("auth.session_ended")
|
# 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)
|
info = Active(row.user_id, row.device_id, row.expires_at)
|
||||||
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
|
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
|
||||||
finally:
|
finally:
|
||||||
@@ -230,3 +260,12 @@ def waiter_login_mode(db) -> str:
|
|||||||
|
|
||||||
def waiter_requires_username(db) -> bool:
|
def waiter_requires_username(db) -> bool:
|
||||||
return _setting(db, "auth.waiter_require_username", "false") == "true"
|
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"
|
||||||
|
|||||||
+42
-6
@@ -43,12 +43,10 @@ def _init_chat():
|
|||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
import asyncio
|
import asyncio
|
||||||
from services.sse_bus import init_loop as sse_init_loop
|
|
||||||
from services.ws_bus import init_loop as ws_init_loop, prune_old_events
|
from services.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
|
||||||
from services.printer_service import start_print_retry_thread
|
from services.printer_service import start_print_retry_thread
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
sse_init_loop(loop)
|
|
||||||
ws_init_loop(loop)
|
ws_init_loop(loop)
|
||||||
# Schema = Alembic revisions only (core/schema.py, APPS_PLATFORM D-13). Refuses v1 databases.
|
# Schema = Alembic revisions only (core/schema.py, APPS_PLATFORM D-13). Refuses v1 databases.
|
||||||
from core.schema import upgrade_to_head
|
from core.schema import upgrade_to_head
|
||||||
@@ -56,6 +54,11 @@ async def lifespan(app: FastAPI):
|
|||||||
_db = SessionLocal()
|
_db = SessionLocal()
|
||||||
try:
|
try:
|
||||||
apply_retention_setting(_db)
|
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:
|
finally:
|
||||||
_db.close()
|
_db.close()
|
||||||
logger.info("startup version=%s", settings.VERSION)
|
logger.info("startup version=%s", settings.VERSION)
|
||||||
@@ -63,6 +66,8 @@ async def lifespan(app: FastAPI):
|
|||||||
from services.tls_identity import ensure_tls_identity
|
from services.tls_identity import ensure_tls_identity
|
||||||
ensure_tls_identity()
|
ensure_tls_identity()
|
||||||
start_print_retry_thread()
|
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)
|
pruned = prune_old_events(hours=24)
|
||||||
if pruned:
|
if pruned:
|
||||||
logger.info("ws_bus: pruned %d old sync_events", pruned)
|
logger.info("ws_bus: pruned %d old sync_events", pruned)
|
||||||
@@ -74,7 +79,10 @@ async def lifespan(app: FastAPI):
|
|||||||
from core.modules import supervisor
|
from core.modules import supervisor
|
||||||
supervisor.start(loop)
|
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()
|
supervisor.stop_all()
|
||||||
sync_task.cancel()
|
sync_task.cancel()
|
||||||
reservation_task.cancel()
|
reservation_task.cancel()
|
||||||
@@ -93,13 +101,41 @@ app.add_middleware(
|
|||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
)
|
)
|
||||||
# (v1's LicenseCheckMiddleware is gone: an unlicensed site gets the free tier, module by module, D-5.)
|
# (v1's LicenseCheckMiddleware is gone: an unlicensed site gets the free tier, module by module, D-5.)
|
||||||
|
|
||||||
|
|
||||||
|
@app.middleware("http")
|
||||||
|
async def _menu_change_push(request, call_next):
|
||||||
|
"""A successful change to products, price rules or fees pushes the customer apps' menu
|
||||||
|
soon (phase 3S; services/cloud_sync.request_menu_push)."""
|
||||||
|
response = await call_next(request)
|
||||||
|
from services.cloud_sync import menu_changed, request_menu_push
|
||||||
|
if menu_changed(request.method, request.url.path, response.status_code):
|
||||||
|
request_menu_push()
|
||||||
|
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.
|
# Added last = outermost: the request id exists before any other middleware runs.
|
||||||
app.add_middleware(RequestContextMiddleware)
|
app.add_middleware(RequestContextMiddleware)
|
||||||
|
|
||||||
# Serve product images as static files
|
# Product photos live in the media library (/api/media/file/..., step 5.2); the old
|
||||||
IMAGE_DIR = "/app/data/product_images"
|
# data/product_images folder is left on disk untouched after Alembic 0027 copied it in.
|
||||||
os.makedirs(IMAGE_DIR, exist_ok=True)
|
|
||||||
app.mount("/static/product_images", StaticFiles(directory=IMAGE_DIR), name="product_images")
|
|
||||||
|
|
||||||
# Serve waiter avatars as static files
|
# Serve waiter avatars as static files
|
||||||
AVATAR_DIR = "/app/data/avatars"
|
AVATAR_DIR = "/app/data/avatars"
|
||||||
|
|||||||
@@ -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')
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Sign-in (owner 2026-11-23, plan 6F.7).
|
||||||
|
|
||||||
|
- devices.require_username: a paired screen's own choice (NULL = the venue's
|
||||||
|
auth.terminal_require_username).
|
||||||
|
- auth.single_session_waiter: 'ask' is the new default; a venue that has the row set to
|
||||||
|
'off' gets 'ask' too (Q-9). A venue that chose refuse_new / end_old keeps its choice.
|
||||||
|
|
||||||
|
Revision ID: 0051_sign_in
|
||||||
|
Revises: 0050_split_bills
|
||||||
|
Create Date: 2026-11-23 22:00:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
revision = '0051_sign_in'
|
||||||
|
down_revision = '0050_split_bills'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('devices') as b:
|
||||||
|
b.add_column(sa.Column('require_username', sa.Boolean(), nullable=True))
|
||||||
|
op.get_bind().execute(sa.text("update pos_settings set value = 'ask' "
|
||||||
|
"where key = 'auth.single_session_waiter' and value = 'off'"))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('devices') as b:
|
||||||
|
b.drop_column('require_username')
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""The day opens and closes by itself (owner 2026-11-23, plan 6F.8, services/day_auto.py).
|
||||||
|
|
||||||
|
- business_days.opened_auto / closed_auto; opened_by_id may be NULL (opened by the system).
|
||||||
|
- notifications.resolved_at: sticky alerts that stay until their cause is gone.
|
||||||
|
|
||||||
|
Revision ID: 0052_day_auto
|
||||||
|
Revises: 0051_sign_in
|
||||||
|
Create Date: 2026-11-23 23:30:00
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime
|
||||||
|
|
||||||
|
revision = '0052_day_auto'
|
||||||
|
down_revision = '0051_sign_in'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
with op.batch_alter_table('business_days') as b:
|
||||||
|
b.alter_column('opened_by_id', existing_type=sa.Integer(), nullable=True)
|
||||||
|
b.add_column(sa.Column('opened_auto', sa.Boolean(), nullable=False, server_default='0'))
|
||||||
|
b.add_column(sa.Column('closed_auto', sa.Boolean(), nullable=False, server_default='0'))
|
||||||
|
with op.batch_alter_table('notifications') as b:
|
||||||
|
b.add_column(sa.Column('resolved_at', UTCDateTime(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table('notifications') as b:
|
||||||
|
b.drop_column('resolved_at')
|
||||||
|
with op.batch_alter_table('business_days') as b:
|
||||||
|
b.drop_column('closed_auto')
|
||||||
|
b.drop_column('opened_auto')
|
||||||
@@ -10,6 +10,7 @@ import models.table # noqa: F401
|
|||||||
import models.printer # noqa: F401
|
import models.printer # noqa: F401
|
||||||
import models.product # noqa: F401
|
import models.product # noqa: F401
|
||||||
import models.customers # noqa: F401
|
import models.customers # noqa: F401
|
||||||
|
import models.phone_call # noqa: F401
|
||||||
import models.order # noqa: F401 also registers OrderAuditLog, OrderDiscount, PrintJob
|
import models.order # noqa: F401 also registers OrderAuditLog, OrderDiscount, PrintJob
|
||||||
import models.business_day # noqa: F401
|
import models.business_day # noqa: F401
|
||||||
import models.shift # noqa: F401 WaiterShift, ShiftBreak
|
import models.shift # noqa: F401 WaiterShift, ShiftBreak
|
||||||
@@ -29,8 +30,17 @@ import models.recovery_code # noqa: F401
|
|||||||
import models.sync_event # noqa: F401
|
import models.sync_event # noqa: F401
|
||||||
import models.site_module # noqa: F401 SiteModule (module enablement, step 1.3)
|
import models.site_module # noqa: F401 SiteModule (module enablement, step 1.3)
|
||||||
import models.user_permission # noqa: F401 UserPermission (permission keys, step 1.5)
|
import models.user_permission # noqa: F401 UserPermission (permission keys, step 1.5)
|
||||||
|
import models.role_permission # noqa: F401 RolePermission (venue role defaults, step 4.3)
|
||||||
import models.session # noqa: F401 LoginSession (step 1.6)
|
import models.session # noqa: F401 LoginSession (step 1.6)
|
||||||
import models.device # noqa: F401 Device, DevicePairRequest (step 1.8)
|
import models.device # noqa: F401 Device, DevicePairRequest (step 1.8)
|
||||||
import models.access_override # noqa: F401 AccessOverride (manager override, step 1.9)
|
import models.access_override # noqa: F401 AccessOverride (manager override, step 1.9)
|
||||||
import models.support_challenge # noqa: F401 SupportChallenge (support access, step 1.10)
|
import models.support_challenge # noqa: F401 SupportChallenge (support access, step 1.10)
|
||||||
import models.notification # noqa: F401 Notification, NotificationRead (step 1.11)
|
import models.notification # noqa: F401 Notification, NotificationRead (step 1.11)
|
||||||
|
import models.fees # noqa: F401 DeliveryArea, FeeRule (phase 3S, S.3)
|
||||||
|
import models.refund # noqa: F401 Refund, RefundItem (step 3.3e)
|
||||||
|
import models.media # noqa: F401 Media (media library, step 5.1)
|
||||||
|
import models.display_look # noqa: F401 DisplayLook (customer display looks, step 5.3)
|
||||||
|
import models.signage # noqa: F401 SignagePlaylist, SignageSlide, SignageSavedSlide (signage, 5.4a; library 2026-11-21)
|
||||||
|
import models.scene # noqa: F401 Scene (2026-11-21)
|
||||||
|
import models.tablet_order # noqa: F401 TabletOrder (ordering from a menu tablet, step 6.6)
|
||||||
|
import models.floor_plan # noqa: F401 FloorPlan, FloorItem (the table map, step 6.8)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from sqlalchemy import Column, Date, Integer, String, Float, ForeignKey, Text
|
from sqlalchemy import Boolean, Column, Date, Integer, String, Float, ForeignKey, Text
|
||||||
from core.timeutil import UTCDateTime, utcnow
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
from sqlalchemy.orm import relationship
|
from sqlalchemy.orm import relationship
|
||||||
from database import Base
|
from database import Base
|
||||||
@@ -15,7 +15,9 @@ class BusinessDay(Base):
|
|||||||
# The date this day counts as (D-11): set once when the day opens with
|
# The date this day counts as (D-11): set once when the day opens with
|
||||||
# core.timeutil.business_date_of(opened_at), never recalculated. Reports group by it.
|
# core.timeutil.business_date_of(opened_at), never recalculated. Reports group by it.
|
||||||
business_date = Column(Date, nullable=False, index=True)
|
business_date = Column(Date, nullable=False, index=True)
|
||||||
opened_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
opened_by_id = Column(Integer, ForeignKey("users.id"), nullable=True) # NULL = opened by the system (6F.8)
|
||||||
|
opened_auto = Column(Boolean, nullable=False, default=False) # 6F.8: opened / closed by
|
||||||
|
closed_auto = Column(Boolean, nullable=False, default=False) # services/day_auto.py
|
||||||
closed_at = Column(UTCDateTime, nullable=True)
|
closed_at = Column(UTCDateTime, nullable=True)
|
||||||
closed_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
closed_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
notes = Column(Text, nullable=True)
|
notes = Column(Text, nullable=True)
|
||||||
|
|||||||
@@ -32,8 +32,8 @@ class ConversationParticipant(Base):
|
|||||||
__tablename__ = "conversation_participants"
|
__tablename__ = "conversation_participants"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False)
|
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False, index=True)
|
||||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||||
joined_at = Column(UTCDateTime, default=utcnow)
|
joined_at = Column(UTCDateTime, default=utcnow)
|
||||||
last_read_at = Column(UTCDateTime, nullable=True)
|
last_read_at = Column(UTCDateTime, nullable=True)
|
||||||
|
|
||||||
@@ -45,7 +45,7 @@ class ChatMessage(Base):
|
|||||||
__tablename__ = "chat_messages"
|
__tablename__ = "chat_messages"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False)
|
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False, index=True)
|
||||||
sender_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
sender_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||||
body = Column(Text, nullable=False)
|
body = Column(Text, nullable=False)
|
||||||
sent_at = Column(UTCDateTime, default=utcnow)
|
sent_at = Column(UTCDateTime, default=utcnow)
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ Devices are never deleted: revoked rows keep their token hash so the device is t
|
|||||||
`device.revoked` (not "unknown"), and old sessions/audit rows keep a valid device_id.
|
`device.revoked` (not "unknown"), and old sessions/audit rows keep a valid device_id.
|
||||||
Read and written through routers/devices.py and core/access/context.py.
|
Read and written through routers/devices.py and core/access/context.py.
|
||||||
"""
|
"""
|
||||||
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
|
from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String
|
||||||
|
|
||||||
from core.timeutil import UTCDateTime, utcnow
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
from database import Base
|
from database import Base
|
||||||
@@ -29,6 +29,7 @@ class Device(Base):
|
|||||||
app_key = Column(String, nullable=False, index=True) # a kind="app" module with device_app
|
app_key = Column(String, nullable=False, index=True) # a kind="app" module with device_app
|
||||||
config = Column(JSON, nullable=True) # app-specific (e.g. KDS prep zone)
|
config = Column(JSON, nullable=True) # app-specific (e.g. KDS prep zone)
|
||||||
login_mode = Column(String, nullable=True) # NULL = site default auth.default_login_mode
|
login_mode = Column(String, nullable=True) # NULL = site default auth.default_login_mode
|
||||||
|
require_username = Column(Boolean, nullable=True) # NULL = site default auth.terminal_require_username (6F.7)
|
||||||
token_hash = Column(String, nullable=True, unique=True) # sha256 hex; NULL until the device picks it up
|
token_hash = Column(String, nullable=True, unique=True) # sha256 hex; NULL until the device picks it up
|
||||||
linked_device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True)
|
linked_device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True)
|
||||||
user_agent = Column(String, nullable=True) # from the pairing request
|
user_agent = Column(String, nullable=True) # from the pairing request
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
"""Customer display looks (plan step 5.3): named idle screens a venue designs.
|
||||||
|
|
||||||
|
One look is the venue's default; each customer display shows the look in its device config
|
||||||
|
(`look`, a ref to this table) or the default. A look's `config` is routers/customer_display.py
|
||||||
|
IdleBody: style, message, theme, QR target…, and pictures as media library ids (logo, image,
|
||||||
|
slides). Those ids are protected in the library while a look uses them.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import JSON, Boolean, Column, Integer, String
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class DisplayLook(Base):
|
||||||
|
__tablename__ = "display_looks"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
is_default = Column(Boolean, nullable=False, default=False)
|
||||||
|
config = Column(JSON, nullable=False, default=dict)
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
|
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
|
||||||
@@ -28,11 +28,11 @@ class Expense(Base):
|
|||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
description = Column(String, nullable=False)
|
description = Column(String, nullable=False)
|
||||||
category = Column(String, nullable=False) # supplier|utilities|rent|maintenance|staff|equipment|other
|
category = Column(String, nullable=False) # supplier|utilities|rent|maintenance|staff|equipment|other
|
||||||
contact_id = Column(Integer, ForeignKey("contacts.id"), nullable=True)
|
contact_id = Column(Integer, ForeignKey("contacts.id"), nullable=True, index=True)
|
||||||
total_amount = Column(Float, nullable=False)
|
total_amount = Column(Float, nullable=False)
|
||||||
paid_amount = Column(Float, default=0.0, nullable=False)
|
paid_amount = Column(Float, default=0.0, nullable=False)
|
||||||
due_date = Column(UTCDateTime, nullable=True)
|
due_date = Column(UTCDateTime, nullable=True)
|
||||||
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True)
|
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
||||||
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||||
created_at = Column(UTCDateTime, default=utcnow)
|
created_at = Column(UTCDateTime, default=utcnow)
|
||||||
notes = Column(Text, nullable=True)
|
notes = Column(Text, nullable=True)
|
||||||
@@ -40,13 +40,18 @@ class Expense(Base):
|
|||||||
contact = relationship("Contact", back_populates="expenses")
|
contact = relationship("Contact", back_populates="expenses")
|
||||||
created_by = relationship("User", foreign_keys=[created_by_id])
|
created_by = relationship("User", foreign_keys=[created_by_id])
|
||||||
payments = relationship("ExpensePayment", back_populates="expense", cascade="all, delete-orphan")
|
payments = relationship("ExpensePayment", back_populates="expense", cascade="all, delete-orphan")
|
||||||
|
# what was bought (2026-11-20): when an expense has lines, its total is theirs
|
||||||
|
lines = relationship("ExpenseLine", back_populates="expense", cascade="all, delete-orphan",
|
||||||
|
order_by="ExpenseLine.position")
|
||||||
|
documents = relationship("ExpenseDocument", back_populates="expense", cascade="all, delete-orphan",
|
||||||
|
order_by="ExpenseDocument.id")
|
||||||
|
|
||||||
|
|
||||||
class ExpensePayment(Base):
|
class ExpensePayment(Base):
|
||||||
__tablename__ = "expense_payments"
|
__tablename__ = "expense_payments"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False)
|
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False, index=True)
|
||||||
amount = Column(Float, nullable=False)
|
amount = Column(Float, nullable=False)
|
||||||
paid_at = Column(UTCDateTime, default=utcnow)
|
paid_at = Column(UTCDateTime, default=utcnow)
|
||||||
paid_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
paid_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||||
@@ -54,3 +59,37 @@ class ExpensePayment(Base):
|
|||||||
|
|
||||||
expense = relationship("Expense", back_populates="payments")
|
expense = relationship("Expense", back_populates="payments")
|
||||||
paid_by = relationship("User", foreign_keys=[paid_by_id])
|
paid_by = relationship("User", foreign_keys=[paid_by_id])
|
||||||
|
|
||||||
|
|
||||||
|
class ExpenseLine(Base):
|
||||||
|
"""A line of an expense (2026-11-20): what was bought, how many, the price of one before VAT
|
||||||
|
and its VAT rate. Line total = quantity × unit price × (1 + VAT %)."""
|
||||||
|
__tablename__ = "expense_lines"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False, index=True)
|
||||||
|
position = Column(Integer, default=0, nullable=False)
|
||||||
|
description = Column(String, nullable=False)
|
||||||
|
quantity = Column(Float, default=1.0, nullable=False)
|
||||||
|
unit_price = Column(Float, nullable=False) # one, before VAT
|
||||||
|
vat_rate = Column(Float, default=0.0, nullable=False) # %, e.g. 24
|
||||||
|
|
||||||
|
expense = relationship("Expense", back_populates="lines")
|
||||||
|
|
||||||
|
|
||||||
|
class ExpenseDocument(Base):
|
||||||
|
"""A file kept with an expense (2026-11-20): the invoice as a PDF or a photo of the receipt.
|
||||||
|
Stored under MEDIA_DIR/expenses/<expense id>/ (services/expense_docs.py)."""
|
||||||
|
__tablename__ = "expense_documents"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False, index=True)
|
||||||
|
filename = Column(String, nullable=False) # as uploaded
|
||||||
|
stored_name = Column(String, nullable=False) # on disk
|
||||||
|
content_type = Column(String, nullable=False)
|
||||||
|
size = Column(Integer, nullable=False)
|
||||||
|
uploaded_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
|
uploaded_at = Column(UTCDateTime, default=utcnow)
|
||||||
|
|
||||||
|
expense = relationship("Expense", back_populates="documents")
|
||||||
|
uploaded_by = relationship("User", foreign_keys=[uploaded_by_id])
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""Delivery areas and fee rules (plan phase 3S, step S.3).
|
||||||
|
|
||||||
|
The venue lists the areas it delivers to (by name, with postcodes when it wants the customer's
|
||||||
|
postcode matched) and fee rules evaluated in order by services/fees.py — the same engine the
|
||||||
|
cloud runs at checkout (the rules travel with the menu snapshot). See that module for the
|
||||||
|
rule semantics.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import Column, Float, Integer, String, Text
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class DeliveryArea(Base):
|
||||||
|
__tablename__ = "delivery_areas"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
postcodes = Column(Text, nullable=False, default="[]") # JSON list of strings
|
||||||
|
is_active = Column(Integer, nullable=False, default=1)
|
||||||
|
sort_order = Column(Integer, nullable=False, default=0)
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow)
|
||||||
|
|
||||||
|
|
||||||
|
class FeeRule(Base):
|
||||||
|
__tablename__ = "fee_rules"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
is_active = Column(Integer, nullable=False, default=1)
|
||||||
|
sort_order = Column(Integer, nullable=False, default=0)
|
||||||
|
# conditions (empty / null = any)
|
||||||
|
sales_points = Column(Text, nullable=False, default='["online_delivery"]') # JSON list
|
||||||
|
area_ids = Column(Text, nullable=False, default="[]") # JSON list of ints
|
||||||
|
subtotal_min = Column(Float, nullable=True) # products total >= this
|
||||||
|
subtotal_max = Column(Float, nullable=True) # products total < this
|
||||||
|
items_min = Column(Integer, nullable=True) # number of items >= this
|
||||||
|
items_max = Column(Integer, nullable=True) # number of items <= this
|
||||||
|
days = Column(Text, nullable=False, default="[]") # JSON list, Mon=0 … Sun=6
|
||||||
|
time_from = Column(String, nullable=True) # "HH:MM", venue time
|
||||||
|
time_to = Column(String, nullable=True) # "HH:MM"; before time_from = crosses midnight
|
||||||
|
# what it does: set | add | percent | free | minimum
|
||||||
|
action = Column(String, nullable=False, default="set")
|
||||||
|
value = Column(Float, nullable=False, default=0.0)
|
||||||
|
stop = Column(Integer, nullable=False, default=0) # no later rule is looked at once this one applies
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow)
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""Floor plans: where the tables stand (plan step 6.8, owner decisions D-31).
|
||||||
|
|
||||||
|
A zone (table group) can have several floor plans ("Ground floor", "Terrace"); a plan may also
|
||||||
|
have no zone. A plan is a canvas `width` × `height` in plan units (1 unit = 1 px at 100%):
|
||||||
|
- `outline`: the floor's shape as a polygon [[x, y], …] (irregular floors); empty = the whole
|
||||||
|
rectangle;
|
||||||
|
- `grid_on` / `grid_size`: with the grid on, the editor snaps positions and sizes to multiples
|
||||||
|
of `grid_size` (the grid is a help for drawing, the stored positions are plain numbers);
|
||||||
|
- `media_id`: a picture from the media library drawn under everything (e.g. a top-down photo),
|
||||||
|
with `background_opacity`.
|
||||||
|
`FloorItem`s are the things that aren't tables: walls, the bar, labels and areas, each a
|
||||||
|
rectangle (x, y = its centre) with a rotation. A table's place is on the table itself
|
||||||
|
(models/table.py: plan_id, floor_x/floor_y = its centre, width/height, rotation, shape).
|
||||||
|
"""
|
||||||
|
from sqlalchemy import JSON, Boolean, Column, Float, ForeignKey, Integer, String
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
ITEM_KINDS = ("wall", "bar", "label", "area")
|
||||||
|
TABLE_SHAPES = ("round", "square", "long")
|
||||||
|
|
||||||
|
|
||||||
|
class FloorPlan(Base):
|
||||||
|
__tablename__ = "floor_plans"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
group_id = Column(Integer, ForeignKey("table_groups.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
sort_order = Column(Integer, nullable=False, default=0)
|
||||||
|
width = Column(Integer, nullable=False, default=1200)
|
||||||
|
height = Column(Integer, nullable=False, default=800)
|
||||||
|
outline = Column(JSON, nullable=True)
|
||||||
|
grid_on = Column(Boolean, nullable=False, default=False)
|
||||||
|
grid_size = Column(Integer, nullable=False, default=40)
|
||||||
|
media_id = Column(Integer, ForeignKey("media.id", ondelete="SET NULL"), nullable=True)
|
||||||
|
background_opacity = Column(Float, nullable=False, default=0.6)
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
|
|
||||||
|
media = relationship("Media")
|
||||||
|
items = relationship("FloorItem", back_populates="plan", cascade="all, delete-orphan", order_by="FloorItem.id")
|
||||||
|
|
||||||
|
|
||||||
|
class FloorItem(Base):
|
||||||
|
__tablename__ = "floor_items"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
plan_id = Column(Integer, ForeignKey("floor_plans.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
kind = Column(String, nullable=False)
|
||||||
|
x = Column(Float, nullable=False)
|
||||||
|
y = Column(Float, nullable=False)
|
||||||
|
width = Column(Float, nullable=False)
|
||||||
|
height = Column(Float, nullable=False)
|
||||||
|
rotation = Column(Float, nullable=False, default=0.0)
|
||||||
|
text = Column(String, nullable=True)
|
||||||
|
color = Column(String, nullable=True) # an area's colour, "#rrggbb" (drawn see-through; 2026-11-20)
|
||||||
|
|
||||||
|
plan = relationship("FloorPlan", back_populates="items")
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""The media library (plan step 5.1): every picture and video the venue uses, kept once.
|
||||||
|
|
||||||
|
A row is one file, identified by the sha256 of its bytes (unique: uploading the same file
|
||||||
|
again returns the existing row). The bytes live under `data/media/<sha[:2]>/<sha>/`
|
||||||
|
(services/media.py): the original as uploaded, and for images three WebP sizes (thumb,
|
||||||
|
card, full). Files are served by hash at `/api/media/file/<sha>/<variant>` with long cache
|
||||||
|
headers, so a URL never changes meaning: a different file is a different URL.
|
||||||
|
|
||||||
|
Rows are referenced by id from what uses them (products, the customer display, signage;
|
||||||
|
steps 5.2-5.4). Those users register a usage check in services/media.py so a file in use
|
||||||
|
can't be deleted.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Media(Base):
|
||||||
|
__tablename__ = "media"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
kind = Column(String, nullable=False, index=True) # image | video
|
||||||
|
name = Column(String, nullable=False) # shown in the library; editable
|
||||||
|
original_name = Column(String, nullable=True) # the uploaded file's name
|
||||||
|
content_type = Column(String, nullable=False) # of the original
|
||||||
|
sha256 = Column(String(64), nullable=False, unique=True)
|
||||||
|
bytes = Column(Integer, nullable=False) # of the original
|
||||||
|
width = Column(Integer, nullable=True) # images; videos when the file says
|
||||||
|
height = Column(Integer, nullable=True)
|
||||||
|
duration_ms = Column(Integer, nullable=True) # videos (MP4) when the file says
|
||||||
|
uploaded_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
|
# Shipped with the server (assets/builtin_media, step 5.4a): can't be deleted or renamed
|
||||||
|
builtin = Column(Boolean, nullable=False, default=False, server_default='0')
|
||||||
|
# Videos (step 5.4e, services/video.py): the still frame and the version every screen plays are
|
||||||
|
# made in the background. waiting | working | done | failed; None = nothing to do (pictures,
|
||||||
|
# or no video tool on this server). `progress` 0-100 while working.
|
||||||
|
processing = Column(String, nullable=True)
|
||||||
|
progress = Column(Integer, nullable=True)
|
||||||
|
# its folder on the Media page (6R.16): only a grouping, the file stays where it is
|
||||||
|
folder_id = Column(Integer, ForeignKey("media_folders.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
|
||||||
|
uploader = relationship("User", lazy="joined")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def uploaded_by_name(self):
|
||||||
|
return self.uploader.full_name or self.uploader.username if self.uploader is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
class MediaFolder(Base):
|
||||||
|
"""A folder of the media library (6R.16): a name and a place in the list; its files point at it."""
|
||||||
|
__tablename__ = "media_folders"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
position = Column(Integer, nullable=False, default=0, server_default='0')
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
@@ -42,7 +42,7 @@ class StaffMessageAck(Base):
|
|||||||
__tablename__ = "staff_message_acks"
|
__tablename__ = "staff_message_acks"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
message_id = Column(Integer, ForeignKey("staff_messages.id"), nullable=False)
|
message_id = Column(Integer, ForeignKey("staff_messages.id"), nullable=False, index=True)
|
||||||
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||||
acked_at = Column(UTCDateTime, default=utcnow)
|
acked_at = Column(UTCDateTime, default=utcnow)
|
||||||
|
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ failures (later: Ergani, close-day reminders). NOT staff chat or manager message
|
|||||||
- The text is an i18n key (`notification.<key>` in core/i18n/*.json) + params, rendered
|
- The text is an i18n key (`notification.<key>` in core/i18n/*.json) + params, rendered
|
||||||
in the reader's language when listed.
|
in the reader's language when listed.
|
||||||
- audience: "all_managers" (holders of core.dashboard.access) | "perm:<key>" | "user:<id>".
|
- audience: "all_managers" (holders of core.dashboard.access) | "perm:<key>" | "user:<id>".
|
||||||
- dedupe_key: while a row with the same key is still live (expires_at NULL or future),
|
- dedupe_key: while a row with the same key is still live (expires_at NULL or future, not
|
||||||
notify() bumps its `count` / `last_at` instead of adding a row.
|
resolved), notify() bumps its `count` / `last_at` instead of adding a row.
|
||||||
|
- resolved_at (6F.8): a sticky alert ("the day isn't open") stays until its cause is gone;
|
||||||
|
core.notifications.resolve() then hides it.
|
||||||
Written through core/notifications.py only.
|
Written through core/notifications.py only.
|
||||||
"""
|
"""
|
||||||
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
|
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
|
||||||
@@ -31,6 +33,7 @@ class Notification(Base):
|
|||||||
created_at = Column(UTCDateTime, nullable=False, default=utcnow, index=True)
|
created_at = Column(UTCDateTime, nullable=False, default=utcnow, index=True)
|
||||||
last_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
last_at = Column(UTCDateTime, nullable=False, default=utcnow)
|
||||||
expires_at = Column(UTCDateTime, nullable=True) # hidden (and dedupe ends) after this
|
expires_at = Column(UTCDateTime, nullable=True) # hidden (and dedupe ends) after this
|
||||||
|
resolved_at = Column(UTCDateTime, nullable=True) # 6F.8: a sticky alert whose cause is gone (hidden, dedupe ends)
|
||||||
|
|
||||||
|
|
||||||
class NotificationRead(Base):
|
class NotificationRead(Base):
|
||||||
|
|||||||
+100
-18
@@ -1,4 +1,4 @@
|
|||||||
from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Text
|
from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Index, Text
|
||||||
from core.timeutil import UTCDateTime, utcnow
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
from sqlalchemy.orm import relationship
|
from sqlalchemy.orm import relationship
|
||||||
from database import Base
|
from database import Base
|
||||||
@@ -8,20 +8,23 @@ from database import Base
|
|||||||
|
|
||||||
class Order(Base):
|
class Order(Base):
|
||||||
__tablename__ = "orders"
|
__tablename__ = "orders"
|
||||||
|
# who opened what when (a shift's orders: migration 0038)
|
||||||
|
__table_args__ = (Index("ix_orders_opened_by_opened_at", "opened_by", "opened_at"),)
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True) # nullable for online orders
|
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True, index=True) # nullable for online orders
|
||||||
opened_by = Column(Integer, ForeignKey("users.id"), nullable=False)
|
opened_by = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||||
opened_at = Column(UTCDateTime, default=utcnow)
|
opened_at = Column(UTCDateTime, default=utcnow, index=True)
|
||||||
status = Column(String, default="open", nullable=False) # open|partially_paid|paid|closed|cancelled
|
status = Column(String, default="open", nullable=False, index=True) # open|partially_paid|paid|closed|cancelled
|
||||||
closed_at = Column(UTCDateTime, nullable=True)
|
closed_at = Column(UTCDateTime, nullable=True)
|
||||||
closed_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
closed_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
notes = Column(Text, nullable=True)
|
notes = Column(Text, nullable=True)
|
||||||
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True)
|
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
||||||
# KDS
|
# KDS
|
||||||
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done
|
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done
|
||||||
kds_status_changed_at = Column(UTCDateTime, nullable=True)
|
kds_status_changed_at = Column(UTCDateTime, nullable=True)
|
||||||
order_type = Column(String, default="here", nullable=False) # here|takeaway|delivery
|
order_type = Column(String, default="here", nullable=False) # here|takeaway|delivery
|
||||||
|
sales_point = Column(String, default="in_store", nullable=False) # core/sales_points.py (phase 3S)
|
||||||
|
|
||||||
# Xenia Connect — online order fields
|
# Xenia Connect — online order fields
|
||||||
source = Column(String, default="pos", nullable=False) # "pos" | "online"
|
source = Column(String, default="pos", nullable=False) # "pos" | "online"
|
||||||
@@ -33,8 +36,14 @@ class Order(Base):
|
|||||||
online_customer_address = Column(Text, nullable=True)
|
online_customer_address = Column(Text, nullable=True)
|
||||||
online_customer_notes = Column(Text, nullable=True)
|
online_customer_notes = Column(Text, nullable=True)
|
||||||
online_order_type = Column(String, nullable=True) # "delivery" | "dine_in"
|
online_order_type = Column(String, nullable=True) # "delivery" | "dine_in"
|
||||||
|
online_delivery_area = Column(String, nullable=True) # the area's name (phase 3S, S.5)
|
||||||
|
# the site's own price check when the order was pulled (S.5): NULL = the cloud's prices
|
||||||
|
# match the site's; else JSON {lines: [...], fee: {...}|null} (services/online_check.py)
|
||||||
|
online_price_diff = Column(Text, nullable=True)
|
||||||
|
# when the customer wants it (S.5); NULL = as soon as possible
|
||||||
|
requested_for = Column(UTCDateTime, nullable=True)
|
||||||
# Phase 2F — customer CRM
|
# Phase 2F — customer CRM
|
||||||
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=True)
|
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=True, index=True)
|
||||||
|
|
||||||
# Number of customers at the table for this order
|
# Number of customers at the table for this order
|
||||||
customer_count = Column(Integer, nullable=True)
|
customer_count = Column(Integer, nullable=True)
|
||||||
@@ -46,7 +55,7 @@ class Order(Base):
|
|||||||
opener = relationship("User", foreign_keys=[opened_by], back_populates="orders_opened")
|
opener = relationship("User", foreign_keys=[opened_by], back_populates="orders_opened")
|
||||||
closer = relationship("User", foreign_keys=[closed_by], back_populates="orders_closed")
|
closer = relationship("User", foreign_keys=[closed_by], back_populates="orders_closed")
|
||||||
customer = relationship("Customer", back_populates="orders", foreign_keys=[customer_id])
|
customer = relationship("Customer", back_populates="orders", foreign_keys=[customer_id])
|
||||||
items = relationship("OrderItem", back_populates="order", cascade="all, delete-orphan")
|
items = relationship("OrderItem", back_populates="order", cascade="all, delete-orphan", lazy="selectin")
|
||||||
waiters = relationship("OrderWaiter", back_populates="order", cascade="all, delete-orphan")
|
waiters = relationship("OrderWaiter", back_populates="order", cascade="all, delete-orphan")
|
||||||
print_logs = relationship("PrintLog", back_populates="order", cascade="all, delete-orphan")
|
print_logs = relationship("PrintLog", back_populates="order", cascade="all, delete-orphan")
|
||||||
print_jobs = relationship("PrintJob", back_populates="order", cascade="all, delete-orphan")
|
print_jobs = relationship("PrintJob", back_populates="order", cascade="all, delete-orphan")
|
||||||
@@ -58,8 +67,8 @@ class OrderWaiter(Base):
|
|||||||
__tablename__ = "order_waiters"
|
__tablename__ = "order_waiters"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
|
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
||||||
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||||
assigned_at = Column(UTCDateTime, default=utcnow)
|
assigned_at = Column(UTCDateTime, default=utcnow)
|
||||||
|
|
||||||
order = relationship("Order", back_populates="waiters")
|
order = relationship("Order", back_populates="waiters")
|
||||||
@@ -68,10 +77,12 @@ class OrderWaiter(Base):
|
|||||||
|
|
||||||
class OrderItem(Base):
|
class OrderItem(Base):
|
||||||
__tablename__ = "order_items"
|
__tablename__ = "order_items"
|
||||||
|
# what someone added when (a shift's lines, cancellations: migration 0038)
|
||||||
|
__table_args__ = (Index("ix_order_items_added_by_added_at", "added_by", "added_at"),)
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
|
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
||||||
product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
|
product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
|
||||||
added_by = Column(Integer, ForeignKey("users.id"), nullable=False)
|
added_by = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||||
quantity = Column(Float, nullable=False)
|
quantity = Column(Float, nullable=False)
|
||||||
unit_price = Column(Float, nullable=False) # price snapshot at time of order
|
unit_price = Column(Float, nullable=False) # price snapshot at time of order
|
||||||
@@ -85,7 +96,7 @@ class OrderItem(Base):
|
|||||||
selected_options = Column(Text, nullable=True) # JSON array of option ids
|
selected_options = Column(Text, nullable=True) # JSON array of option ids
|
||||||
removed_ingredients = Column(Text, nullable=True) # JSON array of ingredient ids
|
removed_ingredients = Column(Text, nullable=True) # JSON array of ingredient ids
|
||||||
notes = Column(Text, nullable=True)
|
notes = Column(Text, nullable=True)
|
||||||
status = Column(String, default="active", nullable=False) # active|paid|cancelled
|
status = Column(String, default="active", nullable=False, index=True) # active|paid|cancelled
|
||||||
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done|served|declined
|
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done|served|declined
|
||||||
added_at = Column(UTCDateTime, default=utcnow)
|
added_at = Column(UTCDateTime, default=utcnow)
|
||||||
printed = Column(Boolean, default=False, nullable=False)
|
printed = Column(Boolean, default=False, nullable=False)
|
||||||
@@ -94,7 +105,7 @@ class OrderItem(Base):
|
|||||||
paid_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
paid_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
paid_at = Column(UTCDateTime, nullable=True)
|
paid_at = Column(UTCDateTime, nullable=True)
|
||||||
payment_method = Column(String, nullable=True) # 'cash'|'card'|'other' — future use
|
payment_method = Column(String, nullable=True) # 'cash'|'card'|'other' — future use
|
||||||
paid_in_shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True)
|
paid_in_shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True, index=True)
|
||||||
|
|
||||||
# Phase 2A — cost snapshot (copied from product at time of order, never updated)
|
# Phase 2A — cost snapshot (copied from product at time of order, never updated)
|
||||||
unit_cost = Column(Float, nullable=True)
|
unit_cost = Column(Float, nullable=True)
|
||||||
@@ -110,28 +121,46 @@ class OrderItem(Base):
|
|||||||
# KDS decline tracking
|
# KDS decline tracking
|
||||||
decline_note = Column(Text, nullable=True) # reason set by kitchen when declining
|
decline_note = Column(Text, nullable=True) # reason set by kitchen when declining
|
||||||
|
|
||||||
|
# KDS claim (plan step 3.2c): the cook working on this item; cleared when it moves on
|
||||||
|
claimed_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
|
claimed_at = Column(UTCDateTime, nullable=True)
|
||||||
|
|
||||||
# Courses — optional course assignment for sequenced firing
|
# Courses — optional course assignment for sequenced firing
|
||||||
course_id = Column(Integer, nullable=True)
|
course_id = Column(Integer, nullable=True)
|
||||||
|
# where the line came from (plan step 4.8): waiter | counter | qr | online; NULL = before 4.8
|
||||||
|
source = Column(String, nullable=True)
|
||||||
|
|
||||||
# Deal binding — which deal created this item, and which original item it's linked to
|
# Deal binding — which deal created this item, and which original item it's linked to
|
||||||
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
|
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
|
||||||
linked_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True)
|
linked_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True)
|
||||||
|
# the line this one was cut from (6F.4): a split, a lowered quantity, a split payment; its moves
|
||||||
|
# before the cut are this line's too (services/moves.py)
|
||||||
|
split_from_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True)
|
||||||
|
# a split bill (6F.6): on the lines it settled (status "split") and on its part lines (the
|
||||||
|
# system product split_part, paid like any line); services/split_bills.py
|
||||||
|
split_bill_id = Column(Integer, ForeignKey("split_bills.id"), nullable=True, index=True)
|
||||||
|
|
||||||
order = relationship("Order", back_populates="items")
|
order = relationship("Order", back_populates="items")
|
||||||
product = relationship("Product", back_populates="order_items")
|
product = relationship("Product", back_populates="order_items")
|
||||||
added_by_user = relationship("User", foreign_keys=[added_by], back_populates="order_items")
|
added_by_user = relationship("User", foreign_keys=[added_by], back_populates="order_items")
|
||||||
paid_by_user = relationship("User", foreign_keys=[paid_by], back_populates="items_paid")
|
paid_by_user = relationship("User", foreign_keys=[paid_by], back_populates="items_paid")
|
||||||
|
claimed_by_user = relationship("User", foreign_keys=[claimed_by])
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def unit_type(self) -> str:
|
def unit_type(self) -> str:
|
||||||
return self.product.unit_type if self.product and self.product.unit_type else "piece"
|
return self.product.unit_type if self.product and self.product.unit_type else "piece"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def system_key(self):
|
||||||
|
"""A line the system added (the delivery fee, S.5): its product's system_key, else None."""
|
||||||
|
return self.product.system_key if self.product is not None else None
|
||||||
|
|
||||||
|
|
||||||
class PrintLog(Base):
|
class PrintLog(Base):
|
||||||
__tablename__ = "print_log"
|
__tablename__ = "print_log"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
|
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
||||||
printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False)
|
printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False)
|
||||||
printed_at = Column(UTCDateTime, default=utcnow)
|
printed_at = Column(UTCDateTime, default=utcnow)
|
||||||
item_ids = Column(Text, nullable=False) # JSON array of order_item ids
|
item_ids = Column(Text, nullable=False) # JSON array of order_item ids
|
||||||
@@ -150,7 +179,7 @@ class PrintJob(Base):
|
|||||||
__tablename__ = "print_jobs"
|
__tablename__ = "print_jobs"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
|
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
||||||
printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False)
|
printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False)
|
||||||
zone_id = Column(Integer, nullable=True) # prep zone id, NULL for legacy
|
zone_id = Column(Integer, nullable=True) # prep zone id, NULL for legacy
|
||||||
item_ids = Column(Text, nullable=False) # JSON array of order_item ids
|
item_ids = Column(Text, nullable=False) # JSON array of order_item ids
|
||||||
@@ -162,7 +191,9 @@ class PrintJob(Base):
|
|||||||
last_attempted_at = Column(UTCDateTime, nullable=True)
|
last_attempted_at = Column(UTCDateTime, nullable=True)
|
||||||
succeeded_at = Column(UTCDateTime, nullable=True)
|
succeeded_at = Column(UTCDateTime, nullable=True)
|
||||||
cancelled_at = Column(UTCDateTime, nullable=True)
|
cancelled_at = Column(UTCDateTime, nullable=True)
|
||||||
cancel_reason = Column(String, nullable=True) # "staff_cancelled" | "order_closed"
|
cancel_reason = Column(String, nullable=True) # "staff_cancelled" | "order_closed" | "handled" (6.10)
|
||||||
|
resolved_by = Column(Integer, nullable=True) # 6.10: who sent it elsewhere / marked it handled
|
||||||
|
redirected_to = Column(Integer, nullable=True) # 6.10: the printer it was sent to instead (status success)
|
||||||
|
|
||||||
order = relationship("Order", back_populates="print_jobs")
|
order = relationship("Order", back_populates="print_jobs")
|
||||||
printer = relationship("Printer", back_populates="print_jobs")
|
printer = relationship("Printer", back_populates="print_jobs")
|
||||||
@@ -173,7 +204,7 @@ class OrderAuditLog(Base):
|
|||||||
__tablename__ = "order_audit_log"
|
__tablename__ = "order_audit_log"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
|
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
||||||
event_type = Column(String, nullable=False)
|
event_type = Column(String, nullable=False)
|
||||||
# ORDER_OPENED | ITEMS_ADDED | PAYMENT | PAYMENT_OFFLINE | ORDER_CLOSED | ORDER_CANCELLED | ITEM_CANCELLED
|
# ORDER_OPENED | ITEMS_ADDED | PAYMENT | PAYMENT_OFFLINE | ORDER_CLOSED | ORDER_CANCELLED | ITEM_CANCELLED
|
||||||
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
@@ -200,7 +231,7 @@ class OrderDiscount(Base):
|
|||||||
__tablename__ = "order_discounts"
|
__tablename__ = "order_discounts"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
|
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
||||||
item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) # NULL = whole-order discount
|
item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) # NULL = whole-order discount
|
||||||
discount_type = Column(String, nullable=False) # 'percent' | 'fixed'
|
discount_type = Column(String, nullable=False) # 'percent' | 'fixed'
|
||||||
discount_value = Column(Float, nullable=False) # e.g. 10.0 = 10% or €10.00
|
discount_value = Column(Float, nullable=False) # e.g. 10.0 = 10% or €10.00
|
||||||
@@ -236,3 +267,54 @@ def _snapshot_item_names(session, flush_context, instances):
|
|||||||
cat = session.get(Category, obj.category_id)
|
cat = session.get(Category, obj.category_id)
|
||||||
obj.category_name = cat.name if cat else None
|
obj.category_name = cat.name if cat else None
|
||||||
|
|
||||||
|
|
||||||
|
class OrderMove(Base):
|
||||||
|
"""Something moved between tables or orders (owner 2026-11-23, plan 6F.4, services/moves.py):
|
||||||
|
a whole order to another table (`table_transfer`), chosen lines to another order
|
||||||
|
(`items_moved`), or one order joined into another (`orders_merged`). Never deleted."""
|
||||||
|
__tablename__ = "order_moves"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
kind = Column(String, nullable=False, index=True) # table_transfer | items_moved | orders_merged
|
||||||
|
from_order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
|
||||||
|
to_order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
|
||||||
|
from_table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
|
||||||
|
to_table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
|
||||||
|
by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
|
approved_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
|
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
||||||
|
at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
|
||||||
|
note = Column(Text, nullable=True) # the importer / backfill: where it came from
|
||||||
|
|
||||||
|
items = relationship("OrderMoveItem", back_populates="move", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class OrderMoveItem(Base):
|
||||||
|
"""A line that went with a move, and how much of it (its quantity at the time)."""
|
||||||
|
__tablename__ = "order_move_items"
|
||||||
|
|
||||||
|
move_id = Column(Integer, ForeignKey("order_moves.id", ondelete="CASCADE"), primary_key=True)
|
||||||
|
item_id = Column(Integer, ForeignKey("order_items.id"), primary_key=True, index=True)
|
||||||
|
quantity = Column(Float, nullable=True)
|
||||||
|
|
||||||
|
move = relationship("OrderMove", back_populates="items")
|
||||||
|
|
||||||
|
|
||||||
|
class SplitBill(Base):
|
||||||
|
"""A bill split by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py): chosen lines
|
||||||
|
settled together (status "split") and cut into `parts` part lines that are paid on their own.
|
||||||
|
Undone (undone_at) only while no part was paid or put on a tab."""
|
||||||
|
__tablename__ = "split_bills"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
||||||
|
total = Column(Float, nullable=False)
|
||||||
|
mode = Column(String, nullable=False) # equal | custom
|
||||||
|
parts = Column(Integer, nullable=False)
|
||||||
|
amounts = Column(Text, nullable=False) # JSON [4.5, 10.5]: each part, in order
|
||||||
|
created_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
|
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
||||||
|
undone_at = Column(UTCDateTime, nullable=True)
|
||||||
|
undone_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
|
receipt_issued_at = Column(UTCDateTime, nullable=True) # the fiscal receipt of the settled lines (last part paid)
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
from sqlalchemy import Column, ForeignKey, Integer, String
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class PhoneCall(Base):
|
||||||
|
"""An incoming call the venue's phone system reported (caller ID, plan step 3.5)."""
|
||||||
|
__tablename__ = "phone_calls"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
|
||||||
|
number = Column(String, nullable=False) # as the phone system sent it
|
||||||
|
ext = Column(String, nullable=True) # the extension that was dialled
|
||||||
|
customer_id = Column(Integer, ForeignKey("customers.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
@@ -89,8 +89,9 @@ class PriceModifierCondition(Base):
|
|||||||
min_item_quantity {"min": N} (this product's qty in cart)
|
min_item_quantity {"min": N} (this product's qty in cart)
|
||||||
min_category_qty {"category_id": N, "min": N} (items in category in cart)
|
min_category_qty {"category_id": N, "min": N} (items in category in cart)
|
||||||
min_order_value {"min": 0.00} (cart total before modifiers)
|
min_order_value {"min": 0.00} (cart total before modifiers)
|
||||||
order_channel {"channels": ["pos","online","qr","takeaway"]}
|
order_channel {"channels": [sales point, ...]} (core/sales_points.py; phase 3S)
|
||||||
price_group_active {"price_group_id": N}
|
price_group_active {"price_group_id": N}
|
||||||
|
scene_active {"scene_id": N} (a scene is on: services/scenes.py, 2026-11-21)
|
||||||
user_tier {"tiers": ["bronze","silver","gold"]} (placeholder, needs user accounts)
|
user_tier {"tiers": ["bronze","silver","gold"]} (placeholder, needs user accounts)
|
||||||
low_stock {"threshold": N} (placeholder, needs inventory)
|
low_stock {"threshold": N} (placeholder, needs inventory)
|
||||||
"""
|
"""
|
||||||
@@ -98,7 +99,7 @@ class PriceModifierCondition(Base):
|
|||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"),
|
modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"),
|
||||||
nullable=False)
|
nullable=False, index=True)
|
||||||
condition_type = Column(String, nullable=False)
|
condition_type = Column(String, nullable=False)
|
||||||
params = Column(Text, nullable=False, default="{}") # JSON
|
params = Column(Text, nullable=False, default="{}") # JSON
|
||||||
|
|
||||||
@@ -120,7 +121,7 @@ class PriceModifierTarget(Base):
|
|||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"),
|
modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"),
|
||||||
nullable=False)
|
nullable=False, index=True)
|
||||||
target_type = Column(String, nullable=False) # 'all'|'item'|'category'|'prep_zone'|'tag'
|
target_type = Column(String, nullable=False) # 'all'|'item'|'category'|'prep_zone'|'tag'
|
||||||
target_id = Column(Integer, nullable=True) # legacy single value
|
target_id = Column(Integer, nullable=True) # legacy single value
|
||||||
target_tag = Column(String, nullable=True) # legacy single value
|
target_tag = Column(String, nullable=True) # legacy single value
|
||||||
@@ -180,7 +181,7 @@ class DealCondition(Base):
|
|||||||
__tablename__ = "deal_conditions"
|
__tablename__ = "deal_conditions"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False)
|
deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
condition_type = Column(String, nullable=False)
|
condition_type = Column(String, nullable=False)
|
||||||
params = Column(Text, nullable=False, default="{}") # JSON
|
params = Column(Text, nullable=False, default="{}") # JSON
|
||||||
|
|
||||||
@@ -195,7 +196,7 @@ class DealTarget(Base):
|
|||||||
__tablename__ = "deal_targets"
|
__tablename__ = "deal_targets"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False)
|
deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
target_type = Column(String, nullable=False) # 'item'|'category'|'tag'|'any'
|
target_type = Column(String, nullable=False) # 'item'|'category'|'tag'|'any'
|
||||||
target_id = Column(Integer, nullable=True) # legacy single value
|
target_id = Column(Integer, nullable=True) # legacy single value
|
||||||
target_tag = Column(String, nullable=True) # legacy single value
|
target_tag = Column(String, nullable=True) # legacy single value
|
||||||
@@ -226,6 +227,7 @@ class PriceEventLog(Base):
|
|||||||
# deal_offer_dismissed — waiter dismissed the deal offer
|
# deal_offer_dismissed — waiter dismissed the deal offer
|
||||||
# waiter_discount — manual waiter discount applied
|
# waiter_discount — manual waiter discount applied
|
||||||
# free_item_added — free item added to order as result of a deal
|
# free_item_added — free item added to order as result of a deal
|
||||||
|
# manual_price — a price changed by hand (6F.3, services/price_changes.py)
|
||||||
|
|
||||||
modifier_id = Column(Integer, ForeignKey("price_modifiers.id"), nullable=True)
|
modifier_id = Column(Integer, ForeignKey("price_modifiers.id"), nullable=True)
|
||||||
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
|
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
|
||||||
@@ -235,10 +237,15 @@ class PriceEventLog(Base):
|
|||||||
price_after = Column(Float, nullable=True)
|
price_after = Column(Float, nullable=True)
|
||||||
delta_amount = Column(Float, nullable=True) # price_after - price_before; negative = discount
|
delta_amount = Column(Float, nullable=True) # price_after - price_before; negative = discount
|
||||||
|
|
||||||
# Waiter discount fields
|
# Waiter discount fields (also manual_price: who changed it, and the reason)
|
||||||
applied_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
applied_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
waiter_note = Column(Text, nullable=True)
|
waiter_note = Column(Text, nullable=True)
|
||||||
|
|
||||||
|
# manual_price (6F.3, services/price_changes.py): a price changed by hand
|
||||||
|
approved_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True) # a manager's PIN (D-10)
|
||||||
|
stage = Column(String, nullable=True) # cart | sent | served
|
||||||
|
quantity = Column(Float, nullable=True) # the line's quantity at the time
|
||||||
|
|
||||||
# Snapshot of the conditions that evaluated to True when the event fired.
|
# Snapshot of the conditions that evaluated to True when the event fired.
|
||||||
# JSON object: {"condition_type": evaluated_value, ...}
|
# JSON object: {"condition_type": evaluated_value, ...}
|
||||||
# e.g. {"day_of_week": 5, "time_range": "21:45", "price_group_active": true}
|
# e.g. {"day_of_week": 5, "time_range": "21:45", "price_group_active": true}
|
||||||
@@ -254,6 +261,7 @@ class PriceEventLog(Base):
|
|||||||
modifier = relationship("PriceModifier", foreign_keys=[modifier_id])
|
modifier = relationship("PriceModifier", foreign_keys=[modifier_id])
|
||||||
deal = relationship("Deal", foreign_keys=[deal_id])
|
deal = relationship("Deal", foreign_keys=[deal_id])
|
||||||
applied_by = relationship("User", foreign_keys=[applied_by_user_id])
|
applied_by = relationship("User", foreign_keys=[applied_by_user_id])
|
||||||
|
approved_by = relationship("User", foreign_keys=[approved_by_user_id])
|
||||||
|
|
||||||
|
|
||||||
class WaiterDiscountSettings(Base):
|
class WaiterDiscountSettings(Base):
|
||||||
@@ -280,3 +288,23 @@ class WaiterDiscountSettings(Base):
|
|||||||
max_items_per_order = Column(Integer, nullable=True)
|
max_items_per_order = Column(Integer, nullable=True)
|
||||||
|
|
||||||
user = relationship("User", foreign_keys=[user_id])
|
user = relationship("User", foreign_keys=[user_id])
|
||||||
|
|
||||||
|
|
||||||
|
class ChannelPrice(Base):
|
||||||
|
"""A price at one or more sales points (2026-11-20, services/channel_prices.py): for listed
|
||||||
|
products, the products of listed categories, or (neither) everything sold there. The most
|
||||||
|
precise rule wins: product > category > channel."""
|
||||||
|
__tablename__ = "channel_prices"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=True)
|
||||||
|
sales_points = Column(Text, nullable=False, default="[]") # JSON ["online_delivery", …]
|
||||||
|
product_ids = Column(Text, nullable=False, default="[]") # JSON [int]
|
||||||
|
category_ids = Column(Text, nullable=False, default="[]") # JSON [int]
|
||||||
|
action_type = Column(String, nullable=False) # 'set' | 'add_amount' | 'add_percent'
|
||||||
|
value = Column(Float, nullable=False)
|
||||||
|
round_to = Column(String, nullable=True) # as PriceModifier.round_to
|
||||||
|
is_active = Column(Boolean, nullable=False, default=True)
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow)
|
||||||
|
updated_at = Column(UTCDateTime, nullable=True)
|
||||||
|
updated_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Text
|
from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Text
|
||||||
from sqlalchemy.orm import relationship
|
from sqlalchemy.orm import relationship
|
||||||
from database import Base
|
from database import Base
|
||||||
|
from core.sales_points import ALL as _SALES_POINTS, dump as _dump_sales_points
|
||||||
|
|
||||||
|
_ALL_SALES_POINTS = _dump_sales_points(_SALES_POINTS)
|
||||||
|
|
||||||
|
|
||||||
class Category(Base):
|
class Category(Base):
|
||||||
@@ -16,6 +19,16 @@ class Category(Base):
|
|||||||
general_sort_order = Column(Integer, default=0, nullable=False)
|
general_sort_order = Column(Integer, default=0, nullable=False)
|
||||||
# sub-categories only: if True, the accordion section is expanded by default on the PWA
|
# sub-categories only: if True, the accordion section is expanded by default on the PWA
|
||||||
auto_expanded = Column(Boolean, default=False, nullable=False)
|
auto_expanded = Column(Boolean, default=False, nullable=False)
|
||||||
|
# Its picture in the media library (plan step 5.2); the library refuses to delete it while set
|
||||||
|
media_id = Column(Integer, ForeignKey("media.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
media = relationship("Media", lazy="joined")
|
||||||
|
# The menu in other languages (plan step 6.4, core/menu_languages.py): {"en": {"name": "…"}}
|
||||||
|
translations = Column(Text, nullable=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def image(self):
|
||||||
|
from services.media import image_of
|
||||||
|
return image_of(self.media)
|
||||||
|
|
||||||
# Products whose PRIMARY category this is (tickets, reports). Every product listed in
|
# Products whose PRIMARY category this is (tickets, reports). Every product listed in
|
||||||
# this category, primary or not: `memberships` (ProductCategory, D-23).
|
# this category, primary or not: `memberships` (ProductCategory, D-23).
|
||||||
@@ -37,20 +50,26 @@ class Product(Base):
|
|||||||
primary_category_id = Column(Integer, ForeignKey("categories.id"), nullable=True, index=True)
|
primary_category_id = Column(Integer, ForeignKey("categories.id"), nullable=True, index=True)
|
||||||
base_price = Column(Float, nullable=False)
|
base_price = Column(Float, nullable=False)
|
||||||
is_available = Column(Boolean, default=True, nullable=False)
|
is_available = Column(Boolean, default=True, nullable=False)
|
||||||
# "active" | "archived" — archived products are kept for order history but hidden from active use
|
# "active" | "archived" — archived products are kept for order history but hidden from active use;
|
||||||
|
# "system" — a line the system adds itself (services/system_products.py), never on a menu
|
||||||
lifecycle_status = Column(String, default="active", nullable=False)
|
lifecycle_status = Column(String, default="active", nullable=False)
|
||||||
image_url = Column(String, nullable=True)
|
# system products only (phase 3S, S.5): what the line is, e.g. "delivery_fee"
|
||||||
|
system_key = Column(String, nullable=True, unique=True, index=True)
|
||||||
|
# Its photo in the media library (plan step 5.2; the old image_url files moved there in 0027)
|
||||||
|
media_id = Column(Integer, ForeignKey("media.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
media = relationship("Media", lazy="joined")
|
||||||
sort_order = Column(Integer, default=0, nullable=False)
|
sort_order = Column(Integer, default=0, nullable=False)
|
||||||
|
|
||||||
# Xenia Connect — digital menu overrides
|
# Where it's sold (phase 3S): JSON list of sales points (core/sales_points.py). Prices
|
||||||
digital_visible = Column(Integer, default=1, nullable=False)
|
# per sales point are price modifiers (condition order_channel), not columns.
|
||||||
|
sold_at = Column(Text, nullable=False, default=_ALL_SALES_POINTS)
|
||||||
|
# Xenia Connect — what the customer apps show (name, text, picture); digital_available =
|
||||||
|
# orderable online right now (a temporary switch, like is_available)
|
||||||
digital_available = Column(Integer, default=1, nullable=False)
|
digital_available = Column(Integer, default=1, nullable=False)
|
||||||
digital_name = Column(String, nullable=True)
|
digital_name = Column(String, nullable=True)
|
||||||
digital_description = Column(String, nullable=True)
|
digital_description = Column(String, nullable=True)
|
||||||
digital_price = Column(Float, nullable=True)
|
|
||||||
digital_discount = Column(Float, default=0.0, nullable=False)
|
|
||||||
digital_image_url = Column(String, nullable=True)
|
digital_image_url = Column(String, nullable=True)
|
||||||
# sha256 of the image_url file last successfully pushed to the cloud — lets
|
# sha256 of the photo file (card size) last successfully pushed to the cloud — lets
|
||||||
# cloud_sync skip re-uploading unchanged images on every sync tick
|
# cloud_sync skip re-uploading unchanged images on every sync tick
|
||||||
cloud_image_hash = Column(String, nullable=True)
|
cloud_image_hash = Column(String, nullable=True)
|
||||||
|
|
||||||
@@ -63,12 +82,19 @@ class Product(Base):
|
|||||||
|
|
||||||
# Quick Add: allow adding 1 unit directly from product list without opening config modal
|
# Quick Add: allow adding 1 unit directly from product list without opening config modal
|
||||||
quick_add_enabled = Column(Boolean, default=True, nullable=False)
|
quick_add_enabled = Column(Boolean, default=True, nullable=False)
|
||||||
|
# "One more" (6F.5): a sent line of this product shows +1 (re-order the same, printed as new)
|
||||||
|
one_more_enabled = Column(Boolean, default=False, nullable=False, server_default="0")
|
||||||
|
|
||||||
# Service item: non-inventoried table-service items (cutlery, glasses, etc.)
|
# Service item: non-inventoried table-service items (cutlery, glasses, etc.)
|
||||||
is_service_item = Column(Boolean, default=False, nullable=False)
|
is_service_item = Column(Boolean, default=False, nullable=False)
|
||||||
|
|
||||||
# Tags: JSON array of strings e.g. ["vegan", "gluten-free"]
|
# Tags: JSON array of strings e.g. ["vegan", "gluten-free"]
|
||||||
tags = Column(Text, nullable=True)
|
tags = Column(Text, nullable=True)
|
||||||
|
# The EU allergens it has (plan step 6.3, core/allergens.py): JSON {key: "contains" | "may_contain"}
|
||||||
|
allergens = Column(Text, nullable=True)
|
||||||
|
# The menu in other languages (plan step 6.4, core/menu_languages.py):
|
||||||
|
# {"en": {"name": "…", "description": "…", "quick": {"<quick option>": "…"}}}
|
||||||
|
translations = Column(Text, nullable=True)
|
||||||
|
|
||||||
# Fiscal printer (ΦΗΜ) fields
|
# Fiscal printer (ΦΗΜ) fields
|
||||||
fiscal_name = Column(String, nullable=True) # short name for receipt (falls back to name)
|
fiscal_name = Column(String, nullable=True) # short name for receipt (falls back to name)
|
||||||
@@ -94,17 +120,30 @@ class Product(Base):
|
|||||||
modifier_groups = relationship("ProductModifierGroup", back_populates="product", cascade="all, delete-orphan")
|
modifier_groups = relationship("ProductModifierGroup", back_populates="product", cascade="all, delete-orphan")
|
||||||
order_items = relationship("OrderItem", back_populates="product")
|
order_items = relationship("OrderItem", back_populates="product")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def image(self):
|
||||||
|
"""{"id", "name", "thumb", "card", "full"} of its photo, or None."""
|
||||||
|
from services.media import image_of
|
||||||
|
return image_of(self.media)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def image_url(self):
|
||||||
|
"""The card size of its photo (what the phones and the counter show), or None."""
|
||||||
|
return (self.image or {}).get("card")
|
||||||
|
|
||||||
|
|
||||||
class ProductModifierGroup(Base):
|
class ProductModifierGroup(Base):
|
||||||
"""A named folder/group that can contain options, ingredients, or preference sets."""
|
"""A named folder/group that can contain options, ingredients, or preference sets."""
|
||||||
__tablename__ = "product_modifier_groups"
|
__tablename__ = "product_modifier_groups"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
|
product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
|
||||||
# "option" | "ingredient" | "preference"
|
# "option" | "ingredient" | "preference"
|
||||||
modifier_type = Column(String, nullable=False)
|
modifier_type = Column(String, nullable=False)
|
||||||
name = Column(String, nullable=False)
|
name = Column(String, nullable=False)
|
||||||
sort_order = Column(Integer, default=0, nullable=False)
|
sort_order = Column(Integer, default=0, nullable=False)
|
||||||
|
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||||
|
translations = Column(Text, nullable=True)
|
||||||
|
|
||||||
product = relationship("Product", back_populates="modifier_groups")
|
product = relationship("Product", back_populates="modifier_groups")
|
||||||
|
|
||||||
@@ -113,7 +152,7 @@ class ProductOption(Base):
|
|||||||
__tablename__ = "product_options"
|
__tablename__ = "product_options"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
|
product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
|
||||||
name = Column(String, nullable=False)
|
name = Column(String, nullable=False)
|
||||||
extra_cost = Column(Float, default=0.0)
|
extra_cost = Column(Float, default=0.0)
|
||||||
allow_multiple = Column(Boolean, default=False, nullable=False)
|
allow_multiple = Column(Boolean, default=False, nullable=False)
|
||||||
@@ -127,6 +166,8 @@ class ProductOption(Base):
|
|||||||
is_compact = Column(Boolean, default=False, nullable=False)
|
is_compact = Column(Boolean, default=False, nullable=False)
|
||||||
# Optional group/folder this option belongs to
|
# Optional group/folder this option belongs to
|
||||||
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
|
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
|
||||||
|
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||||
|
translations = Column(Text, nullable=True)
|
||||||
|
|
||||||
product = relationship("Product", back_populates="options")
|
product = relationship("Product", back_populates="options")
|
||||||
|
|
||||||
@@ -135,7 +176,7 @@ class ProductQuickOption(Base):
|
|||||||
__tablename__ = "product_quick_options"
|
__tablename__ = "product_quick_options"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
|
product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
|
||||||
name = Column(String, nullable=False)
|
name = Column(String, nullable=False)
|
||||||
price = Column(Float, default=0.0, nullable=False)
|
price = Column(Float, default=0.0, nullable=False)
|
||||||
allow_multiple = Column(Boolean, default=False, nullable=False)
|
allow_multiple = Column(Boolean, default=False, nullable=False)
|
||||||
@@ -143,6 +184,8 @@ class ProductQuickOption(Base):
|
|||||||
is_favorite = Column(Boolean, default=False, nullable=False)
|
is_favorite = Column(Boolean, default=False, nullable=False)
|
||||||
favorite_sort_order = Column(Integer, default=0, nullable=False)
|
favorite_sort_order = Column(Integer, default=0, nullable=False)
|
||||||
is_compact = Column(Boolean, default=False, nullable=False)
|
is_compact = Column(Boolean, default=False, nullable=False)
|
||||||
|
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||||
|
translations = Column(Text, nullable=True)
|
||||||
|
|
||||||
product = relationship("Product", back_populates="quick_options")
|
product = relationship("Product", back_populates="quick_options")
|
||||||
|
|
||||||
@@ -151,7 +194,7 @@ class ProductIngredient(Base):
|
|||||||
__tablename__ = "product_ingredients"
|
__tablename__ = "product_ingredients"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
|
product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
|
||||||
name = Column(String, nullable=False)
|
name = Column(String, nullable=False)
|
||||||
extra_cost = Column(Float, default=0.0)
|
extra_cost = Column(Float, default=0.0)
|
||||||
is_favorite = Column(Boolean, default=False, nullable=False)
|
is_favorite = Column(Boolean, default=False, nullable=False)
|
||||||
@@ -160,6 +203,8 @@ class ProductIngredient(Base):
|
|||||||
is_compact = Column(Boolean, default=False, nullable=False)
|
is_compact = Column(Boolean, default=False, nullable=False)
|
||||||
# Optional group/folder this ingredient belongs to
|
# Optional group/folder this ingredient belongs to
|
||||||
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
|
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
|
||||||
|
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||||
|
translations = Column(Text, nullable=True)
|
||||||
|
|
||||||
product = relationship("Product", back_populates="ingredients")
|
product = relationship("Product", back_populates="ingredients")
|
||||||
|
|
||||||
@@ -168,7 +213,7 @@ class ProductPreferenceSet(Base):
|
|||||||
__tablename__ = "product_preference_sets"
|
__tablename__ = "product_preference_sets"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
|
product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
|
||||||
name = Column(String, nullable=False)
|
name = Column(String, nullable=False)
|
||||||
default_choice_id = Column(Integer, nullable=True)
|
default_choice_id = Column(Integer, nullable=True)
|
||||||
# JSON: {name, default_choice_index, choices:[{name,extra_cost,is_default}]}
|
# JSON: {name, default_choice_index, choices:[{name,extra_cost,is_default}]}
|
||||||
@@ -182,6 +227,8 @@ class ProductPreferenceSet(Base):
|
|||||||
allow_multi_select = Column(Boolean, default=False, nullable=False)
|
allow_multi_select = Column(Boolean, default=False, nullable=False)
|
||||||
# When True, each selected choice can have a quantity (x2, x3, …)
|
# When True, each selected choice can have a quantity (x2, x3, …)
|
||||||
allow_choice_quantity = Column(Boolean, default=False, nullable=False)
|
allow_choice_quantity = Column(Boolean, default=False, nullable=False)
|
||||||
|
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||||
|
translations = Column(Text, nullable=True)
|
||||||
|
|
||||||
product = relationship("Product", back_populates="preference_sets")
|
product = relationship("Product", back_populates="preference_sets")
|
||||||
choices = relationship("ProductPreferenceChoice", back_populates="set", cascade="all, delete-orphan")
|
choices = relationship("ProductPreferenceChoice", back_populates="set", cascade="all, delete-orphan")
|
||||||
@@ -191,7 +238,7 @@ class ProductPreferenceChoice(Base):
|
|||||||
__tablename__ = "product_preference_choices"
|
__tablename__ = "product_preference_choices"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
set_id = Column(Integer, ForeignKey("product_preference_sets.id"), nullable=False)
|
set_id = Column(Integer, ForeignKey("product_preference_sets.id"), nullable=False, index=True)
|
||||||
name = Column(String, nullable=False)
|
name = Column(String, nullable=False)
|
||||||
extra_cost = Column(Float, default=0.0)
|
extra_cost = Column(Float, default=0.0)
|
||||||
# JSON array of sub-choice objects: [{name, extra_cost, is_default, is_compact}]
|
# JSON array of sub-choice objects: [{name, extra_cost, is_default, is_compact}]
|
||||||
@@ -201,6 +248,8 @@ class ProductPreferenceChoice(Base):
|
|||||||
disables_subset = Column(Boolean, default=False, nullable=False)
|
disables_subset = Column(Boolean, default=False, nullable=False)
|
||||||
# When True renders as half-width card on the PWA
|
# When True renders as half-width card on the PWA
|
||||||
is_compact = Column(Boolean, default=False, nullable=False)
|
is_compact = Column(Boolean, default=False, nullable=False)
|
||||||
|
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
|
||||||
|
translations = Column(Text, nullable=True)
|
||||||
|
|
||||||
set = relationship("ProductPreferenceSet", back_populates="choices")
|
set = relationship("ProductPreferenceSet", back_populates="choices")
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Refunds (plan step 3.3e): money given back for paid items, kept apart from the sale.
|
||||||
|
|
||||||
|
The paid items are never edited: a refund row says how much of which items went back, how
|
||||||
|
(cash from the drawer or back to the card), in whose shift (that cashier's cash goes down)
|
||||||
|
and what the fiscal device made of it (a credit note, or done by hand on the machine).
|
||||||
|
"""
|
||||||
|
from sqlalchemy import Column, Float, ForeignKey, Integer, String, Text
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Refund(Base):
|
||||||
|
__tablename__ = "refunds"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
||||||
|
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
||||||
|
shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True, index=True) # the refunding cashier's
|
||||||
|
refunded_by = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||||
|
approved_by = Column(Integer, ForeignKey("users.id"), nullable=True) # a manager's override, if one was needed
|
||||||
|
device_id = Column(Integer, ForeignKey("devices.id"), nullable=True)
|
||||||
|
method = Column(String, nullable=False) # cash | card
|
||||||
|
amount = Column(Float, nullable=False)
|
||||||
|
reason = Column(Text, nullable=True)
|
||||||
|
# None (fiscal off) | manual (cashier issues it on the machine) | pending | success | failed
|
||||||
|
fiscal_status = Column(String, nullable=True)
|
||||||
|
fiscal_reference = Column(String, nullable=True)
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
|
|
||||||
|
items = relationship("RefundItem", back_populates="refund", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class RefundItem(Base):
|
||||||
|
__tablename__ = "refund_items"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
refund_id = Column(Integer, ForeignKey("refunds.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=False, index=True)
|
||||||
|
quantity = Column(Float, nullable=False)
|
||||||
|
amount = Column(Float, nullable=False)
|
||||||
|
|
||||||
|
refund = relationship("Refund", back_populates="items")
|
||||||
|
order_item = relationship("OrderItem")
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
from sqlalchemy import Column, Integer, String, ForeignKey, Text
|
from sqlalchemy import Column, Float, Integer, String, ForeignKey, Text
|
||||||
from core.timeutil import UTCDateTime, utcnow
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
from sqlalchemy.orm import relationship
|
from sqlalchemy.orm import relationship
|
||||||
from database import Base
|
from database import Base
|
||||||
@@ -20,9 +20,10 @@ class Reservation(Base):
|
|||||||
reserved_for = Column(UTCDateTime, nullable=False)
|
reserved_for = Column(UTCDateTime, nullable=False)
|
||||||
|
|
||||||
# Optional table assignment (assignable/editable later)
|
# Optional table assignment (assignable/editable later)
|
||||||
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
|
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True, index=True)
|
||||||
|
|
||||||
# Lifecycle: pending | arrived | cancelled | no_show
|
# Lifecycle: pending (confirmed, upcoming) | arrived | cancelled | no_show;
|
||||||
|
# online requests (phase 3S, S.6) start as requested → pending (confirmed) | declined
|
||||||
status = Column(String, nullable=False, default="pending")
|
status = Column(String, nullable=False, default="pending")
|
||||||
|
|
||||||
# Source: manager_app | waiter_app | online
|
# Source: manager_app | waiter_app | online
|
||||||
@@ -34,9 +35,21 @@ class Reservation(Base):
|
|||||||
# For future online reservations: cloud-side customer identifier
|
# For future online reservations: cloud-side customer identifier
|
||||||
online_customer_id = Column(String, nullable=True)
|
online_customer_id = Column(String, nullable=True)
|
||||||
|
|
||||||
|
# Online bookings (phase 3S, S.6): the cloud's order (status mirrored to the customer's page)
|
||||||
|
online_order_cloud_id = Column(Integer, nullable=True, index=True)
|
||||||
|
online_ref = Column(String, nullable=True) # "ORD-0042"
|
||||||
|
# food ordered ahead: the cloud's lines (its prices) until the kitchen gets them, then the order
|
||||||
|
items_json = Column(Text, nullable=True) # JSON list as the cloud sent it; NULL = a table only
|
||||||
|
total = Column(Float, nullable=True)
|
||||||
|
online_price_diff = Column(Text, nullable=True) # services/online_check.py; NULL = matched
|
||||||
|
fire_at = Column(UTCDateTime, nullable=True) # when the kitchen gets the food (set on confirming)
|
||||||
|
order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True) # created at fire time
|
||||||
|
response_note = Column(Text, nullable=True) # why it was declined / cancelled (the customer sees it)
|
||||||
|
|
||||||
created_at = Column(UTCDateTime, default=utcnow)
|
created_at = Column(UTCDateTime, default=utcnow)
|
||||||
updated_at = Column(UTCDateTime, default=utcnow,
|
updated_at = Column(UTCDateTime, default=utcnow,
|
||||||
onupdate=utcnow)
|
onupdate=utcnow)
|
||||||
|
|
||||||
table = relationship("Table", foreign_keys=[table_id])
|
table = relationship("Table", foreign_keys=[table_id])
|
||||||
|
order = relationship("Order", foreign_keys=[order_id])
|
||||||
created_by = relationship("User", foreign_keys=[created_by_user_id])
|
created_by = relationship("User", foreign_keys=[created_by_user_id])
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
"""The venue's own role defaults (plan step 4.3).
|
||||||
|
|
||||||
|
A role's default keys come from the manifests (Perm(..., roles=...)). A venue can change
|
||||||
|
them in the manager (Settings → Operation → "What each role may do"): one row per key it
|
||||||
|
adds to (granted=True) or removes from (granted=False) a role. role_template(role, db)
|
||||||
|
applies them; new staff get the venue's version, and a change is also applied to every
|
||||||
|
person who has that role (core/access/templates.py::set_role_keys).
|
||||||
|
"""
|
||||||
|
from sqlalchemy import Boolean, Column, String
|
||||||
|
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class RolePermission(Base):
|
||||||
|
__tablename__ = "role_permissions"
|
||||||
|
|
||||||
|
role = Column(String, primary_key=True)
|
||||||
|
key = Column(String, primary_key=True)
|
||||||
|
granted = Column(Boolean, nullable=False)
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""Scenes (owner 2026-11-21): a named mode of the venue ("Party mode", "Match night") that is on or
|
||||||
|
off. What follows a scene: signage schedule lines that play only while it is on (and win by their
|
||||||
|
priority), and price rules / deals with the condition "a scene is on". Several can be on at once;
|
||||||
|
one may turn itself off at a time (`until`). services/scenes.py.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import Boolean, Column, Integer, String
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Scene(Base):
|
||||||
|
__tablename__ = "scenes"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
color = Column(String, nullable=True) # "#rrggbb", the venue's choice
|
||||||
|
description = Column(String, nullable=True)
|
||||||
|
is_active = Column(Boolean, nullable=False, default=False)
|
||||||
|
activated_at = Column(UTCDateTime, nullable=True)
|
||||||
|
until = Column(UTCDateTime, nullable=True) # on until then (None: until turned off)
|
||||||
|
sort_order = Column(Integer, nullable=False, default=0)
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
@@ -10,7 +10,7 @@ class ScheduledShift(Base):
|
|||||||
__tablename__ = "scheduled_shifts"
|
__tablename__ = "scheduled_shifts"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||||
scheduled_date = Column(Date, nullable=False)
|
scheduled_date = Column(Date, nullable=False)
|
||||||
start_time = Column(String, nullable=False) # "HH:MM" stored as string (SQLite has no Time type)
|
start_time = Column(String, nullable=False) # "HH:MM" stored as string (SQLite has no Time type)
|
||||||
end_time = Column(String, nullable=False)
|
end_time = Column(String, nullable=False)
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ class WaiterShift(Base):
|
|||||||
__tablename__ = "waiter_shifts"
|
__tablename__ = "waiter_shifts"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||||
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=False)
|
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=False, index=True)
|
||||||
started_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
started_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
ended_at = Column(UTCDateTime, nullable=True)
|
ended_at = Column(UTCDateTime, nullable=True)
|
||||||
starting_cash = Column(Float, nullable=True)
|
starting_cash = Column(Float, nullable=True)
|
||||||
@@ -32,7 +32,7 @@ class ShiftBreak(Base):
|
|||||||
__tablename__ = "shift_breaks"
|
__tablename__ = "shift_breaks"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=False)
|
shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=False, index=True)
|
||||||
started_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
started_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
ended_at = Column(UTCDateTime, nullable=True)
|
ended_at = Column(UTCDateTime, nullable=True)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""Digital signage (plan steps 5.4a-5.4d): playlists of slides for TVs.
|
||||||
|
|
||||||
|
A playlist is made for one orientation (the people who build it see the screen's shape) and
|
||||||
|
holds slides in order. A slide is a menu board, a full-screen picture, a full-screen video or
|
||||||
|
a text, with its time on screen, its transition and when it may show (days, hours, dates).
|
||||||
|
What the slide shows is `content`, typed per kind in routers/signage.py (pictures and videos
|
||||||
|
as media library ids, which the library protects while used).
|
||||||
|
|
||||||
|
A paired signage screen plays its default playlist (device config `playlist`) in its own
|
||||||
|
orientation and rotation (modules/signage/manifest.py), unless a schedule line for it matches
|
||||||
|
(SignageScheduleItem, 2026-11-21).
|
||||||
|
"""
|
||||||
|
from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class SignagePlaylist(Base):
|
||||||
|
__tablename__ = "signage_playlists"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
orientation = Column(String, nullable=False, default="landscape") # landscape | portrait
|
||||||
|
aspect = Column(String, nullable=True) # a custom shape "21:9" (6R.13); None: 16:9 / 9:16
|
||||||
|
transition = Column(String, nullable=False, default="fade") # the slides' default
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
|
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
|
||||||
|
|
||||||
|
slides = relationship("SignageSlide", back_populates="playlist", cascade="all, delete-orphan",
|
||||||
|
order_by="SignageSlide.position")
|
||||||
|
|
||||||
|
|
||||||
|
class SignageSlide(Base):
|
||||||
|
__tablename__ = "signage_slides"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
playlist_id = Column(Integer, ForeignKey("signage_playlists.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
position = Column(Integer, nullable=False, default=0)
|
||||||
|
kind = Column(String, nullable=False) # menu | image | video | text
|
||||||
|
name = Column(String, nullable=True) # the timeline's label (optional)
|
||||||
|
duration_s = Column(Integer, nullable=False, default=10)
|
||||||
|
transition = Column(String, nullable=True) # None: the playlist's
|
||||||
|
video_to_end = Column(Boolean, nullable=False, default=False)
|
||||||
|
enabled = Column(Boolean, nullable=False, default=True)
|
||||||
|
# When it may show (venue time); empty = always
|
||||||
|
days = Column(JSON, nullable=True) # [0..6], Monday = 0
|
||||||
|
time_from = Column(String, nullable=True) # "HH:MM"
|
||||||
|
time_to = Column(String, nullable=True) # "HH:MM" (may pass midnight)
|
||||||
|
date_from = Column(String, nullable=True) # "YYYY-MM-DD"
|
||||||
|
date_to = Column(String, nullable=True)
|
||||||
|
content = Column(JSON, nullable=False, default=dict)
|
||||||
|
|
||||||
|
playlist = relationship("SignagePlaylist", back_populates="slides")
|
||||||
|
|
||||||
|
|
||||||
|
class SignageScheduleItem(Base):
|
||||||
|
"""A schedule line (owner 2026-11-21, was named schedules of 5.4d): a playlist on some screens
|
||||||
|
(none picked = every screen), on some days / hours / dates / smart days (core/calendar_days.py),
|
||||||
|
optionally only while a scene is on, with a priority. At a moment, a screen plays the line
|
||||||
|
that matches with the highest priority (then the most specific, then the later one); none →
|
||||||
|
its own default playlist (Screens). services/signage_schedule.py."""
|
||||||
|
__tablename__ = "signage_schedule_items"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=True)
|
||||||
|
playlist_id = Column(Integer, ForeignKey("signage_playlists.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
screen_ids = Column(JSON, nullable=False, default=list) # [] = every screen
|
||||||
|
priority = Column(Integer, nullable=False, default=0)
|
||||||
|
enabled = Column(Boolean, nullable=False, default=True)
|
||||||
|
days = Column(JSON, nullable=False, default=list) # [0..6], Monday = 0; [] = every day
|
||||||
|
month_days = Column(JSON, nullable=False, default=list) # smart days: first, last, first_week, last_week, holiday, not_holiday
|
||||||
|
time_from = Column(String, nullable=True)
|
||||||
|
time_to = Column(String, nullable=True)
|
||||||
|
date_from = Column(String, nullable=True)
|
||||||
|
date_to = Column(String, nullable=True)
|
||||||
|
scene_id = Column(Integer, ForeignKey("scenes.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
position = Column(Integer, nullable=False, default=0)
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
|
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class SignageSavedSlide(Base):
|
||||||
|
"""A slide kept in the Slides library (owner 2026-11-21): built once, with a name and a short
|
||||||
|
description, then added to playlists (a copy goes in) or shown alone on a screen that has it
|
||||||
|
as its default (device config `slide`). The same fields as a playlist's slide, plus the shape
|
||||||
|
it is built for (its preview and the picture-fit warnings)."""
|
||||||
|
__tablename__ = "signage_saved_slides"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
description = Column(String, nullable=True)
|
||||||
|
orientation = Column(String, nullable=False, default="landscape") # landscape | portrait
|
||||||
|
aspect = Column(String, nullable=True) # a custom shape "21:9" (6R.13); None: 16:9 / 9:16
|
||||||
|
kind = Column(String, nullable=False) # menu | image | video | text | blank
|
||||||
|
duration_s = Column(Integer, nullable=False, default=10)
|
||||||
|
transition = Column(String, nullable=True)
|
||||||
|
video_to_end = Column(Boolean, nullable=False, default=False)
|
||||||
|
enabled = Column(Boolean, nullable=False, default=True)
|
||||||
|
days = Column(JSON, nullable=True)
|
||||||
|
time_from = Column(String, nullable=True)
|
||||||
|
time_to = Column(String, nullable=True)
|
||||||
|
date_from = Column(String, nullable=True)
|
||||||
|
date_to = Column(String, nullable=True)
|
||||||
|
content = Column(JSON, nullable=False, default=dict)
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||||
|
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
|
||||||
@@ -19,5 +19,6 @@ class SyncEvent(Base):
|
|||||||
id = Column(Integer, primary_key=True)
|
id = Column(Integer, primary_key=True)
|
||||||
event_type = Column(String, nullable=False)
|
event_type = Column(String, nullable=False)
|
||||||
payload = Column(Text, nullable=False)
|
payload = Column(Text, nullable=False)
|
||||||
target_user_ids = Column(Text, nullable=True)
|
target_user_ids = Column(Text, nullable=True) # JSON list; NULL = not addressed to users
|
||||||
|
target_device_ids = Column(Text, nullable=True) # JSON list of devices (plan 3.1a); NULL = none
|
||||||
created_at = Column(UTCDateTime, nullable=False, index=True)
|
created_at = Column(UTCDateTime, nullable=False, index=True)
|
||||||
|
|||||||
@@ -22,11 +22,20 @@ class Table(Base):
|
|||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
number = Column(Integer, nullable=False)
|
number = Column(Integer, nullable=False)
|
||||||
label = Column(String, nullable=True)
|
label = Column(String, nullable=True)
|
||||||
group_id = Column(Integer, ForeignKey("table_groups.id"), nullable=True)
|
group_id = Column(Integer, ForeignKey("table_groups.id"), nullable=True, index=True)
|
||||||
is_active = Column(Boolean, default=True, nullable=False)
|
is_active = Column(Boolean, default=True, nullable=False)
|
||||||
seat_count = Column(Integer, nullable=True)
|
seat_count = Column(Integer, nullable=True)
|
||||||
|
# its place on a floor plan (6.8, D-31; models/floor_plan.py): floor_x / floor_y = its centre
|
||||||
|
plan_id = Column(Integer, ForeignKey("floor_plans.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
floor_x = Column(Float, nullable=True)
|
floor_x = Column(Float, nullable=True)
|
||||||
floor_y = Column(Float, nullable=True)
|
floor_y = Column(Float, nullable=True)
|
||||||
|
width = Column(Float, nullable=True)
|
||||||
|
height = Column(Float, nullable=True)
|
||||||
|
rotation = Column(Float, nullable=True)
|
||||||
|
shape = Column(String, nullable=True) # round | square | long
|
||||||
|
# the table's QR code (phase 3S, S.7): a random token in the QR menu link; the cloud gets
|
||||||
|
# only its sha256 (services/table_qr.py). A new token makes the printed code useless.
|
||||||
|
qr_token = Column(String, nullable=True, unique=True)
|
||||||
|
|
||||||
group = relationship("TableGroup", back_populates="tables")
|
group = relationship("TableGroup", back_populates="tables")
|
||||||
orders = relationship("Order", back_populates="table")
|
orders = relationship("Order", back_populates="table")
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Orders from a menu tablet at a table (plan step 6.6, D-30).
|
||||||
|
|
||||||
|
Every order a tablet sends is a row: what was sent (`lines`, as the counter's lines by id,
|
||||||
|
services/pos_cart.py), its note, the total it was quoted at, and what happened:
|
||||||
|
waiting a waiter must confirm it first (the venue's or the tablet's setting)
|
||||||
|
sent on the table's order and in the kitchen (`order_id`)
|
||||||
|
declined a waiter declined it (`reason` for the guests)
|
||||||
|
The rows also give the time limit between two orders from one tablet.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import JSON, Column, Float, ForeignKey, Integer, String, Text
|
||||||
|
|
||||||
|
from core.timeutil import UTCDateTime, utcnow
|
||||||
|
from database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class TabletOrder(Base):
|
||||||
|
__tablename__ = "tablet_orders"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
table_id = Column(Integer, ForeignKey("tables.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
lines = Column(JSON, nullable=False, default=list)
|
||||||
|
note = Column(Text, nullable=True)
|
||||||
|
total = Column(Float, nullable=False, default=0.0)
|
||||||
|
status = Column(String, nullable=False, default="waiting", index=True)
|
||||||
|
order_id = Column(Integer, ForeignKey("orders.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
reason = Column(String, nullable=True)
|
||||||
|
decided_by_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
|
||||||
|
decided_at = Column(UTCDateTime, nullable=True)
|
||||||
|
created_at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
|
||||||
@@ -10,7 +10,7 @@ class Tab(Base):
|
|||||||
__tablename__ = "tabs"
|
__tablename__ = "tabs"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=False)
|
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=False, index=True)
|
||||||
status = Column(String, default="open", nullable=False) # open | closed | forgiven
|
status = Column(String, default="open", nullable=False) # open | closed | forgiven
|
||||||
opened_at = Column(UTCDateTime, default=utcnow)
|
opened_at = Column(UTCDateTime, default=utcnow)
|
||||||
closed_at = Column(UTCDateTime, nullable=True)
|
closed_at = Column(UTCDateTime, nullable=True)
|
||||||
@@ -28,13 +28,16 @@ class TabEntry(Base):
|
|||||||
__tablename__ = "tab_entries"
|
__tablename__ = "tab_entries"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False)
|
tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False, index=True)
|
||||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=True)
|
order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
|
||||||
order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True)
|
order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True)
|
||||||
amount = Column(Float, nullable=False) # snapshot at time of tab entry
|
amount = Column(Float, nullable=False) # snapshot at time of tab entry
|
||||||
description = Column(Text, nullable=True) # auto-generated summary
|
description = Column(Text, nullable=True) # auto-generated summary
|
||||||
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||||
created_at = Column(UTCDateTime, default=utcnow)
|
created_at = Column(UTCDateTime, default=utcnow)
|
||||||
|
# 6.13c: the business day and the shift (of whoever did it, if on one) it happened in
|
||||||
|
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
||||||
|
shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True, index=True)
|
||||||
|
|
||||||
tab = relationship("Tab", back_populates="entries")
|
tab = relationship("Tab", back_populates="entries")
|
||||||
created_by = relationship("User", foreign_keys=[created_by_id])
|
created_by = relationship("User", foreign_keys=[created_by_id])
|
||||||
@@ -45,12 +48,15 @@ class TabPayment(Base):
|
|||||||
__tablename__ = "tab_payments"
|
__tablename__ = "tab_payments"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False)
|
tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False, index=True)
|
||||||
amount = Column(Float, nullable=False)
|
amount = Column(Float, nullable=False)
|
||||||
payment_method = Column(String, nullable=True) # cash | card | other
|
payment_method = Column(String, nullable=True) # cash | card | other
|
||||||
received_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
received_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||||
notes = Column(Text, nullable=True)
|
notes = Column(Text, nullable=True)
|
||||||
created_at = Column(UTCDateTime, default=utcnow)
|
created_at = Column(UTCDateTime, default=utcnow)
|
||||||
|
# 6.13c: the business day and the shift (of whoever did it, if on one) it happened in
|
||||||
|
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
||||||
|
shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True, index=True)
|
||||||
|
|
||||||
tab = relationship("Tab", back_populates="payments")
|
tab = relationship("Tab", back_populates="payments")
|
||||||
received_by = relationship("User", foreign_keys=[received_by_id])
|
received_by = relationship("User", foreign_keys=[received_by_id])
|
||||||
|
|||||||
@@ -10,14 +10,14 @@ class WasteLog(Base):
|
|||||||
__tablename__ = "waste_log"
|
__tablename__ = "waste_log"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
|
product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
|
||||||
quantity = Column(Float, nullable=False) # supports decimals
|
quantity = Column(Float, nullable=False) # supports decimals
|
||||||
unit_cost_snapshot = Column(Float, nullable=True) # product's effective cost at log time
|
unit_cost_snapshot = Column(Float, nullable=True) # product's effective cost at log time
|
||||||
total_cost = Column(Float, nullable=True) # unit_cost_snapshot * quantity
|
total_cost = Column(Float, nullable=True) # unit_cost_snapshot * quantity
|
||||||
reason = Column(String, nullable=False) # kitchen_error|dropped|expired|other
|
reason = Column(String, nullable=False) # kitchen_error|dropped|expired|other
|
||||||
reason_notes = Column(Text, nullable=True)
|
reason_notes = Column(Text, nullable=True)
|
||||||
logged_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
logged_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||||
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True)
|
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
||||||
logged_at = Column(UTCDateTime, default=utcnow)
|
logged_at = Column(UTCDateTime, default=utcnow)
|
||||||
|
|
||||||
product = relationship("Product", foreign_keys=[product_id])
|
product = relationship("Product", foreign_keys=[product_id])
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
||||||
from core.modules.model import Module, Mount, Perm
|
from core.modules.model import Module, Mount, Perm, SettingDef
|
||||||
|
|
||||||
MODULE = Module(
|
MODULE = Module(
|
||||||
key='caller_id',
|
key='caller_id',
|
||||||
kind='integration',
|
kind='integration',
|
||||||
name='Caller ID',
|
name='Caller ID',
|
||||||
description="Incoming phone calls from the venue's phone system (Grandstream UCM).",
|
description="Incoming phone calls from the venue's phone system (Grandstream UCM): who is calling, with their last orders.",
|
||||||
permissions=(
|
permissions=(
|
||||||
Perm('caller_id.use', 'See incoming calls', roles=('owner', 'store_manager', 'staff_manager')),
|
Perm('caller_id.use', 'See incoming calls', roles=('owner', 'store_manager', 'staff_manager')),
|
||||||
),
|
),
|
||||||
|
settings=(
|
||||||
|
SettingDef('caller_id.secret', '', 'Optional shared secret for the phone system webhook: when set, the UCM Action URL must add &key=<secret>. Plan step 3.5.', type='str'),
|
||||||
|
),
|
||||||
routers=(
|
routers=(
|
||||||
Mount('routers.phone', '/api/phone'),
|
Mount('routers.phone', '/api/phone'),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ MODULE = Module(
|
|||||||
),
|
),
|
||||||
routers=(
|
routers=(
|
||||||
Mount('routers.tables', '/api/tables'),
|
Mount('routers.tables', '/api/tables'),
|
||||||
|
Mount('routers.floor_plans', '/api/floor-plans'),
|
||||||
Mount('routers.products', '/api/products'),
|
Mount('routers.products', '/api/products'),
|
||||||
Mount('routers.prep_zones', '/api/prep-zones'),
|
Mount('routers.prep_zones', '/api/prep-zones'),
|
||||||
Mount('routers.data_transfer', '/api/data-transfer'),
|
Mount('routers.data_transfer', '/api/data-transfer'),
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
||||||
from core.modules.model import Module, Perm
|
from core.modules.model import Module, Mount, Perm, SettingDef
|
||||||
|
|
||||||
MODULE = Module(
|
MODULE = Module(
|
||||||
key='connect_menu',
|
key='connect_menu',
|
||||||
@@ -10,5 +10,11 @@ MODULE = Module(
|
|||||||
permissions=(
|
permissions=(
|
||||||
Perm('connect_menu.manage', 'Manage the QR menu', roles=('owner', 'store_manager')),
|
Perm('connect_menu.manage', 'Manage the QR menu', roles=('owner', 'store_manager')),
|
||||||
),
|
),
|
||||||
|
settings=(
|
||||||
|
SettingDef('connect_menu.table_ordering', 'false', 'The QR menu takes orders at the table (with a table QR code): "true" | "false" (read-only). Phase 3S, S.7.', type='bool'),
|
||||||
|
),
|
||||||
|
routers=(
|
||||||
|
Mount('routers.qr_codes', '/api/connect/qr'),
|
||||||
|
),
|
||||||
workers=('services.cloud_sync:menu_push_worker',),
|
workers=('services.cloud_sync:menu_push_worker',),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
||||||
from core.modules.model import Module, Mount, Perm
|
from core.modules.model import Module, Mount, Perm, SettingDef
|
||||||
|
|
||||||
MODULE = Module(
|
MODULE = Module(
|
||||||
key='connect_orders',
|
key='connect_orders',
|
||||||
@@ -8,10 +8,16 @@ MODULE = Module(
|
|||||||
description='Orders placed from the QR menu, pulled from the cloud.',
|
description='Orders placed from the QR menu, pulled from the cloud.',
|
||||||
depends=('ordering', 'connect_menu'),
|
depends=('ordering', 'connect_menu'),
|
||||||
permissions=(
|
permissions=(
|
||||||
Perm('connect_orders.manage', 'Accept and manage online orders', roles=('owner', 'store_manager', 'staff_manager')),
|
Perm('connect_orders.manage', 'Accept and manage online orders', roles=('owner', 'store_manager', 'staff_manager', 'barista', 'barman')),
|
||||||
|
Perm('connect_orders.fees', 'Set delivery areas and fees', roles=('owner', 'store_manager')),
|
||||||
|
),
|
||||||
|
settings=(
|
||||||
|
SettingDef('connect_orders.ordering', '{}', 'Online ordering (phase 3S): services offered, ordering hours, preparation and slot minutes, days ahead, as soon as possible. Edited on the Online ordering page.', type='json'),
|
||||||
),
|
),
|
||||||
routers=(
|
routers=(
|
||||||
|
Mount('routers.fees', '/api/connect/fees'),
|
||||||
Mount('routers.connect_orders', '/api/connect'),
|
Mount('routers.connect_orders', '/api/connect'),
|
||||||
),
|
),
|
||||||
workers=('services.cloud_sync:order_pull_worker',),
|
# S.6: bookings' food goes to the kitchen at its fire time
|
||||||
|
workers=('services.cloud_sync:order_pull_worker', 'services.online_reservations:fire_worker'),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ MODULE = Module(
|
|||||||
Perm('core.settings.manage', 'Change venue settings', roles=('owner',)),
|
Perm('core.settings.manage', 'Change venue settings', roles=('owner',)),
|
||||||
Perm('core.modules.manage', 'Turn apps, features and integrations on or off', roles=('owner',)),
|
Perm('core.modules.manage', 'Turn apps, features and integrations on or off', roles=('owner',)),
|
||||||
Perm('core.devices.manage', 'Pair, rename, reassign and remove devices', roles=('owner', 'store_manager')),
|
Perm('core.devices.manage', 'Pair, rename, reassign and remove devices', roles=('owner', 'store_manager')),
|
||||||
|
Perm('core.scenes.manage', 'Make scenes and turn them on or off', roles=('owner', 'store_manager')),
|
||||||
Perm('core.system.admin', 'Support-only maintenance (superadmin)', roles=()),
|
Perm('core.system.admin', 'Support-only maintenance (superadmin)', roles=()),
|
||||||
),
|
),
|
||||||
settings=(
|
settings=(
|
||||||
@@ -26,12 +27,16 @@ MODULE = Module(
|
|||||||
SettingDef('auth.default_login_mode', 'pin', "How staff log in on paired devices (KDS, counter POS) unless the device sets its own: 'pin' | 'password' | 'tap' | 'none'. Apps that can't use it fall back to their first mode.", type='enum', choices=('pin', 'password', 'tap', 'none')),
|
SettingDef('auth.default_login_mode', 'pin', "How staff log in on paired devices (KDS, counter POS) unless the device sets its own: 'pin' | 'password' | 'tap' | 'none'. Apps that can't use it fall back to their first mode.", type='enum', choices=('pin', 'password', 'tap', 'none')),
|
||||||
SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'),
|
SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'),
|
||||||
SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
||||||
SettingDef('auth.single_session_waiter', 'off', "One waiter session per user (no double login): 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
|
SettingDef('auth.single_session_waiter', 'ask', "One waiter session per user, phones only (no double login): 'off' | 'refuse_new' | 'end_old' | 'ask' (the default: the phone asks, yes signs the other one out)", type='enum', choices=('off', 'refuse_new', 'end_old', 'ask')),
|
||||||
|
SettingDef('auth.terminal_require_username', 'false', 'Paired screens (counter, KDS): type a username instead of picking a name; no names are listed, and "tap" is not used. A device can choose otherwise on the Devices page.', type='bool'),
|
||||||
SettingDef('auth.idle_days', '14', 'Sign people out after this many days without using the app (manager, waiter, paired-device sessions; support has its own 4 h). 0 = never.', type='int'),
|
SettingDef('auth.idle_days', '14', 'Sign people out after this many days without using the app (manager, waiter, paired-device sessions; support has its own 4 h). 0 = never.', type='int'),
|
||||||
SettingDef('system.log_retention_days', '30', 'Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.', type='int'),
|
SettingDef('system.log_retention_days', '30', 'Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.', type='int'),
|
||||||
SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'),
|
SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'),
|
||||||
SettingDef('venue.timezone', 'Europe/Athens', 'IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.', type='str'),
|
SettingDef('venue.timezone', 'Europe/Athens', 'IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.', type='str'),
|
||||||
SettingDef('venue.name', '', 'Venue name shown on screens and tickets.', type='str'),
|
SettingDef('venue.name', '', 'Venue name shown on screens and tickets.', type='str'),
|
||||||
|
SettingDef('venue.opening_hours', '{}', 'Opening hours, Monday first (6R.15; JSON {days, note}; edited on the Schedule page, shown by signage).', type='json'),
|
||||||
|
SettingDef('venue.identity', '{}', "The venue's identity (6R.14): slogan, colours, logos, Wi-Fi, contact details (JSON; Settings > Identity, routers/identity.py).", type='json'),
|
||||||
|
SettingDef('venue.theme', 'amber', "Accent colour of the staff apps (the waiter's phones first, plan step 4.6): 'teal' | 'amber' | 'blue' | 'violet' | 'rose', or 'identity' = the first colour of the venue's identity (6R.20: also the counter, KDS and tablets)", type='enum', choices=('teal', 'amber', 'blue', 'violet', 'rose', 'identity')),
|
||||||
SettingDef('venue.type', '', 'Kind of venue (restaurant, cafe, bar...), chosen in the setup wizard.', type='str'),
|
SettingDef('venue.type', '', 'Kind of venue (restaurant, cafe, bar...), chosen in the setup wizard.', type='str'),
|
||||||
SettingDef('venue.currency', 'EUR', 'ISO 4217 currency of all prices.', type='str'),
|
SettingDef('venue.currency', 'EUR', 'ISO 4217 currency of all prices.', type='str'),
|
||||||
),
|
),
|
||||||
@@ -41,12 +46,14 @@ MODULE = Module(
|
|||||||
Mount('routers.waiters', '/api/waiters'),
|
Mount('routers.waiters', '/api/waiters'),
|
||||||
Mount('routers.system', '/api/system'),
|
Mount('routers.system', '/api/system'),
|
||||||
Mount('routers.settings', '/api/settings'),
|
Mount('routers.settings', '/api/settings'),
|
||||||
Mount('routers.sse', '/api/sse'),
|
|
||||||
Mount('routers.ws', '/api/ws'),
|
Mount('routers.ws', '/api/ws'),
|
||||||
Mount('routers.recovery', '/api/recovery'),
|
Mount('routers.recovery', '/api/recovery'),
|
||||||
Mount('routers.devices', '/api/devices'),
|
Mount('routers.devices', '/api/devices'),
|
||||||
|
Mount('routers.media', '/api/media'),
|
||||||
Mount('routers.access', '/api/access'),
|
Mount('routers.access', '/api/access'),
|
||||||
Mount('routers.notifications', '/api/platform/notifications'),
|
Mount('routers.notifications', '/api/platform/notifications'),
|
||||||
|
Mount('routers.scenes', '/api/scenes'),
|
||||||
|
Mount('routers.identity', '/api/identity'),
|
||||||
Mount('core.modules.api', '/api/platform'),
|
Mount('core.modules.api', '/api/platform'),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,14 +1,23 @@
|
|||||||
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
||||||
from core.modules.model import DeviceApp, Limit, Module
|
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm
|
||||||
|
|
||||||
MODULE = Module(
|
MODULE = Module(
|
||||||
key='customer_display',
|
key='customer_display',
|
||||||
kind='app',
|
kind='app',
|
||||||
name='Customer display',
|
name='Customer display',
|
||||||
description='Screen facing the customer at a counter POS (phase 3).',
|
description='Screen facing the customer at a counter POS: the sale, the total, the change, and an idle screen (a look) the venue designs; each display can show its own (plan steps 3.4, 5.3).',
|
||||||
depends=('pos_counter',),
|
depends=('pos_counter',),
|
||||||
|
permissions=(
|
||||||
|
Perm('customer_display.manage', 'Set up the customer display (idle screen, images)', roles=('owner', 'store_manager')),
|
||||||
|
),
|
||||||
limits=(
|
limits=(
|
||||||
Limit('devices', 'Number of customer displays', free=0, licensed_default=1),
|
Limit('devices', 'Number of customer displays', free=0, licensed_default=1),
|
||||||
),
|
),
|
||||||
device_app=DeviceApp(login_modes=('none',), scope=()),
|
routers=(
|
||||||
|
Mount('routers.customer_display', '/api/display'),
|
||||||
|
),
|
||||||
|
device_app=DeviceApp(login_modes=('none',), scope=(), config=(
|
||||||
|
# Its idle screen: one of the venue's looks (Settings > Customer display); none = the default
|
||||||
|
ConfigField('look', 'ref', default=None, choices_from='display_looks'),
|
||||||
|
)),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ MODULE = Module(
|
|||||||
SettingDef('fiscal.eftpos_id', '1', "EFTPOS terminal ID sent in CD commands (integer string, e.g. '1')", type='int'),
|
SettingDef('fiscal.eftpos_id', '1', "EFTPOS terminal ID sent in CD commands (integer string, e.g. '1')", type='int'),
|
||||||
SettingDef('fiscal.enabled', 'false', "Master switch for fiscal printing: 'true' | 'false'", type='bool'),
|
SettingDef('fiscal.enabled', 'false', "Master switch for fiscal printing: 'true' | 'false'", type='bool'),
|
||||||
SettingDef('fiscal.end_message', '[]', 'JSON array of up to 5 strings printed at end of receipt via FM commands', type='json'),
|
SettingDef('fiscal.end_message', '[]', 'JSON array of up to 5 strings printed at end of receipt via FM commands', type='json'),
|
||||||
SettingDef('fiscal.in_folder', '', 'Path the backend reads fiscal reply files FROM (output of the fiscal driver)', type='json'),
|
SettingDef('fiscal.in_folder', '', 'Path the backend reads fiscal reply files FROM (output of the fiscal driver)', type='str'),
|
||||||
SettingDef('fiscal.out_folder', '', 'Path the backend writes fiscal command files TO (input for the fiscal driver)', type='json'),
|
SettingDef('fiscal.out_folder', '', 'Path the backend writes fiscal command files TO (input for the fiscal driver)', type='str'),
|
||||||
SettingDef('fiscal.type', 'txt_file', "Fiscal driver type: 'txt_file' (dTEC100extra) — more types coming", type='str'),
|
SettingDef('fiscal.type', 'txt_file', "Fiscal driver type: 'txt_file' (dTEC100extra) — more types coming", type='str'),
|
||||||
SettingDef('fiscal.vat_groups', '[]', 'JSON array of VAT group definitions: [{machine_id: int, friendly_name: str}]', type='json'),
|
SettingDef('fiscal.vat_groups', '[]', 'JSON array of VAT group definitions: [{machine_id: int, friendly_name: str}]', type='json'),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,5 +1,44 @@
|
|||||||
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
||||||
from core.modules.model import DeviceApp, Limit, Module, Mount, Perm
|
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm
|
||||||
|
|
||||||
|
# Back to the sign-in screen after this many idle minutes (shared screens; 0 = never). Used by
|
||||||
|
# the terminal from step 3.1c.
|
||||||
|
AUTO_SIGN_OUT = ConfigField('auto_sign_out_minutes', 'int', default=0, choices=(0, 2, 5, 10, 30, 60))
|
||||||
|
|
||||||
|
# A kitchen screen's settings (plan step 3.2a). They were the KDS page's localStorage settings
|
||||||
|
# (manager_dashboard KdsPage.jsx, `xenia_kds_settings_v2`); now they belong to the device, are
|
||||||
|
# edited on the Devices page or on the screen (PATCH /api/devices/me/config), and the screen
|
||||||
|
# reads them from GET /api/kds/context. prep_zone_id also scopes the backend: a KDS device
|
||||||
|
# with a zone only ever gets that zone's orders (routers/kds.py).
|
||||||
|
KDS_CONFIG = (
|
||||||
|
ConfigField('prep_zone_id', 'ref', default=None, choices_from='prep_zones', group='zone'),
|
||||||
|
# board
|
||||||
|
ConfigField('card_width', 'int', default=272, min=200, max=800, group='board'),
|
||||||
|
ConfigField('font_scale', 'int', default=100, min=60, max=200, group='board'),
|
||||||
|
ConfigField('font_weight', 'int', default=600, choices=(300, 400, 500, 600, 700, 800), group='board'),
|
||||||
|
ConfigField('batch_mode', 'enum', default='merged', choices=('merged', 'grouped', 'split'), group='board'),
|
||||||
|
ConfigField('group_items', 'enum', default='off',
|
||||||
|
choices=('off', 'floating', 'right_sidebar', 'left_sidebar', 'topbar_button'), group='board'),
|
||||||
|
ConfigField('group_by_course', 'bool', default=False, group='board'),
|
||||||
|
ConfigField('combine_modifiers', 'bool', default=False, group='board'),
|
||||||
|
ConfigField('categories_as_filters', 'bool', default=True, group='board'),
|
||||||
|
# how late an order is: minutes and colours
|
||||||
|
ConfigField('age_warning_minutes', 'int', default=5, min=1, max=120, group='age'),
|
||||||
|
ConfigField('age_late_minutes', 'int', default=10, min=2, max=120, after='age_warning_minutes', group='age'),
|
||||||
|
ConfigField('age_flash_minutes', 'int', default=15, min=3, max=120, after='age_late_minutes', group='age'),
|
||||||
|
ConfigField('flash_late', 'bool', default=True, group='age'),
|
||||||
|
ConfigField('colour_fresh', 'color', default='#34b56a', group='age'),
|
||||||
|
ConfigField('colour_warning', 'color', default='#f0a52a', group='age'),
|
||||||
|
ConfigField('colour_late', 'color', default='#e8513f', group='age'),
|
||||||
|
ConfigField('colour_done', 'color', default='#3d4757', group='age'),
|
||||||
|
# behaviour
|
||||||
|
ConfigField('triple_state', 'bool', default=False, group='behaviour'),
|
||||||
|
ConfigField('sound', 'bool', default=True, group='behaviour'),
|
||||||
|
ConfigField('notify_order_complete', 'bool', default=False, group='behaviour'),
|
||||||
|
ConfigField('notify_item_complete', 'bool', default=False, group='behaviour'),
|
||||||
|
ConfigField('refresh_seconds', 'int', default=30, choices=(10, 15, 20, 30, 45, 60, 90, 120), group='behaviour'),
|
||||||
|
AUTO_SIGN_OUT,
|
||||||
|
)
|
||||||
|
|
||||||
MODULE = Module(
|
MODULE = Module(
|
||||||
key='kds',
|
key='kds',
|
||||||
@@ -14,7 +53,7 @@ MODULE = Module(
|
|||||||
limits=(
|
limits=(
|
||||||
Limit('devices', 'Number of kitchen screens', free=0, licensed_default=1),
|
Limit('devices', 'Number of kitchen screens', free=0, licensed_default=1),
|
||||||
),
|
),
|
||||||
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('kds.*',)),
|
device_app=DeviceApp(login_modes=('pin', 'tap', 'password'), scope=('kds.*',), config=KDS_CONFIG),
|
||||||
routers=(
|
routers=(
|
||||||
Mount('routers.kds', '/api/kds'),
|
Mount('routers.kds', '/api/kds'),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
|
||||||
from core.modules.model import DeviceApp, Limit, Module, Perm
|
from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm, SettingDef
|
||||||
|
|
||||||
|
POINTS = ('in_store', 'in_store_takeaway', 'qr_table', 'online_takeaway', 'online_delivery', 'online_preorder', 'none')
|
||||||
|
|
||||||
MODULE = Module(
|
MODULE = Module(
|
||||||
key='menu_tablet',
|
key='menu_tablet',
|
||||||
kind='app',
|
kind='app',
|
||||||
name='Menu tablet',
|
name='Menu tablet',
|
||||||
description='Self-service catalogue on a tablet (phase 5).',
|
description="The venue's menu on a tablet: a quick price check for staff and a menu for guests (plan step 5.7a).",
|
||||||
depends=('catalog',),
|
depends=('catalog',),
|
||||||
permissions=(
|
permissions=(
|
||||||
Perm('menu_tablet.manage', 'Set up menu tablets', roles=('owner', 'store_manager')),
|
Perm('menu_tablet.manage', 'Set up menu tablets', roles=('owner', 'store_manager')),
|
||||||
@@ -13,5 +15,36 @@ MODULE = Module(
|
|||||||
limits=(
|
limits=(
|
||||||
Limit('devices', 'Number of menu tablets', free=0, licensed_default=1),
|
Limit('devices', 'Number of menu tablets', free=0, licensed_default=1),
|
||||||
),
|
),
|
||||||
device_app=DeviceApp(login_modes=('none',), scope=()),
|
routers=(
|
||||||
|
Mount('routers.menu_tablet', '/api/menu-tablet'),
|
||||||
|
),
|
||||||
|
# Ordering from a tablet at a table (6.6, D-30): the venue's rules, each overridable per tablet
|
||||||
|
settings=(
|
||||||
|
SettingDef('menu_tablet.ordering', '{}', 'Ordering from menu tablets at tables (plan step 6.6): confirm (kitchen | waiter), no_order (open | refuse), max_items, max_of_one, min_seconds. Edited in Settings > Menu tablets.', type='json'),
|
||||||
|
),
|
||||||
|
# How the menu looks on this tablet (owner 2026-11-17: views, photos, descriptions, grouping…)
|
||||||
|
device_app=DeviceApp(login_modes=('none',), scope=(), config=(
|
||||||
|
ConfigField('view', 'enum', default='expanded', choices=('compact', 'expanded', 'full'), group='look'),
|
||||||
|
ConfigField('photos', 'bool', default=True, group='look'),
|
||||||
|
ConfigField('descriptions', 'bool', default=True, group='look'),
|
||||||
|
ConfigField('group', 'bool', default=True, group='look'),
|
||||||
|
ConfigField('theme', 'enum', default='light', choices=('light', 'dark'), group='look'),
|
||||||
|
ConfigField('sales_point', 'enum', default='in_store', choices=POINTS, group='menu'),
|
||||||
|
ConfigField('sold_out', 'enum', default='strike', choices=('strike', 'hide'), group='menu'),
|
||||||
|
ConfigField('category', 'ref', default=None, choices_from='categories', group='menu'),
|
||||||
|
ConfigField('search', 'bool', default=True, group='use'),
|
||||||
|
ConfigField('languages', 'enum', default='both', choices=('both', 'el', 'en'), group='use'),
|
||||||
|
ConfigField('idle_seconds', 'int', default=120, choices=(0, 30, 60, 120, 300, 600), group='use'),
|
||||||
|
# A tablet on a table (5.7b): only then guests can call a waiter
|
||||||
|
ConfigField('table', 'ref', default=None, choices_from='tables', group='table'),
|
||||||
|
ConfigField('call_waiter', 'bool', default=True, group='table'),
|
||||||
|
# Guests order from it (6.6, D-30): off until the venue turns it on; the rest -1 / venue = the venue's setting
|
||||||
|
ConfigField('ordering', 'bool', default=False, group='order'),
|
||||||
|
ConfigField('bill', 'bool', default=True, group='order'),
|
||||||
|
ConfigField('order_confirm', 'enum', default='venue', choices=('venue', 'kitchen', 'waiter'), group='order'),
|
||||||
|
ConfigField('order_no_order', 'enum', default='venue', choices=('venue', 'open', 'refuse'), group='order'),
|
||||||
|
ConfigField('order_max_items', 'int', default=-1, choices=(-1, 5, 10, 15, 20, 30, 50), group='order'),
|
||||||
|
ConfigField('order_max_of_one', 'int', default=-1, choices=(-1, 1, 2, 3, 5, 10, 20), group='order'),
|
||||||
|
ConfigField('order_min_seconds', 'int', default=-1, choices=(-1, 0, 30, 60, 120, 300, 600), group='order'),
|
||||||
|
)),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -11,21 +11,38 @@ MODULE = Module(
|
|||||||
Perm('ordering.orders.open', 'Open orders and add items', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
|
Perm('ordering.orders.open', 'Open orders and add items', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
|
||||||
Perm('ordering.orders.close', 'Take payments and close orders', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
|
Perm('ordering.orders.close', 'Take payments and close orders', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
|
||||||
Perm('ordering.orders.cancel', 'Cancel items already sent', roles=('owner', 'store_manager'), overridable=True),
|
Perm('ordering.orders.cancel', 'Cancel items already sent', roles=('owner', 'store_manager'), overridable=True),
|
||||||
Perm('ordering.prices.modify', "Change an item's price", roles=('owner',), overridable=True),
|
Perm('ordering.prices.modify', "Change an item's price before it is sent", roles=('owner',), overridable=True),
|
||||||
|
Perm('ordering.prices.modify_sent', "Change the price of an item already sent or served", roles=('owner',), overridable=True),
|
||||||
|
Perm('ordering.items.change_quantity', "Change a sent line's quantity (no new ticket)", roles=('owner', 'store_manager'), overridable=True),
|
||||||
|
Perm('ordering.prices.view_changes', 'See the prices changed by hand (who, when, why)', roles=('owner', 'store_manager')),
|
||||||
|
Perm('ordering.refunds', 'Refund payments from other shifts', roles=('owner', 'store_manager'), overridable=True),
|
||||||
|
Perm('ordering.payments.revert', 'Turn paid items back to unpaid', roles=('owner', 'store_manager'), overridable=True),
|
||||||
|
Perm('ordering.payments.split_amount', 'Split a bill by amount (equal parts or a ratio)', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter'), overridable=True),
|
||||||
Perm('ordering.business_day.manage', 'Open and close the business day', roles=('owner', 'store_manager', 'staff_manager')),
|
Perm('ordering.business_day.manage', 'Open and close the business day', roles=('owner', 'store_manager', 'staff_manager')),
|
||||||
),
|
),
|
||||||
settings=(
|
settings=(
|
||||||
SettingDef('business_day.force_close_allowed', 'true', 'Allow force-closing business day with open tables', type='bool'),
|
SettingDef('business_day.force_close_allowed', 'true', 'Allow force-closing business day with open tables', type='bool'),
|
||||||
|
SettingDef('business_day.auto_open', 'off', "The day opens by itself (6F.8): 'off' | 'schedule' (at the opening hours) | 'time' (every day at business_day.auto_open_time) | 'alert' (at the opening hours, only tell the managers)", type='enum', choices=('off', 'schedule', 'time', 'alert')),
|
||||||
|
SettingDef('business_day.auto_close', 'off', "The day closes by itself (6F.8): 'off' | 'schedule' | 'time' | 'alert'. Closes only when every order of the day is closed; otherwise the managers are alerted and it tries again every 15 minutes.", type='enum', choices=('off', 'schedule', 'time', 'alert')),
|
||||||
|
SettingDef('business_day.auto_open_time', '09:00', "HH:MM venue time, for business_day.auto_open = 'time' (6F.8).", type='str'),
|
||||||
|
SettingDef('business_day.auto_close_time', '23:30', "HH:MM venue time, for business_day.auto_close = 'time' (6F.8).", type='str'),
|
||||||
|
SettingDef('business_day.auto_ignore_break', 'true', "A day's opening spans count as one (first opening to last closing); 'false' = the break between spans closes the day and the next span opens a new one (6F.8).", type='bool'),
|
||||||
|
SettingDef('business_day.auto_open_offset_min', '0', 'Open this many minutes before the opening hours start (6F.8, 0-720).', type='int'),
|
||||||
|
SettingDef('business_day.auto_close_offset_min', '0', 'Close this many minutes after the opening hours end (6F.8, 0-720).', type='int'),
|
||||||
SettingDef('business_day.rollover_hour', '6', 'Hour (0-23, venue time) before which a newly opened business day counts as the previous date. Default 6.', type='int'),
|
SettingDef('business_day.rollover_hour', '6', 'Hour (0-23, venue time) before which a newly opened business day counts as the previous date. Default 6.', type='int'),
|
||||||
SettingDef('orders.auto_close_on_full_payment', 'false', "Automatically close the table order when all items have been paid: 'true' | 'false'", type='bool'),
|
SettingDef('orders.auto_close_on_full_payment', 'false', "Automatically close the table order when all items have been paid: 'true' | 'false'", type='bool'),
|
||||||
|
SettingDef('orders.close_with_unpaid', 'false', "Allow closing an order that still has unpaid items (they are written off as unpaid): 'true' | 'false'. When 'false', closing asks for the payment first (plan step 4.8).", type='bool'),
|
||||||
SettingDef('orders.bypass_kds_serve', 'false', "Skip KDS pending/serve flow — new orders and items are immediately marked as served: 'true' | 'false'", type='bool'),
|
SettingDef('orders.bypass_kds_serve', 'false', "Skip KDS pending/serve flow — new orders and items are immediately marked as served: 'true' | 'false'", type='bool'),
|
||||||
|
SettingDef('orders.quantity_change', 'off', "Changing a sent line's quantity without sending it again (6F.5): 'off' | 'add_only' | 'add_and_remove' (lowering cancels the difference; also needs ordering.orders.cancel). Who may: ordering.items.change_quantity.", type='enum', choices=('off', 'add_only', 'add_and_remove')),
|
||||||
|
SettingDef('orders.price_change', 'anytime', "Changing a line's price by hand (6F.3): 'off' | 'before_sending' (only in the cart) | 'anytime' (also a sent or served line). Who may: the keys ordering.prices.modify / modify_sent.", type='enum', choices=('off', 'before_sending', 'anytime')),
|
||||||
|
SettingDef('orders.price_change_reason', 'false', "A price changed by hand needs a reason: 'true' | 'false' (6F.3).", type='bool'),
|
||||||
|
SettingDef('orders.price_change_reasons', '[]', 'JSON array of quick reasons offered when a price is changed by hand (6F.3); [] = the built-in ones.', type='json'),
|
||||||
SettingDef('orders.courses', '[]', 'JSON array of course objects [{id, name, color}] defining available courses', type='json'),
|
SettingDef('orders.courses', '[]', 'JSON array of course objects [{id, name, color}] defining available courses', type='json'),
|
||||||
SettingDef('orders.courses_enabled', 'false', "Enable per-item course assignment when ordering: 'true' | 'false'", type='bool'),
|
SettingDef('orders.courses_enabled', 'false', "Enable per-item course assignment when ordering: 'true' | 'false'", type='bool'),
|
||||||
SettingDef('orders.quick_notes', '["Χωρίς αλάτι","Βγάλτε γρήγορα","Αλλεργία!","Κόψτε σε μικρά κομμάτια","Έξτρα χαρτοπετσέτες"]', 'JSON array of quick-note strings shown in the waiter note tab', type='json'),
|
SettingDef('orders.quick_notes', '["Χωρίς αλάτι","Βγάλτε γρήγορα","Αλλεργία!","Κόψτε σε μικρά κομμάτια","Έξτρα χαρτοπετσέτες"]', 'JSON array of quick-note strings shown in the waiter note tab', type='json'),
|
||||||
SettingDef('orders.waiter_cancellations_allowed', 'true', "Allow waiters with per-account permission to cancel sent orders: 'true' | 'false'", type='bool'),
|
SettingDef('payments.split_amount', 'off', "Splitting a bill by amount (6F.6), each level with the ones before: 'off' | 'two_equal' (half and half) | 'two_custom' (two parts in any ratio) | 'multiple_equal' (2 to payments.split_max_parts equal parts). Who may: ordering.payments.split_amount.", type='enum', choices=('off', 'two_equal', 'two_custom', 'multiple_equal')),
|
||||||
SettingDef('orders.waiter_price_adjust_allowed', 'false', "Allow waiters to adjust item prices (before or after ordering): 'true' | 'false'", type='bool'),
|
SettingDef('payments.split_max_parts', '10', 'The most equal parts a bill can be split into (6F.6, 2-50).', type='int'),
|
||||||
SettingDef('payments.card_enabled', 'false', "Allow waiters to record card payments (in addition to cash): 'true' | 'false'", type='bool'),
|
SettingDef('payments.card_enabled', 'false', "Allow waiters to record card payments (in addition to cash): 'true' | 'false'", type='bool'),
|
||||||
SettingDef('payments.waiter_revert_allowed', 'false', "Allow waiters to revert individual paid items back to unpaid: 'true' | 'false'", type='bool'),
|
|
||||||
SettingDef('print.alert_after_failures', '2', 'Tell managers when a kitchen/bar ticket has failed to print this many times and is still retrying (0 = never; they are always told when a ticket is finally given up).', type='int'),
|
SettingDef('print.alert_after_failures', '2', 'Tell managers when a kitchen/bar ticket has failed to print this many times and is still retrying (0 = never; they are always told when a ticket is finally given up).', type='int'),
|
||||||
SettingDef('print.beep_on_ticket', 'true', "Play beep when a kitchen ticket prints: 'true' | 'false'", type='bool'),
|
SettingDef('print.beep_on_ticket', 'true', "Play beep when a kitchen ticket prints: 'true' | 'false'", type='bool'),
|
||||||
SettingDef('print.beep_pattern', 'double', "Beep pattern: 'single' | 'double' | 'triple' | 'long' | 'custom:n1:n2:n3'", type='str'),
|
SettingDef('print.beep_pattern', 'double', "Beep pattern: 'single' | 'double' | 'triple' | 'long' | 'custom:n1:n2:n3'", type='str'),
|
||||||
@@ -51,5 +68,6 @@ MODULE = Module(
|
|||||||
Mount('routers.business_day', '/api/business-day'),
|
Mount('routers.business_day', '/api/business-day'),
|
||||||
Mount('routers.shifts', '/api/shifts'),
|
Mount('routers.shifts', '/api/shifts'),
|
||||||
Mount('routers.flags', '/api/flags'),
|
Mount('routers.flags', '/api/flags'),
|
||||||
|
Mount('routers.print_problems', '/api/print-problems'), # 6.10
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user