Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
+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.
|
||||
+7
-2
File diff suppressed because one or more lines are too long
@@ -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)
|
||||
@@ -110,6 +110,7 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"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."),
|
||||
@@ -125,6 +126,7 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"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."),
|
||||
@@ -198,6 +200,15 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"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."),
|
||||
@@ -210,6 +221,15 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"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."),
|
||||
"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."),
|
||||
|
||||
@@ -1,4 +1,21 @@
|
||||
"""The menu in other languages (plan step 6.4, owner decisions 2026-11-18, D-29).
|
||||
"""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
|
||||
@@ -89,8 +106,11 @@ def texts(base: str | None, translations: dict, field: str) -> dict:
|
||||
return {lang: (translations.get(lang) or {}).get(field) or base for lang in MENU_LANGUAGES}
|
||||
|
||||
|
||||
def quick_texts(base: str, translations: dict) -> dict:
|
||||
return {lang: ((translations.get(lang) or {}).get("quick") or {}).get(base) 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:
|
||||
@@ -100,3 +120,28 @@ def product_texts(product, customer: bool = True) -> dict:
|
||||
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}
|
||||
|
||||
@@ -38,6 +38,22 @@ router = APIRouter()
|
||||
_optional_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
def _identity_brief(db) -> dict:
|
||||
"""What every app needs of the venue's identity (6R.20): its first colour (the accent when
|
||||
venue.theme is "identity"), the slogan and the logos' addresses. Public, like the venue's name."""
|
||||
try:
|
||||
from routers.identity import identity_out
|
||||
ident = identity_out(db)
|
||||
except Exception:
|
||||
return {"colour": None, "slogan": None, "logo": None, "logo_light": None, "logo_dark": None, "icon": None}
|
||||
logos = ident.get("logos") or {}
|
||||
|
||||
def card(k):
|
||||
return (logos.get(k) or {}).get("card")
|
||||
return {"colour": (ident.get("colours") or [{}])[0].get("colour"), "slogan": ident.get("slogan"),
|
||||
"logo": card("main"), "logo_light": card("light"), "logo_dark": card("dark"), "icon": (logos.get("icon") or {}).get("thumb")}
|
||||
|
||||
|
||||
def permission_keys_for(user) -> list[str]:
|
||||
"""The keys a user holds (user_permissions; superadmin: every key)."""
|
||||
from core.access.check import user_keys
|
||||
@@ -113,6 +129,7 @@ def bootstrap(
|
||||
"language": i18n.venue_language(),
|
||||
"currency": _setting(db, "venue.currency", "EUR"),
|
||||
"theme": _setting(db, "venue.theme", "amber") or "amber", # the accent colour (4.6, data-venue-theme)
|
||||
"identity": _identity_brief(db), # 6R.20: its colour and logos for the apps
|
||||
"business_day_rollover_hour": timeutil.rollover_hour(),
|
||||
},
|
||||
"modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective],
|
||||
|
||||
@@ -55,13 +55,13 @@ def _ref_exists(source: str, value: int, db) -> bool:
|
||||
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 == "signage_schedules":
|
||||
from models.signage import SignageSchedule
|
||||
return db.get(SignageSchedule, value) is not None
|
||||
if source == "display_looks":
|
||||
from models.display_look import DisplayLook
|
||||
return db.get(DisplayLook, value) is not None
|
||||
|
||||
@@ -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')
|
||||
@@ -40,6 +40,7 @@ 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 (signage, step 5.4a)
|
||||
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)
|
||||
|
||||
@@ -32,8 +32,8 @@ class ConversationParticipant(Base):
|
||||
__tablename__ = "conversation_participants"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||
joined_at = Column(UTCDateTime, default=utcnow)
|
||||
last_read_at = Column(UTCDateTime, nullable=True)
|
||||
|
||||
@@ -45,7 +45,7 @@ class ChatMessage(Base):
|
||||
__tablename__ = "chat_messages"
|
||||
|
||||
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)
|
||||
body = Column(Text, nullable=False)
|
||||
sent_at = Column(UTCDateTime, default=utcnow)
|
||||
|
||||
@@ -28,11 +28,11 @@ class Expense(Base):
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
description = Column(String, nullable=False)
|
||||
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)
|
||||
paid_amount = Column(Float, default=0.0, nullable=False)
|
||||
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_at = Column(UTCDateTime, default=utcnow)
|
||||
notes = Column(Text, nullable=True)
|
||||
@@ -40,13 +40,18 @@ class Expense(Base):
|
||||
contact = relationship("Contact", back_populates="expenses")
|
||||
created_by = relationship("User", foreign_keys=[created_by_id])
|
||||
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):
|
||||
__tablename__ = "expense_payments"
|
||||
|
||||
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)
|
||||
paid_at = Column(UTCDateTime, default=utcnow)
|
||||
paid_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
@@ -54,3 +59,37 @@ class ExpensePayment(Base):
|
||||
|
||||
expense = relationship("Expense", back_populates="payments")
|
||||
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])
|
||||
|
||||
@@ -54,5 +54,6 @@ class FloorItem(Base):
|
||||
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")
|
||||
|
||||
@@ -39,9 +39,21 @@ class Media(Base):
|
||||
# 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"
|
||||
|
||||
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)
|
||||
acked_at = Column(UTCDateTime, default=utcnow)
|
||||
|
||||
|
||||
@@ -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 sqlalchemy.orm import relationship
|
||||
from database import Base
|
||||
@@ -8,16 +8,18 @@ from database import Base
|
||||
|
||||
class Order(Base):
|
||||
__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)
|
||||
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_at = Column(UTCDateTime, default=utcnow)
|
||||
status = Column(String, default="open", nullable=False) # open|partially_paid|paid|closed|cancelled
|
||||
opened_at = Column(UTCDateTime, default=utcnow, index=True)
|
||||
status = Column(String, default="open", nullable=False, index=True) # open|partially_paid|paid|closed|cancelled
|
||||
closed_at = Column(UTCDateTime, nullable=True)
|
||||
closed_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||
notes = Column(Text, nullable=True)
|
||||
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True)
|
||||
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
|
||||
# KDS
|
||||
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done
|
||||
kds_status_changed_at = Column(UTCDateTime, nullable=True)
|
||||
@@ -41,7 +43,7 @@ class Order(Base):
|
||||
# when the customer wants it (S.5); NULL = as soon as possible
|
||||
requested_for = Column(UTCDateTime, nullable=True)
|
||||
# Phase 2F — customer CRM
|
||||
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=True)
|
||||
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=True, index=True)
|
||||
|
||||
# Number of customers at the table for this order
|
||||
customer_count = Column(Integer, nullable=True)
|
||||
@@ -53,7 +55,7 @@ class Order(Base):
|
||||
opener = relationship("User", foreign_keys=[opened_by], back_populates="orders_opened")
|
||||
closer = relationship("User", foreign_keys=[closed_by], back_populates="orders_closed")
|
||||
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")
|
||||
print_logs = relationship("PrintLog", back_populates="order", cascade="all, delete-orphan")
|
||||
print_jobs = relationship("PrintJob", back_populates="order", cascade="all, delete-orphan")
|
||||
@@ -65,8 +67,8 @@ class OrderWaiter(Base):
|
||||
__tablename__ = "order_waiters"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
|
||||
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
||||
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||
assigned_at = Column(UTCDateTime, default=utcnow)
|
||||
|
||||
order = relationship("Order", back_populates="waiters")
|
||||
@@ -75,10 +77,12 @@ class OrderWaiter(Base):
|
||||
|
||||
class OrderItem(Base):
|
||||
__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)
|
||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False)
|
||||
product_id = Column(Integer, ForeignKey("products.id"), nullable=False)
|
||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
|
||||
product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
|
||||
added_by = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
quantity = Column(Float, nullable=False)
|
||||
unit_price = Column(Float, nullable=False) # price snapshot at time of order
|
||||
@@ -92,7 +96,7 @@ class OrderItem(Base):
|
||||
selected_options = Column(Text, nullable=True) # JSON array of option ids
|
||||
removed_ingredients = Column(Text, nullable=True) # JSON array of ingredient ids
|
||||
notes = Column(Text, nullable=True)
|
||||
status = Column(String, default="active", nullable=False) # active|paid|cancelled
|
||||
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
|
||||
added_at = Column(UTCDateTime, default=utcnow)
|
||||
printed = Column(Boolean, default=False, nullable=False)
|
||||
@@ -101,7 +105,7 @@ class OrderItem(Base):
|
||||
paid_by = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||
paid_at = Column(UTCDateTime, nullable=True)
|
||||
payment_method = Column(String, nullable=True) # 'cash'|'card'|'other' — future use
|
||||
paid_in_shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True)
|
||||
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)
|
||||
unit_cost = Column(Float, nullable=True)
|
||||
@@ -129,6 +133,9 @@ class OrderItem(Base):
|
||||
# Deal binding — which deal created this item, and which original item it's linked to
|
||||
deal_id = Column(Integer, ForeignKey("deals.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)
|
||||
|
||||
order = relationship("Order", back_populates="items")
|
||||
product = relationship("Product", back_populates="order_items")
|
||||
@@ -150,7 +157,7 @@ class PrintLog(Base):
|
||||
__tablename__ = "print_log"
|
||||
|
||||
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)
|
||||
printed_at = Column(UTCDateTime, default=utcnow)
|
||||
item_ids = Column(Text, nullable=False) # JSON array of order_item ids
|
||||
@@ -169,7 +176,7 @@ class PrintJob(Base):
|
||||
__tablename__ = "print_jobs"
|
||||
|
||||
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)
|
||||
zone_id = Column(Integer, nullable=True) # prep zone id, NULL for legacy
|
||||
item_ids = Column(Text, nullable=False) # JSON array of order_item ids
|
||||
@@ -194,7 +201,7 @@ class OrderAuditLog(Base):
|
||||
__tablename__ = "order_audit_log"
|
||||
|
||||
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)
|
||||
# ORDER_OPENED | ITEMS_ADDED | PAYMENT | PAYMENT_OFFLINE | ORDER_CLOSED | ORDER_CANCELLED | ITEM_CANCELLED
|
||||
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=True)
|
||||
@@ -221,7 +228,7 @@ class OrderDiscount(Base):
|
||||
__tablename__ = "order_discounts"
|
||||
|
||||
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
|
||||
discount_type = Column(String, nullable=False) # 'percent' | 'fixed'
|
||||
discount_value = Column(Float, nullable=False) # e.g. 10.0 = 10% or €10.00
|
||||
@@ -257,3 +264,34 @@ def _snapshot_item_names(session, flush_context, instances):
|
||||
cat = session.get(Category, obj.category_id)
|
||||
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")
|
||||
|
||||
@@ -12,4 +12,4 @@ class PhoneCall(Base):
|
||||
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)
|
||||
customer_id = Column(Integer, ForeignKey("customers.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||
|
||||
@@ -91,6 +91,7 @@ class PriceModifierCondition(Base):
|
||||
min_order_value {"min": 0.00} (cart total before modifiers)
|
||||
order_channel {"channels": [sales point, ...]} (core/sales_points.py; phase 3S)
|
||||
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)
|
||||
low_stock {"threshold": N} (placeholder, needs inventory)
|
||||
"""
|
||||
@@ -98,7 +99,7 @@ class PriceModifierCondition(Base):
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"),
|
||||
nullable=False)
|
||||
nullable=False, index=True)
|
||||
condition_type = Column(String, nullable=False)
|
||||
params = Column(Text, nullable=False, default="{}") # JSON
|
||||
|
||||
@@ -120,7 +121,7 @@ class PriceModifierTarget(Base):
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
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_id = Column(Integer, nullable=True) # legacy single value
|
||||
target_tag = Column(String, nullable=True) # legacy single value
|
||||
@@ -180,7 +181,7 @@ class DealCondition(Base):
|
||||
__tablename__ = "deal_conditions"
|
||||
|
||||
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)
|
||||
params = Column(Text, nullable=False, default="{}") # JSON
|
||||
|
||||
@@ -195,7 +196,7 @@ class DealTarget(Base):
|
||||
__tablename__ = "deal_targets"
|
||||
|
||||
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_id = Column(Integer, 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
|
||||
# waiter_discount — manual waiter discount applied
|
||||
# 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)
|
||||
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
|
||||
@@ -235,10 +237,15 @@ class PriceEventLog(Base):
|
||||
price_after = Column(Float, nullable=True)
|
||||
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)
|
||||
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.
|
||||
# JSON object: {"condition_type": evaluated_value, ...}
|
||||
# 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])
|
||||
deal = relationship("Deal", foreign_keys=[deal_id])
|
||||
applied_by = relationship("User", foreign_keys=[applied_by_user_id])
|
||||
approved_by = relationship("User", foreign_keys=[approved_by_user_id])
|
||||
|
||||
|
||||
class WaiterDiscountSettings(Base):
|
||||
@@ -280,3 +288,23 @@ class WaiterDiscountSettings(Base):
|
||||
max_items_per_order = Column(Integer, nullable=True)
|
||||
|
||||
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)
|
||||
|
||||
@@ -82,6 +82,8 @@ class Product(Base):
|
||||
|
||||
# Quick Add: allow adding 1 unit directly from product list without opening config modal
|
||||
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.)
|
||||
is_service_item = Column(Boolean, default=False, nullable=False)
|
||||
@@ -135,11 +137,13 @@ class ProductModifierGroup(Base):
|
||||
__tablename__ = "product_modifier_groups"
|
||||
|
||||
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"
|
||||
modifier_type = Column(String, nullable=False)
|
||||
name = Column(String, 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")
|
||||
|
||||
@@ -148,7 +152,7 @@ class ProductOption(Base):
|
||||
__tablename__ = "product_options"
|
||||
|
||||
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)
|
||||
extra_cost = Column(Float, default=0.0)
|
||||
allow_multiple = Column(Boolean, default=False, nullable=False)
|
||||
@@ -162,6 +166,8 @@ class ProductOption(Base):
|
||||
is_compact = Column(Boolean, default=False, nullable=False)
|
||||
# Optional group/folder this option belongs to
|
||||
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")
|
||||
|
||||
@@ -170,7 +176,7 @@ class ProductQuickOption(Base):
|
||||
__tablename__ = "product_quick_options"
|
||||
|
||||
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)
|
||||
price = Column(Float, default=0.0, nullable=False)
|
||||
allow_multiple = Column(Boolean, default=False, nullable=False)
|
||||
@@ -178,6 +184,8 @@ class ProductQuickOption(Base):
|
||||
is_favorite = Column(Boolean, default=False, nullable=False)
|
||||
favorite_sort_order = Column(Integer, default=0, 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")
|
||||
|
||||
@@ -186,7 +194,7 @@ class ProductIngredient(Base):
|
||||
__tablename__ = "product_ingredients"
|
||||
|
||||
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)
|
||||
extra_cost = Column(Float, default=0.0)
|
||||
is_favorite = Column(Boolean, default=False, nullable=False)
|
||||
@@ -195,6 +203,8 @@ class ProductIngredient(Base):
|
||||
is_compact = Column(Boolean, default=False, nullable=False)
|
||||
# Optional group/folder this ingredient belongs to
|
||||
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")
|
||||
|
||||
@@ -203,7 +213,7 @@ class ProductPreferenceSet(Base):
|
||||
__tablename__ = "product_preference_sets"
|
||||
|
||||
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)
|
||||
default_choice_id = Column(Integer, nullable=True)
|
||||
# JSON: {name, default_choice_index, choices:[{name,extra_cost,is_default}]}
|
||||
@@ -217,6 +227,8 @@ class ProductPreferenceSet(Base):
|
||||
allow_multi_select = Column(Boolean, default=False, nullable=False)
|
||||
# When True, each selected choice can have a quantity (x2, x3, …)
|
||||
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")
|
||||
choices = relationship("ProductPreferenceChoice", back_populates="set", cascade="all, delete-orphan")
|
||||
@@ -226,7 +238,7 @@ class ProductPreferenceChoice(Base):
|
||||
__tablename__ = "product_preference_choices"
|
||||
|
||||
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)
|
||||
extra_cost = Column(Float, default=0.0)
|
||||
# JSON array of sub-choice objects: [{name, extra_cost, is_default, is_compact}]
|
||||
@@ -236,6 +248,8 @@ class ProductPreferenceChoice(Base):
|
||||
disables_subset = Column(Boolean, default=False, nullable=False)
|
||||
# When True renders as half-width card on the PWA
|
||||
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")
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ class Reservation(Base):
|
||||
reserved_for = Column(UTCDateTime, nullable=False)
|
||||
|
||||
# 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 (confirmed, upcoming) | arrived | cancelled | no_show;
|
||||
# online requests (phase 3S, S.6) start as requested → pending (confirmed) | declined
|
||||
@@ -43,7 +43,7 @@ class Reservation(Base):
|
||||
total = Column(Float, nullable=True)
|
||||
online_price_diff = Column(Text, nullable=True) # services/online_check.py; NULL = matched
|
||||
fire_at = Column(UTCDateTime, nullable=True) # when the kitchen gets the food (set on confirming)
|
||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=True) # created at fire time
|
||||
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)
|
||||
|
||||
@@ -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"
|
||||
|
||||
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)
|
||||
start_time = Column(String, nullable=False) # "HH:MM" stored as string (SQLite has no Time type)
|
||||
end_time = Column(String, nullable=False)
|
||||
|
||||
@@ -10,8 +10,8 @@ class WaiterShift(Base):
|
||||
__tablename__ = "waiter_shifts"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=False)
|
||||
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=False, index=True)
|
||||
started_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||
ended_at = Column(UTCDateTime, nullable=True)
|
||||
starting_cash = Column(Float, nullable=True)
|
||||
@@ -32,7 +32,7 @@ class ShiftBreak(Base):
|
||||
__tablename__ = "shift_breaks"
|
||||
|
||||
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)
|
||||
ended_at = Column(UTCDateTime, nullable=True)
|
||||
|
||||
|
||||
@@ -6,8 +6,9 @@ a text, with its time on screen, its transition and when it may show (days, hour
|
||||
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 the playlist in its device config (`playlist`), in its own
|
||||
orientation and rotation (modules/signage/manifest.py).
|
||||
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
|
||||
@@ -22,6 +23,7 @@ class SignagePlaylist(Base):
|
||||
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)
|
||||
@@ -53,15 +55,54 @@ class SignageSlide(Base):
|
||||
playlist = relationship("SignagePlaylist", back_populates="slides")
|
||||
|
||||
|
||||
class SignageSchedule(Base):
|
||||
"""Which playlist plays when (5.4d): entries matched in venue time (services/signage_schedule.py),
|
||||
the fallback when none matches. A screen with a schedule plays it instead of a single playlist."""
|
||||
__tablename__ = "signage_schedules"
|
||||
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)
|
||||
fallback_playlist_id = Column(Integer, ForeignKey("signage_playlists.id", ondelete="SET NULL"), nullable=True)
|
||||
# [{playlist_id, days, time_from, time_to, date_from, date_to, priority}]
|
||||
entries = Column(JSON, nullable=False, default=list)
|
||||
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)
|
||||
|
||||
@@ -22,7 +22,7 @@ class Table(Base):
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
number = Column(Integer, nullable=False)
|
||||
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)
|
||||
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
|
||||
|
||||
@@ -23,7 +23,7 @@ class TabletOrder(Base):
|
||||
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)
|
||||
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)
|
||||
|
||||
@@ -10,7 +10,7 @@ class Tab(Base):
|
||||
__tablename__ = "tabs"
|
||||
|
||||
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
|
||||
opened_at = Column(UTCDateTime, default=utcnow)
|
||||
closed_at = Column(UTCDateTime, nullable=True)
|
||||
@@ -28,9 +28,9 @@ class TabEntry(Base):
|
||||
__tablename__ = "tab_entries"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False)
|
||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=True)
|
||||
order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True)
|
||||
tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False, index=True)
|
||||
order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=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
|
||||
description = Column(Text, nullable=True) # auto-generated summary
|
||||
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
@@ -48,7 +48,7 @@ class TabPayment(Base):
|
||||
__tablename__ = "tab_payments"
|
||||
|
||||
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)
|
||||
payment_method = Column(String, nullable=True) # cash | card | other
|
||||
received_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
|
||||
@@ -10,14 +10,14 @@ class WasteLog(Base):
|
||||
__tablename__ = "waste_log"
|
||||
|
||||
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
|
||||
unit_cost_snapshot = Column(Float, nullable=True) # product's effective cost at log time
|
||||
total_cost = Column(Float, nullable=True) # unit_cost_snapshot * quantity
|
||||
reason = Column(String, nullable=False) # kitchen_error|dropped|expired|other
|
||||
reason_notes = Column(Text, nullable=True)
|
||||
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)
|
||||
|
||||
product = relationship("Product", foreign_keys=[product_id])
|
||||
|
||||
@@ -12,6 +12,7 @@ MODULE = Module(
|
||||
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.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=()),
|
||||
),
|
||||
settings=(
|
||||
@@ -32,7 +33,9 @@ MODULE = Module(
|
||||
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.name', '', 'Venue name shown on screens and tickets.', type='str'),
|
||||
SettingDef('venue.theme', 'amber', "Accent colour of the staff apps (the waiter's phones first, plan step 4.6): 'teal' | 'amber' | 'blue' | 'violet' | 'rose'", type='enum', choices=('teal', 'amber', 'blue', 'violet', 'rose')),
|
||||
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.currency', 'EUR', 'ISO 4217 currency of all prices.', type='str'),
|
||||
),
|
||||
@@ -48,6 +51,8 @@ MODULE = Module(
|
||||
Mount('routers.media', '/api/media'),
|
||||
Mount('routers.access', '/api/access'),
|
||||
Mount('routers.notifications', '/api/platform/notifications'),
|
||||
Mount('routers.scenes', '/api/scenes'),
|
||||
Mount('routers.identity', '/api/identity'),
|
||||
Mount('core.modules.api', '/api/platform'),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -11,7 +11,10 @@ MODULE = Module(
|
||||
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.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.business_day.manage', 'Open and close the business day', roles=('owner', 'store_manager', 'staff_manager')),
|
||||
@@ -22,6 +25,10 @@ MODULE = Module(
|
||||
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.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_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'),
|
||||
|
||||
@@ -17,6 +17,7 @@ MODULE = Module(
|
||||
),
|
||||
settings=(
|
||||
SettingDef('signage.message', '', 'The message of the day on every signage screen with a message widget (Signage > Message of the day).'),
|
||||
SettingDef('signage.reviews', '[]', 'The reviews the venue typed in for the reviews widget (6R.19; JSON list; Signage > Message & settings).', type='json'),
|
||||
SettingDef('signage.weather.place', '', 'The place whose weather the screens show (picked from a town search in Signage).'),
|
||||
SettingDef('signage.weather.latitude', '', 'Latitude of the weather place.'),
|
||||
SettingDef('signage.weather.longitude', '', 'Longitude of the weather place.'),
|
||||
@@ -27,9 +28,17 @@ MODULE = Module(
|
||||
device_app=DeviceApp(login_modes=('none',), scope=(), config=(
|
||||
# What it plays and how the TV hangs (5.4a); the editor builds for the screen's shape
|
||||
ConfigField('playlist', 'ref', default=None, choices_from='signage_playlists'),
|
||||
# or a schedule: which playlist plays when (5.4d); it wins over the single playlist
|
||||
ConfigField('schedule', 'ref', default=None, choices_from='signage_schedules'),
|
||||
# ... or a library slide shown alone (owner 2026-11-21; a playlist wins when both are set)
|
||||
ConfigField('slide', 'ref', default=None, choices_from='signage_slides'),
|
||||
ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')),
|
||||
ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)),
|
||||
# its picture (6R.13): a slide of another shape keeps its shape (bands) or fills the picture;
|
||||
# px cut off each edge of the TV's window (set by Signage > Screens > Calibrate); below 0 the
|
||||
# picture reaches past that edge of the window the TV reported (owner 2026-11-23)
|
||||
ConfigField('fit', 'enum', default='keep', choices=('keep', 'stretch'), group='picture'),
|
||||
ConfigField('area_left', 'int', default=0, min=-2000, max=4000, group='picture'),
|
||||
ConfigField('area_top', 'int', default=0, min=-2000, max=4000, group='picture'),
|
||||
ConfigField('area_right', 'int', default=0, min=-2000, max=4000, group='picture'),
|
||||
ConfigField('area_bottom', 'int', default=0, min=-2000, max=4000, group='picture'),
|
||||
)),
|
||||
)
|
||||
|
||||
@@ -64,6 +64,7 @@ class IdleBody(BaseModel):
|
||||
qr_url: Optional[str] = Field(default=None, max_length=300)
|
||||
qr_caption: Optional[str] = Field(default=None, max_length=80)
|
||||
theme: Literal["dark", "light"] = "dark"
|
||||
brand: Literal["own", "identity"] = "own" # 6R.20: the venue's identity: its colour as the accent, its logo when the look has none
|
||||
|
||||
@field_validator("qr_url")
|
||||
@classmethod
|
||||
@@ -157,7 +158,15 @@ def idle_out(db, look: DisplayLook | None) -> dict:
|
||||
cfg = config_of(look)
|
||||
pics = _pictures(db, [cfg["logo"], cfg["image"], *cfg["slides"]])
|
||||
url = lambda i, size: (media_store.image_of(pics[i]) or {}).get(size) if i in pics else None # noqa: E731
|
||||
return {**cfg, "logo_url": url(cfg["logo"], "card"), "image_url": url(cfg["image"], "full"),
|
||||
logo = url(cfg["logo"], "card")
|
||||
accent = None
|
||||
if cfg.get("brand") == "identity":
|
||||
from core.modules.api import _identity_brief
|
||||
ib = _identity_brief(db)
|
||||
accent = ib["colour"]
|
||||
# its own logo first; else the identity's (the one made for this background, else the main one)
|
||||
logo = logo or (ib["logo_light"] if cfg.get("theme", "dark") == "dark" else ib["logo_dark"]) or ib["logo"]
|
||||
return {**cfg, "logo_url": logo, "accent": accent, "image_url": url(cfg["image"], "full"),
|
||||
"slide_urls": [u for u in (url(i, "full") for i in cfg["slides"]) if u],
|
||||
"qr_link": _qr_link(cfg) if cfg["style"] == "qr" else None}
|
||||
|
||||
|
||||
@@ -22,11 +22,17 @@ EXPORT_VERSION = 1 # tables bundle
|
||||
CATALOG_EXPORT_VERSION = 2 # catalogue bundle: v2 = products listed in several categories (D-23)
|
||||
|
||||
|
||||
def _names(value):
|
||||
"""A choice's names per language from a bundle (0042), stored cleaned."""
|
||||
return menu_languages.dump(menu_languages.normalize_names(value))
|
||||
|
||||
|
||||
def _serialize_product(p: Product) -> dict:
|
||||
quick_options = [
|
||||
{"name": qo.name, "price": qo.price, "allow_multiple": qo.allow_multiple,
|
||||
"sort_order": qo.sort_order, "is_favorite": qo.is_favorite,
|
||||
"favorite_sort_order": qo.favorite_sort_order, "is_compact": qo.is_compact}
|
||||
"favorite_sort_order": qo.favorite_sort_order, "is_compact": qo.is_compact,
|
||||
"translations": menu_languages.names_of(qo)}
|
||||
for qo in p.quick_options
|
||||
]
|
||||
options = []
|
||||
@@ -34,10 +40,12 @@ def _serialize_product(p: Product) -> dict:
|
||||
sub = json.loads(opt.sub_choices) if opt.sub_choices else []
|
||||
options.append({"name": opt.name, "extra_cost": opt.extra_cost,
|
||||
"allow_multiple": opt.allow_multiple, "sub_choices": sub,
|
||||
"is_favorite": opt.is_favorite, "favorite_sort_order": opt.favorite_sort_order})
|
||||
"is_favorite": opt.is_favorite, "favorite_sort_order": opt.favorite_sort_order,
|
||||
"translations": menu_languages.names_of(opt)})
|
||||
ingredients = [
|
||||
{"name": ing.name, "extra_cost": ing.extra_cost,
|
||||
"is_favorite": ing.is_favorite, "favorite_sort_order": ing.favorite_sort_order}
|
||||
"is_favorite": ing.is_favorite, "favorite_sort_order": ing.favorite_sort_order,
|
||||
"translations": menu_languages.names_of(ing)}
|
||||
for ing in p.ingredients
|
||||
]
|
||||
preference_sets = []
|
||||
@@ -50,11 +58,13 @@ def _serialize_product(p: Product) -> dict:
|
||||
default_index = i
|
||||
sub = json.loads(ch.sub_choices) if ch.sub_choices else []
|
||||
choices.append({"name": ch.name, "extra_cost": ch.extra_cost,
|
||||
"sub_choices": sub, "disables_subset": ch.disables_subset})
|
||||
"sub_choices": sub, "disables_subset": ch.disables_subset,
|
||||
"translations": menu_languages.names_of(ch)})
|
||||
preference_sets.append({
|
||||
"name": ps.name, "choices": choices,
|
||||
"default_choice_index": default_index, "shared_subset": shared,
|
||||
"is_favorite": ps.is_favorite, "favorite_sort_order": ps.favorite_sort_order,
|
||||
"translations": menu_languages.names_of(ps),
|
||||
})
|
||||
return {
|
||||
"name": p.name, "base_price": p.base_price, "is_available": p.is_available,
|
||||
@@ -226,7 +236,9 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
|
||||
db.flush()
|
||||
|
||||
for qo in prod_data.get("quick_options", []):
|
||||
db.add(ProductQuickOption(product_id=product.id, **qo))
|
||||
qo = dict(qo)
|
||||
names = _names(qo.pop("translations", None))
|
||||
db.add(ProductQuickOption(product_id=product.id, **qo, translations=names))
|
||||
|
||||
for opt in prod_data.get("options", []):
|
||||
sub_json = json.dumps(opt.get("sub_choices", []))
|
||||
@@ -234,11 +246,13 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
|
||||
product_id=product.id, name=opt["name"], extra_cost=opt.get("extra_cost", 0.0),
|
||||
allow_multiple=opt.get("allow_multiple", False), sub_choices=sub_json,
|
||||
is_favorite=opt.get("is_favorite", False),
|
||||
favorite_sort_order=opt.get("favorite_sort_order", 0),
|
||||
favorite_sort_order=opt.get("favorite_sort_order", 0), translations=_names(opt.get("translations")),
|
||||
))
|
||||
|
||||
for ing in prod_data.get("ingredients", []):
|
||||
db.add(ProductIngredient(product_id=product.id, **ing))
|
||||
ing = dict(ing)
|
||||
names = _names(ing.pop("translations", None))
|
||||
db.add(ProductIngredient(product_id=product.id, **ing, translations=names))
|
||||
|
||||
for ps_data in prod_data.get("preference_sets", []):
|
||||
shared_json = json.dumps(ps_data["shared_subset"]) if ps_data.get("shared_subset") else None
|
||||
@@ -246,7 +260,7 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
|
||||
product_id=product.id, name=ps_data["name"],
|
||||
shared_subset=shared_json,
|
||||
is_favorite=ps_data.get("is_favorite", False),
|
||||
favorite_sort_order=ps_data.get("favorite_sort_order", 0),
|
||||
favorite_sort_order=ps_data.get("favorite_sort_order", 0), translations=_names(ps_data.get("translations")),
|
||||
)
|
||||
db.add(ps)
|
||||
db.flush()
|
||||
@@ -255,7 +269,7 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
|
||||
sub_json = json.dumps(ch.get("sub_choices", []))
|
||||
choice = ProductPreferenceChoice(
|
||||
set_id=ps.id, name=ch["name"], extra_cost=ch.get("extra_cost", 0.0),
|
||||
sub_choices=sub_json, disables_subset=ch.get("disables_subset", False),
|
||||
sub_choices=sub_json, disables_subset=ch.get("disables_subset", False), translations=_names(ch.get("translations")),
|
||||
)
|
||||
db.add(choice)
|
||||
db.flush()
|
||||
|
||||
@@ -7,12 +7,14 @@ in one or more payments; it is "due", "partial" or "paid" from what was paid. A
|
||||
be more than what is still due, and the total can't drop below what was already paid.
|
||||
"""
|
||||
from datetime import date
|
||||
from fastapi import APIRouter, Depends, status, Query
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from fastapi import APIRouter, Depends, File, Query, UploadFile, status
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
|
||||
from database import get_db
|
||||
from models.expenses import Contact, Expense, ExpensePayment
|
||||
from models.expenses import Contact, Expense, ExpenseDocument, ExpenseLine, ExpensePayment
|
||||
from models.user import User
|
||||
from schemas.expenses import (
|
||||
ContactCreate, ContactUpdate, ContactOut,
|
||||
@@ -22,6 +24,7 @@ from schemas.expenses import (
|
||||
from core.access.deps import require, require_any
|
||||
from core.errors import XeniaError
|
||||
from core.timeutil import venue_day_window
|
||||
from services import expense_docs
|
||||
from services.ws_bus import broadcast_sync
|
||||
|
||||
contacts_router = APIRouter()
|
||||
@@ -43,6 +46,45 @@ def _check_contact(fields: dict):
|
||||
raise XeniaError("validation.missing", field="name")
|
||||
|
||||
|
||||
def _line_money(ln) -> tuple[float, float, float]:
|
||||
"""(net, vat, total) of a line, rounded to cents."""
|
||||
q = ln["quantity"] if isinstance(ln, dict) else ln.quantity
|
||||
p = ln["unit_price"] if isinstance(ln, dict) else ln.unit_price
|
||||
r = ln["vat_rate"] if isinstance(ln, dict) else ln.vat_rate
|
||||
cents = Decimal("0.01")
|
||||
net = (Decimal(str(q or 0)) * Decimal(str(p or 0))).quantize(cents, ROUND_HALF_UP)
|
||||
vat = (net * Decimal(str(r or 0)) / 100).quantize(cents, ROUND_HALF_UP) # as on a Greek invoice: half up
|
||||
return float(net), float(vat), float(net + vat)
|
||||
|
||||
|
||||
def _take_lines(fields: dict) -> list | None:
|
||||
"""The lines sent (checked), and the total they make into fields["total_amount"]."""
|
||||
lines = fields.pop("lines", None)
|
||||
if lines is None:
|
||||
return None
|
||||
out = []
|
||||
for ln in lines:
|
||||
d = (ln.get("description") or "").strip()
|
||||
if not d:
|
||||
raise XeniaError("validation.missing", field="lines.description")
|
||||
if ln.get("quantity") is None or ln["quantity"] <= 0:
|
||||
raise XeniaError("validation.positive", field="lines.quantity")
|
||||
if ln.get("unit_price") is None or ln["unit_price"] < 0:
|
||||
raise XeniaError("validation.positive", field="lines.unit_price")
|
||||
if (ln.get("vat_rate") or 0) < 0 or (ln.get("vat_rate") or 0) > 100:
|
||||
raise XeniaError("validation.choice", field="lines.vat_rate", value=ln.get("vat_rate"))
|
||||
out.append({**ln, "description": d[:200], "vat_rate": ln.get("vat_rate") or 0.0})
|
||||
if out:
|
||||
fields["total_amount"] = round(sum(_line_money(ln)[2] for ln in out), 2)
|
||||
return out
|
||||
|
||||
|
||||
def _set_lines(expense: Expense, lines: list | None):
|
||||
if lines is None:
|
||||
return
|
||||
expense.lines = [ExpenseLine(position=i, **ln) for i, ln in enumerate(lines)]
|
||||
|
||||
|
||||
def _check_expense(db: Session, fields: dict, paid: float = 0.0):
|
||||
if "description" in fields and not (fields["description"] or "").strip():
|
||||
raise XeniaError("validation.missing", field="description")
|
||||
@@ -103,6 +145,11 @@ def _expense_out(e: Expense) -> dict:
|
||||
"created_at": e.created_at,
|
||||
"notes": e.notes,
|
||||
"payments": payments_out,
|
||||
"lines": [{"id": ln.id, "description": ln.description, "quantity": ln.quantity, "unit_price": ln.unit_price,
|
||||
"vat_rate": ln.vat_rate, **dict(zip(("net", "vat", "total"), _line_money(ln)))} for ln in e.lines],
|
||||
"net_amount": round(sum(_line_money(ln)[0] for ln in e.lines), 2) if e.lines else None,
|
||||
"vat_amount": round(sum(_line_money(ln)[1] for ln in e.lines), 2) if e.lines else None,
|
||||
"documents": [expense_docs.out(d) for d in e.documents],
|
||||
}
|
||||
|
||||
|
||||
@@ -220,9 +267,13 @@ def list_expenses(
|
||||
@expenses_router.post("/", response_model=ExpenseOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_expense(body: ExpenseCreate, db: Session = Depends(get_db), user: User = MANAGE):
|
||||
fields = body.model_dump()
|
||||
lines = _take_lines(fields)
|
||||
if fields.get("total_amount") is None:
|
||||
raise XeniaError("validation.positive", field="total_amount")
|
||||
_check_expense(db, fields)
|
||||
fields["description"] = fields["description"].strip()
|
||||
expense = Expense(**fields, created_by_id=user.id)
|
||||
_set_lines(expense, lines)
|
||||
db.add(expense)
|
||||
db.commit()
|
||||
db.refresh(expense)
|
||||
@@ -237,12 +288,16 @@ def update_expense(expense_id: int, body: ExpenseUpdate, db: Session = Depends(g
|
||||
raise XeniaError("expense.not_found")
|
||||
# Fields sent as null are cleared (supplier, due date, notes); the rest only change when given
|
||||
fields = body.model_dump(exclude_unset=True)
|
||||
if fields.get("lines") is None:
|
||||
fields.pop("lines", None)
|
||||
lines = _take_lines(fields)
|
||||
for k in ("description", "category", "total_amount"):
|
||||
if fields.get(k) is None:
|
||||
fields.pop(k, None)
|
||||
_check_expense(db, fields, paid=expense.paid_amount)
|
||||
for field, value in fields.items():
|
||||
setattr(expense, field, value.strip() if field == "description" else value)
|
||||
_set_lines(expense, lines)
|
||||
db.commit()
|
||||
db.refresh(expense)
|
||||
_changed()
|
||||
@@ -256,6 +311,7 @@ def delete_expense(expense_id: int, db: Session = Depends(get_db), user: User =
|
||||
raise XeniaError("expense.not_found")
|
||||
db.delete(expense)
|
||||
db.commit()
|
||||
expense_docs.remove_all(expense_id)
|
||||
_changed()
|
||||
|
||||
|
||||
@@ -289,3 +345,49 @@ def record_payment(
|
||||
db.refresh(expense)
|
||||
_changed()
|
||||
return _expense_out(expense)
|
||||
|
||||
|
||||
# ── Documents: the invoice / receipt kept with an expense (2026-11-20) ────────────
|
||||
|
||||
def _expense(db: Session, expense_id: int) -> Expense:
|
||||
expense = db.query(Expense).filter(Expense.id == expense_id).first()
|
||||
if not expense:
|
||||
raise XeniaError("expense.not_found")
|
||||
return expense
|
||||
|
||||
|
||||
@expenses_router.post("/{expense_id}/documents", response_model=ExpenseOut, status_code=status.HTTP_201_CREATED)
|
||||
def upload_document(expense_id: int, file: UploadFile = File(...), db: Session = Depends(get_db), user: User = MANAGE):
|
||||
"""A PDF or a photo (JPG, PNG, WebP, HEIC), at most 15 MB."""
|
||||
expense = _expense(db, expense_id)
|
||||
stored, content_type, size = expense_docs.save(expense_id, file)
|
||||
expense.documents.append(ExpenseDocument(filename=(file.filename or "document")[:200], stored_name=stored,
|
||||
content_type=content_type, size=size, uploaded_by_id=user.id))
|
||||
db.commit()
|
||||
db.refresh(expense)
|
||||
_changed()
|
||||
return _expense_out(expense)
|
||||
|
||||
|
||||
@expenses_router.get("/{expense_id}/documents/{doc_id}")
|
||||
def get_document(expense_id: int, doc_id: int, db: Session = Depends(get_db),
|
||||
user: User = Depends(require_any("expenses.manage", "reports.view"))):
|
||||
doc = db.query(ExpenseDocument).filter(ExpenseDocument.id == doc_id, ExpenseDocument.expense_id == expense_id).first()
|
||||
path = expense_docs.path(doc) if doc else None
|
||||
if not path:
|
||||
raise XeniaError("expense.document_not_found")
|
||||
return FileResponse(path, media_type=doc.content_type, filename=doc.filename, content_disposition_type="inline")
|
||||
|
||||
|
||||
@expenses_router.delete("/{expense_id}/documents/{doc_id}", response_model=ExpenseOut)
|
||||
def delete_document(expense_id: int, doc_id: int, db: Session = Depends(get_db), user: User = MANAGE):
|
||||
expense = _expense(db, expense_id)
|
||||
doc = next((d for d in expense.documents if d.id == doc_id), None)
|
||||
if not doc:
|
||||
raise XeniaError("expense.document_not_found")
|
||||
expense_docs.remove(doc)
|
||||
expense.documents.remove(doc)
|
||||
db.commit()
|
||||
db.refresh(expense)
|
||||
_changed()
|
||||
return _expense_out(expense)
|
||||
|
||||
@@ -88,6 +88,7 @@ class PlacedItem(BaseModel):
|
||||
height: float = Field(gt=0, le=6000)
|
||||
rotation: float = 0.0
|
||||
text: Optional[str] = Field(None, max_length=60)
|
||||
color: Optional[str] = Field(None, pattern=r"^#[0-9a-fA-F]{6}$") # an area's colour (2026-11-20)
|
||||
|
||||
|
||||
class LayoutBody(BaseModel):
|
||||
@@ -110,7 +111,7 @@ def plan_out(p: FloorPlan) -> dict:
|
||||
"media_id": p.media_id, "background": media_store.image_of(p.media) if p.media_id else None,
|
||||
"background_opacity": p.background_opacity,
|
||||
"items": [{"id": i.id, "kind": i.kind, "x": i.x, "y": i.y, "width": i.width, "height": i.height,
|
||||
"rotation": i.rotation, "text": i.text} for i in p.items],
|
||||
"rotation": i.rotation, "text": i.text, "color": i.color} for i in p.items],
|
||||
}
|
||||
|
||||
|
||||
@@ -211,7 +212,8 @@ def save_layout(plan_id: int, body: LayoutBody, db: Session = Depends(get_db), u
|
||||
db.flush()
|
||||
for it in body.items:
|
||||
p.items.append(FloorItem(kind=it.kind, x=_inside(it.x, p.width), y=_inside(it.y, p.height), width=round(it.width, 1),
|
||||
height=round(it.height, 1), rotation=_rot(it.rotation), text=(it.text or "").strip() or None))
|
||||
height=round(it.height, 1), rotation=_rot(it.rotation), text=(it.text or "").strip() or None,
|
||||
color=it.color if it.kind == "area" else None))
|
||||
db.commit()
|
||||
db.refresh(p)
|
||||
_changed()
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
"""The venue's identity (6R.14, owner 2026-11-22): set once, used by every app that shows the venue.
|
||||
|
||||
GET /api/identity its name, slogan, colours, logos, Wi-Fi and contact details (anyone who opens the manager)
|
||||
PUT /api/identity all of it at once (core.settings.manage)
|
||||
GET /api/identity/hours the opening hours, Monday first (6R.15)
|
||||
PUT /api/identity/hours {days: [[{from, to}], … 7], note} (core.settings.manage or core.staff.manage: the Schedule page)
|
||||
|
||||
Stored as the settings `venue.name` (the name everything already shows) and `venue.identity` (JSON,
|
||||
the rest). Logos are media library pictures, protected while used. Signage screens get it with
|
||||
their venue (routers/signage._venue) and are told when it changes; the colours are offered first in
|
||||
every colour field of signage. Other apps follow it in 6R.20.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import List, Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.access.deps import require, require_any
|
||||
from core.errors import XeniaError
|
||||
from database import get_db
|
||||
|
||||
router = APIRouter()
|
||||
KEY = "venue.identity"
|
||||
HOURS = "venue.opening_hours"
|
||||
TIME = r"^([01]\d|2[0-3]):[0-5]\d$"
|
||||
HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$"
|
||||
LOGOS = ("main", "light", "dark", "icon")
|
||||
|
||||
|
||||
class _Strict(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
def _text(v, n):
|
||||
v = " ".join(str(v or "").split())[:n]
|
||||
return v or None
|
||||
|
||||
|
||||
class Colour(_Strict):
|
||||
"""One of the venue's colours: a name people see ("Main", "Olive") and its colour."""
|
||||
name: str = Field(min_length=1, max_length=40)
|
||||
colour: str = Field(pattern=HEX)
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def _name(cls, v):
|
||||
v = _text(v, 40)
|
||||
if not v:
|
||||
raise ValueError("a colour has a name")
|
||||
return v
|
||||
|
||||
@field_validator("colour")
|
||||
@classmethod
|
||||
def _lower(cls, v):
|
||||
return v.lower()
|
||||
|
||||
|
||||
class Logos(_Strict):
|
||||
"""Pictures of the media library: the main logo, one for dark backgrounds (light), one for light
|
||||
backgrounds (dark), a small square icon."""
|
||||
main: Optional[int] = None
|
||||
light: Optional[int] = None
|
||||
dark: Optional[int] = None
|
||||
icon: Optional[int] = None
|
||||
|
||||
|
||||
class Wifi(_Strict):
|
||||
ssid: Optional[str] = Field(default=None, max_length=32)
|
||||
password: Optional[str] = Field(default=None, max_length=63)
|
||||
security: Literal["WPA", "WEP", "nopass"] = "WPA"
|
||||
hidden: bool = False
|
||||
note: Optional[str] = Field(default=None, max_length=120) # "Ask us for the guest network"
|
||||
|
||||
@field_validator("ssid", "note")
|
||||
@classmethod
|
||||
def _trim(cls, v):
|
||||
return (v or "").strip() or None
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def _pw(cls, v):
|
||||
return v or None # spaces count in a password
|
||||
|
||||
|
||||
class Contact(_Strict):
|
||||
phone: Optional[str] = Field(default=None, max_length=40)
|
||||
phone2: Optional[str] = Field(default=None, max_length=40)
|
||||
email: Optional[str] = Field(default=None, max_length=120)
|
||||
address: Optional[str] = Field(default=None, max_length=200)
|
||||
website: Optional[str] = Field(default=None, max_length=200)
|
||||
facebook: Optional[str] = Field(default=None, max_length=200)
|
||||
instagram: Optional[str] = Field(default=None, max_length=200)
|
||||
tiktok: Optional[str] = Field(default=None, max_length=200)
|
||||
tripadvisor: Optional[str] = Field(default=None, max_length=200)
|
||||
google: Optional[str] = Field(default=None, max_length=300) # its Google Maps / reviews link
|
||||
whatsapp: Optional[str] = Field(default=None, max_length=40)
|
||||
viber: Optional[str] = Field(default=None, max_length=40)
|
||||
|
||||
@field_validator("*")
|
||||
@classmethod
|
||||
def _trim(cls, v):
|
||||
return (v or "").strip() or None if isinstance(v, str) or v is None else v
|
||||
|
||||
|
||||
class Identity(_Strict):
|
||||
slogan: Optional[str] = Field(default=None, max_length=120)
|
||||
colours: List[Colour] = Field(default_factory=list, max_length=12)
|
||||
logos: Logos = Field(default_factory=Logos)
|
||||
wifi: Wifi = Field(default_factory=Wifi)
|
||||
contact: Contact = Field(default_factory=Contact)
|
||||
|
||||
@field_validator("slogan")
|
||||
@classmethod
|
||||
def _slogan(cls, v):
|
||||
return _text(v, 120)
|
||||
|
||||
|
||||
class IdentityBody(Identity):
|
||||
name: Optional[str] = Field(default=None, max_length=80)
|
||||
|
||||
|
||||
def _setting(db, key: str) -> str:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
return row.value if row and row.value is not None else ""
|
||||
|
||||
|
||||
def _save(db, key: str, value: str) -> None:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
if row is None:
|
||||
db.add(PosSettings(key=key, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
|
||||
|
||||
def stored(db) -> Identity:
|
||||
"""The identity as stored (an old or broken value reads as empty, never an error)."""
|
||||
try:
|
||||
return Identity(**json.loads(_setting(db, KEY) or "{}"))
|
||||
except Exception:
|
||||
return Identity()
|
||||
|
||||
|
||||
def identity_out(db) -> dict:
|
||||
"""The identity for an app: the logos as pictures ({id, name, thumb, card, full} or None)."""
|
||||
from models.media import Media
|
||||
from services.media import image_of
|
||||
ident = stored(db).model_dump()
|
||||
ident["logos"] = {k: image_of(db.get(Media, v)) if v else None for k, v in ident["logos"].items()}
|
||||
return {"name": _setting(db, "venue.name") or None, **ident}
|
||||
|
||||
|
||||
def _uses(db, media_id: int) -> list:
|
||||
logos = stored(db).logos
|
||||
return [{"id": 0, "name": k} for k in LOGOS if getattr(logos, k) == media_id]
|
||||
|
||||
|
||||
def _register():
|
||||
from services import media as media_store
|
||||
media_store.register_usage("identity", _uses)
|
||||
|
||||
|
||||
_register()
|
||||
|
||||
|
||||
@router.get("")
|
||||
def get_identity(db: Session = Depends(get_db), user=Depends(require("core.dashboard.access"))):
|
||||
return identity_out(db)
|
||||
|
||||
|
||||
@router.put("")
|
||||
def put_identity(body: IdentityBody, db: Session = Depends(get_db), user=Depends(require("core.settings.manage"))):
|
||||
from models.media import Media
|
||||
for k in LOGOS:
|
||||
mid = getattr(body.logos, k)
|
||||
if mid is None:
|
||||
continue
|
||||
m = db.get(Media, mid)
|
||||
if m is None:
|
||||
raise XeniaError("media.not_found", media_id=mid)
|
||||
if m.kind != "image":
|
||||
raise XeniaError("media.not_a_picture")
|
||||
if "name" in body.model_fields_set:
|
||||
_save(db, "venue.name", (body.name or "").strip())
|
||||
_save(db, KEY, json.dumps(Identity(**body.model_dump(exclude={"name"})).model_dump(), ensure_ascii=False))
|
||||
db.commit()
|
||||
try:
|
||||
from routers.signage import tell_all_screens
|
||||
tell_all_screens(db) # the screens show the venue's name, logo, Wi-Fi…
|
||||
except Exception:
|
||||
pass # signage not installed / off: nothing to tell
|
||||
return identity_out(db)
|
||||
|
||||
|
||||
# ── opening hours (6R.15): edited on the Schedule page, shown by signage's opening hours widget ──
|
||||
|
||||
class Span(_Strict):
|
||||
"""Open from … to … (venue time; `to` before `from` passes midnight)."""
|
||||
from_: str = Field(alias="from", pattern=TIME)
|
||||
to: str = Field(pattern=TIME)
|
||||
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
||||
|
||||
|
||||
class Hours(_Strict):
|
||||
days: List[List[Span]] = Field(default_factory=lambda: [[] for _ in range(7)]) # Monday first; [] = closed
|
||||
note: Optional[str] = Field(default=None, max_length=120) # "Closed on holidays"
|
||||
|
||||
@field_validator("days")
|
||||
@classmethod
|
||||
def _seven(cls, v):
|
||||
if len(v) != 7 or any(len(d) > 3 for d in v):
|
||||
raise ValueError("seven days, up to three spans a day")
|
||||
return v
|
||||
|
||||
@field_validator("note")
|
||||
@classmethod
|
||||
def _note(cls, v):
|
||||
return _text(v, 120)
|
||||
|
||||
|
||||
def hours_out(db) -> dict:
|
||||
"""{days: [[{from, to}]…7], note, set}: `set` false while no day has hours."""
|
||||
try:
|
||||
h = Hours(**json.loads(_setting(db, HOURS) or "{}"))
|
||||
except Exception:
|
||||
h = Hours()
|
||||
days = [[{"from": x.from_, "to": x.to} for x in d] for d in h.days]
|
||||
return {"days": days, "note": h.note, "set": any(days)}
|
||||
|
||||
|
||||
@router.get("/hours")
|
||||
def get_hours(db: Session = Depends(get_db), user=Depends(require("core.dashboard.access"))):
|
||||
return hours_out(db)
|
||||
|
||||
|
||||
@router.put("/hours")
|
||||
def put_hours(body: Hours, db: Session = Depends(get_db), user=Depends(require_any("core.settings.manage", "core.staff.manage"))):
|
||||
days = [[{"from": x.from_, "to": x.to} for x in sorted(d, key=lambda x: x.from_)] for d in body.days]
|
||||
_save(db, HOURS, json.dumps({"days": days, "note": body.note}, ensure_ascii=False))
|
||||
db.commit()
|
||||
try:
|
||||
from routers.signage import tell_all_screens
|
||||
tell_all_screens(db)
|
||||
except Exception:
|
||||
pass
|
||||
return hours_out(db)
|
||||
@@ -29,7 +29,7 @@ from core.access.deps import public, require_any
|
||||
from core.errors import XeniaError
|
||||
from database import get_db
|
||||
from datetime import datetime
|
||||
from models.media import Media
|
||||
from models.media import Media, MediaFolder
|
||||
from services import media as store
|
||||
from services import video
|
||||
|
||||
@@ -57,6 +57,7 @@ class MediaOut(BaseModel):
|
||||
builtin: bool = False
|
||||
processing: Optional[str] = None # videos: waiting | working | done | failed (5.4e)
|
||||
progress: Optional[int] = None
|
||||
folder_id: Optional[int] = None # 6R.16
|
||||
urls: dict = Field(default_factory=dict)
|
||||
|
||||
|
||||
@@ -75,17 +76,53 @@ class MediaPage(BaseModel):
|
||||
|
||||
|
||||
class RenameBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
name: Optional[str] = Field(default=None, min_length=1, max_length=120)
|
||||
folder_id: Optional[int] = None # 6R.16: its folder (None: none)
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def _strip(cls, v):
|
||||
if v is None:
|
||||
return v
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("empty")
|
||||
return v
|
||||
|
||||
|
||||
class FolderBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=60)
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def _strip(cls, v):
|
||||
v = " ".join(v.split())
|
||||
if not v:
|
||||
raise ValueError("empty")
|
||||
return v
|
||||
|
||||
|
||||
class MoveBody(BaseModel):
|
||||
ids: List[int] = Field(min_length=1, max_length=500)
|
||||
folder_id: Optional[int] = None
|
||||
|
||||
|
||||
def _folder(db: Session, folder_id: Optional[int]) -> Optional[MediaFolder]:
|
||||
if folder_id is None:
|
||||
return None
|
||||
f = db.get(MediaFolder, folder_id)
|
||||
if f is None:
|
||||
raise XeniaError("media.folder_unknown", folder_id=folder_id)
|
||||
return f
|
||||
|
||||
|
||||
def _folders_out(db: Session) -> list:
|
||||
from sqlalchemy import func
|
||||
counts = dict(db.query(Media.folder_id, func.count(Media.id)).group_by(Media.folder_id).all())
|
||||
rows = db.query(MediaFolder).order_by(MediaFolder.position, MediaFolder.name).all()
|
||||
return [{"id": f.id, "name": f.name, "count": counts.get(f.id, 0)} for f in rows]
|
||||
|
||||
|
||||
def _out(item: Media, cls=MediaOut, **extra):
|
||||
return cls.model_validate(item).model_copy(update={"urls": store.urls(item), **extra})
|
||||
|
||||
@@ -105,9 +142,14 @@ def _name_from(filename: str | None) -> str:
|
||||
|
||||
@router.get("", response_model=MediaPage)
|
||||
def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str] = None,
|
||||
collection: Optional[Literal["builtin", "own"]] = None, limit: int = 100, offset: int = 0,
|
||||
collection: Optional[Literal["builtin", "own"]] = None, folder: Optional[str] = None, limit: int = 100, offset: int = 0,
|
||||
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
"""`folder`: a folder's id, or "none" for the files in no folder (6R.16)."""
|
||||
query = db.query(Media)
|
||||
if folder == "none":
|
||||
query = query.filter(Media.folder_id.is_(None))
|
||||
elif folder and folder.isdigit():
|
||||
query = query.filter(Media.folder_id == int(folder))
|
||||
if kind:
|
||||
query = query.filter(Media.kind == kind)
|
||||
if q and q.strip():
|
||||
@@ -122,11 +164,13 @@ def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str
|
||||
|
||||
@router.post("", response_model=UploadOut, status_code=201)
|
||||
def upload_media(response: Response, file: UploadFile = File(...), name: Optional[str] = Form(None),
|
||||
folder_id: Optional[int] = Form(None),
|
||||
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
# The type comes from the bytes; the browser's content type only picks the size limit.
|
||||
declared = (file.content_type or "").lower()
|
||||
limit = store.VIDEO_MAX_BYTES if declared.startswith("video/") else store.IMAGE_MAX_BYTES
|
||||
tmp, sha, size = store.receive(file.file, limit)
|
||||
folder = _folder(db, folder_id)
|
||||
existing = db.query(Media).filter(Media.sha256 == sha).first()
|
||||
if existing is not None:
|
||||
store._remove(tmp)
|
||||
@@ -134,7 +178,8 @@ def upload_media(response: Response, file: UploadFile = File(...), name: Optiona
|
||||
return _out(existing, UploadOut, existing=True)
|
||||
info = store.ingest(tmp, sha, size)
|
||||
item = Media(name=(name or "").strip()[:120] or _name_from(file.filename),
|
||||
original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id, **info)
|
||||
original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id,
|
||||
folder_id=folder.id if folder else None, **info)
|
||||
if item.kind == "video":
|
||||
video.queued(item) # its still frame and playable version, in the background
|
||||
try:
|
||||
@@ -195,6 +240,50 @@ def _ranged(path: str, ctype: str, rng: str, headers: dict):
|
||||
**headers, "Content-Range": f"bytes {start}-{end}/{size}", "Content-Length": str(end - start + 1)})
|
||||
|
||||
|
||||
# ── folders (6R.16): only a grouping; files keep their place on disk ─────────────
|
||||
|
||||
@router.get("/folders")
|
||||
def list_folders(db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
return {"folders": _folders_out(db), "none": db.query(Media).filter(Media.folder_id.is_(None)).count()}
|
||||
|
||||
|
||||
@router.post("/folders", status_code=201)
|
||||
def create_folder(body: FolderBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
last = db.query(MediaFolder).count()
|
||||
f = MediaFolder(name=body.name, position=last)
|
||||
db.add(f)
|
||||
db.commit()
|
||||
db.refresh(f)
|
||||
return {"id": f.id, "name": f.name, "count": 0}
|
||||
|
||||
|
||||
@router.patch("/folders/{folder_id}")
|
||||
def rename_folder(folder_id: int, body: FolderBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
f = _folder(db, folder_id)
|
||||
f.name = body.name
|
||||
db.commit()
|
||||
return next(x for x in _folders_out(db) if x["id"] == f.id)
|
||||
|
||||
|
||||
@router.delete("/folders/{folder_id}", status_code=204)
|
||||
def delete_folder(folder_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
"""The folder goes; its files stay in the library, in no folder."""
|
||||
f = _folder(db, folder_id)
|
||||
db.query(Media).filter(Media.folder_id == f.id).update({Media.folder_id: None})
|
||||
db.delete(f)
|
||||
db.commit()
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.post("/move")
|
||||
def move_media(body: MoveBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
"""Several files into a folder (or out of any: folder_id null)."""
|
||||
folder = _folder(db, body.folder_id)
|
||||
n = db.query(Media).filter(Media.id.in_(body.ids)).update({Media.folder_id: folder.id if folder else None}, synchronize_session=False)
|
||||
db.commit()
|
||||
return {"moved": n}
|
||||
|
||||
|
||||
@router.get("/{media_id}", response_model=MediaDetail)
|
||||
def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
item = _get(db, media_id)
|
||||
@@ -204,9 +293,12 @@ def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require
|
||||
@router.patch("/{media_id}", response_model=MediaOut)
|
||||
def rename_media(media_id: int, body: RenameBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
|
||||
item = _get(db, media_id)
|
||||
if item.builtin:
|
||||
raise XeniaError("media.builtin")
|
||||
item.name = body.name
|
||||
if "name" in body.model_fields_set and body.name is not None:
|
||||
if item.builtin:
|
||||
raise XeniaError("media.builtin")
|
||||
item.name = body.name
|
||||
if "folder_id" in body.model_fields_set:
|
||||
item.folder_id = _folder(db, body.folder_id).id if body.folder_id is not None else None # built-in pictures may be filed too
|
||||
db.commit()
|
||||
db.refresh(item)
|
||||
return _out(item)
|
||||
|
||||
+205
-21
@@ -343,7 +343,8 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
|
||||
"id": i.id,
|
||||
"order_id": i.order_id,
|
||||
"product_id": i.product_id,
|
||||
"product": {"id": i.product.id, "name": i.product.name} if i.product else None,
|
||||
"product": {"id": i.product.id, "name": i.product.name, "unit_type": i.product.unit_type or "piece",
|
||||
"one_more_enabled": bool(i.product.one_more_enabled)} if i.product else None, # 6F.5: +1
|
||||
"product_name": i.product_name, "category_id": i.category_id, "category_name": i.category_name,
|
||||
"added_by": i.added_by,
|
||||
"added_by_name": name_map.get(i.added_by),
|
||||
@@ -366,6 +367,9 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
|
||||
"system_key": i.system_key, # the delivery fee line (phase 3S, S.5)
|
||||
"source": i.source, # waiter | counter | qr | online (4.8)
|
||||
"course_id": i.course_id,
|
||||
"deal_id": i.deal_id, "linked_item_id": i.linked_item_id,
|
||||
"split_from_id": i.split_from_id, # 6F.4: the line it was cut from
|
||||
"cancel_reason": i.cancel_reason,
|
||||
}
|
||||
|
||||
def fmt_log(l):
|
||||
@@ -584,20 +588,27 @@ def add_items(order_id: int, body: AddLinesRequest, request: Request, db: Sessio
|
||||
raise XeniaError("order.not_yours")
|
||||
lines, manual = _resolve_lines(db, body.lines, of_order(order))
|
||||
approval = None
|
||||
reasons = [None] * len(lines)
|
||||
if any(manual) or any(line.discount_pct for line in lines):
|
||||
from services import price_changes # the venue's switch and the reason first (6F.3)
|
||||
reasons = [price_changes.check(db, sent=False, reason=(raw or {}).get("price_reason") if isinstance(raw, dict) else None,
|
||||
by_hand=bool(hand)) if hand or line.discount_pct else None
|
||||
for raw, line, hand in zip(body.lines, lines, manual)]
|
||||
approval = _need(request, db, user, "ordering.prices.modify", target=f"order {order_id} new items")
|
||||
discounts = [0.0] * len(lines)
|
||||
if any(line.discount_pct for line in lines):
|
||||
priced = pos_cart.price_lines(db, lines, order.order_type or "here", pos_cart.order_cart(order), point=of_order(order))
|
||||
discounts = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
|
||||
items = []
|
||||
for raw, line, hand, disc in zip(body.lines, lines, manual, discounts):
|
||||
for raw, line, hand, disc, reason in zip(body.lines, lines, manual, discounts, reasons):
|
||||
adj = round(hand + disc, 2)
|
||||
items.append(OrderItemInput(
|
||||
product_id=line.product.id, quantity=line.quantity,
|
||||
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
|
||||
removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None,
|
||||
is_service_item=raw.get("is_service_item") is True, course_id=raw.get("course_id"),
|
||||
price_reason=reason if adj else None,
|
||||
price_approved_by=approval.approved_by if approval is not None and adj else None,
|
||||
))
|
||||
result = add_priced_items(order_id, AddItemsRequest(items=items, order_note=body.order_note,
|
||||
customer_count=body.customer_count), db, user)
|
||||
@@ -630,6 +641,8 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
|
||||
# Build pricing context once for the whole batch
|
||||
now = utcnow()
|
||||
active_pg_ids = build_active_price_group_ids(db, now)
|
||||
from services.pricing import build_active_scene_ids
|
||||
active_scenes = build_active_scene_ids(db, now)
|
||||
# The order's sales point (phase 3S): what the pricing engine's channel condition sees
|
||||
from core.sales_points import is_sold_at, of_order
|
||||
order_channel = of_order(order)
|
||||
@@ -670,6 +683,7 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
|
||||
}
|
||||
],
|
||||
active_price_group_ids=active_pg_ids,
|
||||
active_scene_ids=active_scenes,
|
||||
)
|
||||
|
||||
# Resolve final unit_price through pricing engine
|
||||
@@ -705,6 +719,11 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
|
||||
db.add(item)
|
||||
db.flush()
|
||||
new_item_ids.append(item.id)
|
||||
if item.price_adjustment: # a price changed by hand in the cart (6F.3)
|
||||
from services import price_changes
|
||||
price_changes.record(db, item=item, before=unit_price, after=unit_price + item.price_adjustment,
|
||||
user_id=user.id, stage="cart", reason=item_in.price_reason,
|
||||
approved_by=item_in.price_approved_by)
|
||||
|
||||
# Stamp order_id on events and queue them — written after commit
|
||||
if price_events:
|
||||
@@ -804,6 +823,7 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
|
||||
now=now,
|
||||
cart_items=final_cart,
|
||||
active_price_group_ids=active_pg_ids,
|
||||
active_scene_ids=active_scenes,
|
||||
)
|
||||
deal_offers = evaluate_deals(order_id, deal_ctx, already_fired, db)
|
||||
|
||||
@@ -1481,6 +1501,9 @@ def transfer_order(
|
||||
order.table_id = body.target_table_id
|
||||
_audit(db, order_id, "TABLE_TRANSFER", waiter_id=user.id,
|
||||
note=f"Transferred from table {old_table_id} to table {body.target_table_id}")
|
||||
from services import moves # 6F.4: the whole order and its lines, on the record
|
||||
moves.record(db, kind="table_transfer", source=order, target=order, items=list(order.items), user_id=user.id,
|
||||
from_table_id=old_table_id, to_table_id=body.target_table_id)
|
||||
db.commit()
|
||||
db.refresh(order)
|
||||
broadcast_sync("order_updated", {"order_id": order.id, "table_id": order.table_id, "old_table_id": old_table_id, "status": order.status, "action": "transferred"})
|
||||
@@ -1523,6 +1546,8 @@ def merge_order(
|
||||
raise XeniaError("order.same_order")
|
||||
|
||||
# Move all items to target order
|
||||
from services import moves # 6F.4
|
||||
moves.record(db, kind="orders_merged", source=source, target=target, items=list(source.items), user_id=user.id)
|
||||
moved_item_ids = []
|
||||
for item in source.items:
|
||||
item.order_id = target.id
|
||||
@@ -1597,21 +1622,7 @@ def split_item(
|
||||
|
||||
# Reduce original item
|
||||
item.quantity -= body.quantity
|
||||
|
||||
# Create split-off item
|
||||
new_item = OrderItem(
|
||||
source=item.source,
|
||||
order_id=order_id,
|
||||
product_id=item.product_id,
|
||||
added_by=item.added_by,
|
||||
quantity=body.quantity,
|
||||
unit_price=item.unit_price,
|
||||
selected_options=item.selected_options,
|
||||
removed_ingredients=item.removed_ingredients,
|
||||
notes=item.notes,
|
||||
status="active",
|
||||
printed=item.printed,
|
||||
)
|
||||
new_item = cut_part(item, body.quantity)
|
||||
db.add(new_item)
|
||||
db.commit()
|
||||
db.refresh(item)
|
||||
@@ -1619,10 +1630,141 @@ def split_item(
|
||||
return [item, new_item]
|
||||
|
||||
|
||||
def cut_part(item, quantity, **changes):
|
||||
"""A new line cut from `item` (a split, a lowered quantity, 6F.4/6F.5): everything the line was
|
||||
(product, price and its change, choices, note, kitchen state, course, cost, names, source) for
|
||||
`quantity`, linked by split_from_id so its moves follow it. Not added to the session."""
|
||||
fields = dict(
|
||||
source=item.source, order_id=item.order_id, product_id=item.product_id, added_by=item.added_by,
|
||||
quantity=quantity, unit_price=item.unit_price, selected_options=item.selected_options,
|
||||
removed_ingredients=item.removed_ingredients, notes=item.notes, status="active", printed=item.printed,
|
||||
split_from_id=item.id, kds_status=item.kds_status, course_id=item.course_id,
|
||||
price_adjustment=item.price_adjustment, unit_cost=item.unit_cost, product_name=item.product_name,
|
||||
category_id=item.category_id, category_name=item.category_name,
|
||||
) # added_at = now: the moment it was cut (services/moves.py reads it)
|
||||
fields.update(changes)
|
||||
return OrderItem(**fields)
|
||||
|
||||
|
||||
# ─── One more of a line, and a line's quantity (6F.5) ────────────────────────
|
||||
|
||||
class AgainRequest(BaseModel):
|
||||
quantity: int = Field(default=1, ge=1, le=50)
|
||||
|
||||
|
||||
@router.post("/{order_id}/items/{item_id}/again", response_model=AddItemsResponse)
|
||||
def order_again(order_id: int, item_id: int, body: AgainRequest, request: Request, db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user)):
|
||||
""""One more" (6F.5): a new line just like this one (product, choices, removed ingredients, note,
|
||||
course) for `quantity`, priced by the server now and sent like any new line (kitchen ticket,
|
||||
KDS). Only for products with one_more_enabled, counted in pieces, from an active, paid or
|
||||
tabbed line that isn't a deal's or the system's. Needs ordering.orders.open."""
|
||||
from core.access.context import current_device
|
||||
from schemas.order import OrderItemInput, SelectedOptionInput
|
||||
_need(request, db, user, "ordering.orders.open", target=f"order:{order_id}")
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first()
|
||||
if item is None:
|
||||
raise XeniaError("order.item_not_found")
|
||||
product = item.product
|
||||
if product is None or not product.one_more_enabled:
|
||||
raise XeniaError("order.one_more_off")
|
||||
if item.status not in ("active", "paid", "tabbed") or item.deal_id or item.linked_item_id \
|
||||
or product.system_key or (product.unit_type or "piece") != "piece":
|
||||
raise XeniaError("order.one_more_line")
|
||||
try:
|
||||
options = [SelectedOptionInput(**o) for o in json.loads(item.selected_options or "[]") if isinstance(o, dict)]
|
||||
removed = [str(x) for x in json.loads(item.removed_ingredients or "[]")]
|
||||
except (ValueError, TypeError):
|
||||
options, removed = [], []
|
||||
device = current_device(request, db)
|
||||
source = "counter" if device is not None and device.app_key == "pos_counter" else "waiter"
|
||||
result = add_priced_items(order_id, AddItemsRequest(items=[OrderItemInput(
|
||||
product_id=item.product_id, quantity=body.quantity, selected_options=options or None,
|
||||
removed_ingredients=removed or None, notes=item.notes, course_id=item.course_id, source=source,
|
||||
)]), db, user)
|
||||
_audit(db, order_id, "ITEM_REORDERED", waiter_id=user.id, item_ids=[item.id],
|
||||
note=f"{body.quantity:g} more of #{item.id}")
|
||||
db.commit()
|
||||
return result
|
||||
|
||||
|
||||
class QuantityRequest(BaseModel):
|
||||
quantity: int = Field(ge=1, le=999)
|
||||
print_cancellation: bool = False # lowering: send a cancellation to the kitchen (the app asks)
|
||||
|
||||
|
||||
@router.post("/{order_id}/items/{item_id}/quantity")
|
||||
def change_quantity(order_id: int, item_id: int, body: QuantityRequest, request: Request, background_tasks: BackgroundTasks,
|
||||
db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
"""Change a sent line's quantity without sending it again (6F.5). The venue
|
||||
(orders.quantity_change: off | add_only | add_and_remove) and ordering.items.change_quantity
|
||||
decide; lowering also needs ordering.orders.cancel (or a manager's PIN each). Up: the line
|
||||
grows, nothing is printed. Down: the removed part becomes its own cancelled line ("quantity
|
||||
lowered", split_from_id = the line) and, when asked, a cancellation ticket goes to the kitchen.
|
||||
Only unpaid lines counted in pieces, not a deal's or the system's."""
|
||||
from models.settings import PosSettings
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
row = db.query(PosSettings).filter(PosSettings.key == "orders.quantity_change").first()
|
||||
mode = row.value if row is not None and row.value in ("off", "add_only", "add_and_remove") else "off"
|
||||
if mode == "off":
|
||||
raise XeniaError("order.quantity_change_off")
|
||||
item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first()
|
||||
if item is None:
|
||||
raise XeniaError("order.item_not_found")
|
||||
product = item.product
|
||||
if item.status != "active" or item.deal_id or item.linked_item_id or (product is not None and product.system_key) \
|
||||
or (item.unit_type or "piece") != "piece" or item.quantity != int(item.quantity):
|
||||
raise XeniaError("order.quantity_line")
|
||||
old = int(item.quantity)
|
||||
if body.quantity == old:
|
||||
return {"item_id": item.id, "quantity": old, "cancelled_item_id": None}
|
||||
lowering = body.quantity < old
|
||||
if lowering and mode != "add_and_remove":
|
||||
raise XeniaError("order.quantity_remove_off")
|
||||
approval = _need(request, db, user, "ordering.items.change_quantity", target=f"order:{order_id} item:{item_id}")
|
||||
cancel_approval = None
|
||||
if lowering and not holds(user, "core.dashboard.access") and not _waiter_can_cancel(user, db):
|
||||
cancel_approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}")
|
||||
note = f"{old} → {body.quantity}" + (f" · {_approval_note(approval)}" if approval is not None else "")
|
||||
part = None
|
||||
if lowering:
|
||||
now = utcnow()
|
||||
part = cut_part(item, old - body.quantity, status="cancelled", cancelled_by=user.id, cancelled_at=now,
|
||||
cancel_reason="quantity lowered")
|
||||
db.add(part)
|
||||
item.quantity = body.quantity
|
||||
db.flush()
|
||||
_audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=[part.id],
|
||||
note=("quantity lowered" + (f" · {_approval_note(cancel_approval)}" if cancel_approval is not None else "")
|
||||
+ ("" if body.print_cancellation else " · no kitchen ticket")))
|
||||
else:
|
||||
item.quantity = body.quantity
|
||||
_audit(db, order_id, "QUANTITY_CHANGED", waiter_id=user.id, item_ids=[item.id], note=note)
|
||||
db.commit()
|
||||
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status,
|
||||
"action": "quantity_changed", "item_ids": [item.id]})
|
||||
if part is not None:
|
||||
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status,
|
||||
"action": "items_cancelled", "item_ids": [part.id]})
|
||||
if body.print_cancellation:
|
||||
background_tasks.add_task(print_cancellation_ticket, order_id, [part.id])
|
||||
return {"item_id": item.id, "quantity": item.quantity, "cancelled_item_id": part.id if part is not None else None}
|
||||
|
||||
|
||||
# ─── Adjust price on an existing item ────────────────────────────────────────
|
||||
|
||||
class PriceAdjustRequest(BaseModel):
|
||||
price_adjustment: float # delta from unit_price (can be negative)
|
||||
reason: Optional[str] = Field(default=None, max_length=200) # 6F.3: needed when the venue asks for one
|
||||
|
||||
|
||||
@router.patch("/{order_id}/items/{item_id}/price-adjust", response_model=OrderItemOut)
|
||||
@@ -1634,8 +1776,10 @@ def adjust_item_price(
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Apply an on-the-fly price adjustment to an active order item. Without
|
||||
ordering.prices.modify a manager can approve it once (X-Xenia-Override, D-10)."""
|
||||
"""Change a sent line's price by hand (6F.3): the venue must allow it after sending
|
||||
(orders.price_change = anytime), it needs ordering.prices.modify_sent (a manager can approve it
|
||||
once, X-Xenia-Override, D-10) and, when the venue asks, a reason. Recorded as a manual_price
|
||||
event (before → after, who, the approver, the stage, the reason)."""
|
||||
item = db.query(OrderItem).filter(
|
||||
OrderItem.id == item_id, OrderItem.order_id == order_id
|
||||
).first()
|
||||
@@ -1647,15 +1791,51 @@ def adjust_item_price(
|
||||
order = db.query(Order).filter(Order.id == order_id).first()
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
_need(request, db, user, "ordering.prices.modify", target=f"order:{order_id} item:{item_id}")
|
||||
from services import price_changes
|
||||
reason = price_changes.check(db, sent=True, reason=body.reason)
|
||||
approval = _need(request, db, user, "ordering.prices.modify_sent", target=f"order:{order_id} item:{item_id}")
|
||||
if not -10000 <= body.price_adjustment <= 10000 or item.unit_price + body.price_adjustment < 0:
|
||||
raise XeniaError("order.line.price", line=1, name=item.product_name)
|
||||
|
||||
item.price_adjustment = body.price_adjustment
|
||||
before = item.unit_price + (item.price_adjustment or 0.0)
|
||||
item.price_adjustment = round(body.price_adjustment, 2)
|
||||
price_changes.record(db, item=item, before=before, after=item.unit_price + item.price_adjustment, user_id=user.id,
|
||||
stage=price_changes.stage_of(item), reason=reason,
|
||||
approved_by=approval.approved_by if approval is not None else None)
|
||||
db.commit()
|
||||
db.refresh(item)
|
||||
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "item_price_adjusted"})
|
||||
return item
|
||||
|
||||
|
||||
@router.get("/{order_id}/moves")
|
||||
def order_moves(order_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
"""Where an order and its lines came from (6F.4): {order: [the whole order's transfers and
|
||||
merges], items: {line id: [its moves, its parents' before it was split from them]}}. Each move:
|
||||
kind, at, from / to table (id, name) and order, who, the lines and quantities."""
|
||||
from services import moves
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
if not _can_access_order(order, user, db):
|
||||
raise XeniaError("order.not_yours")
|
||||
return moves.for_order(db, order)
|
||||
|
||||
|
||||
@router.get("/{order_id}/price-changes")
|
||||
def order_price_changes(order_id: int, db: Session = Depends(get_db),
|
||||
user: User = Depends(require("ordering.prices.view_changes"))):
|
||||
"""The prices changed by hand on an order (6F.3), oldest first, for the waiter app and the
|
||||
counter: [{id, item_id, product_name, before, after, delta, quantity, stage, reason, by, approved_by, at}]."""
|
||||
from models.pricing import PriceEventLog
|
||||
from services import price_changes
|
||||
order = db.get(Order, order_id)
|
||||
if order is None:
|
||||
raise XeniaError("order.not_found", order_id=order_id)
|
||||
return [price_changes.event_out(ev, db) for ev in db.query(PriceEventLog).filter(
|
||||
PriceEventLog.order_id == order_id, PriceEventLog.event_type == price_changes.EVENT).order_by(PriceEventLog.id)]
|
||||
|
||||
|
||||
# ─── Waiter-applied manual discount ─────────────────────────────────────────
|
||||
|
||||
from schemas.pricing import ApplyDiscountRequest, ApplyDiscountResponse
|
||||
@@ -1921,6 +2101,8 @@ def move_items(
|
||||
if not items:
|
||||
raise XeniaError("order.no_active_items")
|
||||
|
||||
from services import moves # 6F.4
|
||||
moves.record(db, kind="items_moved", source=source, target=target, items=items, user_id=user.id)
|
||||
moved_ids = []
|
||||
for item in items:
|
||||
item.order_id = target.id
|
||||
@@ -2123,6 +2305,8 @@ def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db
|
||||
rest_ids = [i.id for i in rest]
|
||||
db.query(PriceEventLog).filter(PriceEventLog.order_item_id.in_(rest_ids)).update(
|
||||
{PriceEventLog.order_item_id: keep.id}, synchronize_session=False)
|
||||
from services import moves # 6F.4
|
||||
moves.repoint(db, rest_ids, keep.id)
|
||||
for i in rest:
|
||||
db.delete(i)
|
||||
_audit(db, order_id, "ITEMS_COMBINED", waiter_id=user.id, item_ids=[keep.id] + rest_ids,
|
||||
|
||||
@@ -89,6 +89,7 @@ def _product_out(p, price: float, prices: dict | None = None) -> dict:
|
||||
"price": round(price, 2), "prices": {k: round(v, 2) for k, v in (prices or {}).items()},
|
||||
"sold_at": [sp for sp in sales_points.sold_at(p) if sp in sales_points.IN_PERSON],
|
||||
"base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece",
|
||||
"one_more": bool(p.one_more_enabled), # 6F.5
|
||||
"tags": _tags(p.tags),
|
||||
"allergens": allergens.of(p),
|
||||
"primary_category_id": p.primary_category_id,
|
||||
@@ -140,8 +141,10 @@ def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(requi
|
||||
by_point = {sp: pos_cart.unit_prices(db, products, sp) for sp in sales_points.IN_PERSON}
|
||||
default = pos_cart.point_for(settings["default_order_type"])
|
||||
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
|
||||
from services import price_changes
|
||||
return {
|
||||
"settings": settings,
|
||||
# + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount
|
||||
"settings": {**settings, "price_change": price_changes.mode(db)},
|
||||
"categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order}
|
||||
for c in cats],
|
||||
"products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON})
|
||||
@@ -209,7 +212,7 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
|
||||
orders_api._need(request, db, user, "ordering.orders.close", target="pos sale") # 4.3: taking payment is a key
|
||||
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
|
||||
groups = _payment_groups(body, len(lines))
|
||||
_check_discounts(request, db, user, lines)
|
||||
approved_by = _check_discounts(request, db, user, lines)
|
||||
_check_fiscal(db, {line.product for line in lines})
|
||||
priced = pos_cart.price_lines(db, lines, body.order_type)
|
||||
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
|
||||
@@ -218,7 +221,7 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
|
||||
_check_cash(body.cash_given, cash_due)
|
||||
|
||||
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
|
||||
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
|
||||
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user)
|
||||
item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()]
|
||||
paid, fiscal = [], None
|
||||
for method, idx in groups:
|
||||
@@ -247,9 +250,16 @@ def _require_shift(db, user):
|
||||
|
||||
|
||||
def _check_discounts(request, db, user, lines):
|
||||
"""A % discount at the counter is a price change in the cart (6F.3): the venue's switch, then
|
||||
the key (or a manager's PIN). Returns the approving manager's id, else None. The reason isn't
|
||||
asked: the discount itself says what it is."""
|
||||
from core.access.context import authorize
|
||||
from services import price_changes
|
||||
if any(line.discount_pct for line in lines):
|
||||
authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
|
||||
price_changes.check(db, sent=False, by_hand=False)
|
||||
approval = authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
|
||||
return approval.approved_by if approval is not None else None
|
||||
return None
|
||||
|
||||
|
||||
def _check_fiscal(db, products):
|
||||
@@ -265,14 +275,17 @@ def _check_cash(cash_given, cash_due):
|
||||
raise XeniaError("pos.payment_invalid", reason="cash_short")
|
||||
|
||||
|
||||
def _items_in(lines, adjs):
|
||||
def _items_in(lines, adjs, approved_by=None):
|
||||
"""Resolved lines as orders.add_priced_items takes them (selected_options entries with the
|
||||
database's prices; a discount as the item's price_adjustment)."""
|
||||
database's prices; a discount as the item's price_adjustment, recorded as a manual_price event
|
||||
with "−N %" as its reason, 6F.3)."""
|
||||
from schemas.order import OrderItemInput, SelectedOptionInput
|
||||
return [OrderItemInput(
|
||||
product_id=line.product.id, quantity=line.quantity,
|
||||
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
|
||||
removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None, source="counter",
|
||||
price_reason=f"−{line.discount_pct:g} %" if adj and line.discount_pct else None,
|
||||
price_approved_by=approved_by if adj else None,
|
||||
) for line, adj in zip(lines, adjs)]
|
||||
|
||||
|
||||
@@ -407,13 +420,13 @@ def pos_table_items(table_id: int, body: TableItemsBody, request: Request, db: S
|
||||
elif not _in_zones(db, user, table):
|
||||
raise XeniaError("pos.table_not_yours", table=_table_name(table))
|
||||
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
|
||||
_check_discounts(request, db, user, lines)
|
||||
approved_by = _check_discounts(request, db, user, lines)
|
||||
existing = pos_cart.order_cart(order) if order is not None else None
|
||||
priced = pos_cart.price_lines(db, lines, (order.order_type or "here") if order is not None else "here", existing)
|
||||
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
|
||||
if order is None:
|
||||
order = orders_api.open_order(OrderCreate(table_id=table_id, order_type="here"), db, user)
|
||||
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
|
||||
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user)
|
||||
return {"order_id": order.id, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", [])}
|
||||
|
||||
|
||||
|
||||
@@ -527,12 +527,11 @@ def get_order_price_events(
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
events = (
|
||||
db.query(PriceEventLog)
|
||||
.filter(PriceEventLog.order_id == order_id)
|
||||
.order_by(PriceEventLog.applied_at)
|
||||
.all()
|
||||
)
|
||||
from services import price_changes
|
||||
q = db.query(PriceEventLog).filter(PriceEventLog.order_id == order_id)
|
||||
if not price_changes.can_view(user): # prices changed by hand: ordering.prices.view_changes (6F.3)
|
||||
q = q.filter(PriceEventLog.event_type != price_changes.EVENT)
|
||||
events = q.order_by(PriceEventLog.applied_at).all()
|
||||
result = []
|
||||
for ev in events:
|
||||
out = PriceEventOut.model_validate(ev)
|
||||
@@ -541,7 +540,9 @@ def get_order_price_events(
|
||||
if ev.deal:
|
||||
out.deal_name = ev.deal.name
|
||||
if ev.applied_by:
|
||||
out.applied_by_username = ev.applied_by.username
|
||||
out.applied_by_username = ev.applied_by.nickname or ev.applied_by.username
|
||||
if ev.approved_by:
|
||||
out.approved_by_username = ev.approved_by.nickname or ev.approved_by.username
|
||||
result.append(out)
|
||||
return result
|
||||
|
||||
@@ -718,6 +719,8 @@ def _condition_ok(ctype: str, p: dict) -> bool:
|
||||
return bool(p.get("channels"))
|
||||
if ctype == "price_group_active":
|
||||
return isinstance(p.get("price_group_id"), int)
|
||||
if ctype == "scene_active":
|
||||
return isinstance(p.get("scene_id"), int) and not isinstance(p.get("scene_id"), bool)
|
||||
return ctype in ("user_tier", "low_stock") # old placeholders: kept, never added
|
||||
|
||||
|
||||
@@ -763,3 +766,136 @@ def _sync_deal_targets(deal, targets_in, db: Session):
|
||||
target_ids=json.dumps(t.target_ids) if t.target_ids else None,
|
||||
target_tags=json.dumps(t.target_tags) if t.target_tags else None,
|
||||
))
|
||||
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# ORDER CHANNEL PRICES (2026-11-20, services/channel_prices.py)
|
||||
# =============================================================================
|
||||
|
||||
from pydantic import BaseModel as _Base # noqa: E402
|
||||
|
||||
|
||||
class ChannelPriceIn(_Base):
|
||||
name: Optional[str] = None
|
||||
sales_points: List[str]
|
||||
product_ids: List[int] = []
|
||||
category_ids: List[int] = []
|
||||
action_type: str
|
||||
value: float
|
||||
round_to: Optional[str] = None
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class ProductChannelPriceIn(_Base):
|
||||
"""The product editor's quick edit: per sales point, its own rule or null (no own rule)."""
|
||||
points: dict[str, Optional[dict]]
|
||||
|
||||
|
||||
def _cp_fields(body: ChannelPriceIn) -> dict:
|
||||
from services import channel_prices as cp
|
||||
f = body.model_dump()
|
||||
f["name"] = (f.get("name") or "").strip()[:120] or None
|
||||
f["round_to"] = f.get("round_to") or None
|
||||
cp.check(f)
|
||||
return f
|
||||
|
||||
|
||||
def _cp_store(row, f: dict, user) -> None:
|
||||
from core.timeutil import utcnow as _now
|
||||
row.name = f["name"]
|
||||
row.sales_points = json.dumps(list(dict.fromkeys(f["sales_points"])))
|
||||
row.product_ids = json.dumps(sorted(set(f["product_ids"])))
|
||||
row.category_ids = json.dumps(sorted(set(f["category_ids"])))
|
||||
row.action_type = f["action_type"]
|
||||
row.value = f["value"]
|
||||
row.round_to = f["round_to"]
|
||||
row.is_active = f["is_active"]
|
||||
row.updated_at = _now()
|
||||
row.updated_by = user.id
|
||||
|
||||
|
||||
@router.get("/channel-prices")
|
||||
def list_channel_prices(db: Session = Depends(get_db), user: User = Depends(require(MANAGE))):
|
||||
from models.pricing import ChannelPrice
|
||||
from services import channel_prices as cp
|
||||
return [cp.out(r) for r in db.query(ChannelPrice).order_by(ChannelPrice.id).all()]
|
||||
|
||||
|
||||
@router.post("/channel-prices", status_code=status.HTTP_201_CREATED)
|
||||
def create_channel_price(body: ChannelPriceIn, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))):
|
||||
from models.pricing import ChannelPrice
|
||||
from services import channel_prices as cp
|
||||
f = _cp_fields(body)
|
||||
row = ChannelPrice()
|
||||
_cp_store(row, f, user)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
_changed()
|
||||
return cp.out(row)
|
||||
|
||||
|
||||
@router.put("/channel-prices/{rule_id}")
|
||||
def update_channel_price(rule_id: int, body: ChannelPriceIn, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))):
|
||||
from models.pricing import ChannelPrice
|
||||
from services import channel_prices as cp
|
||||
row = db.query(ChannelPrice).filter(ChannelPrice.id == rule_id).first()
|
||||
if not row:
|
||||
raise XeniaError("channel_price.not_found")
|
||||
_cp_store(row, _cp_fields(body), user)
|
||||
db.commit()
|
||||
_changed()
|
||||
return cp.out(row)
|
||||
|
||||
|
||||
@router.delete("/channel-prices/{rule_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_channel_price(rule_id: int, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))):
|
||||
from models.pricing import ChannelPrice
|
||||
row = db.query(ChannelPrice).filter(ChannelPrice.id == rule_id).first()
|
||||
if not row:
|
||||
raise XeniaError("channel_price.not_found")
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
_changed()
|
||||
|
||||
|
||||
@router.get("/channel-prices/product/{product_id}")
|
||||
def product_channel_prices(product_id: int, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))):
|
||||
"""Per sales point the product is sold at: the default price, the price there and why."""
|
||||
from models.product import Product
|
||||
from services import channel_prices as cp
|
||||
p = db.query(Product).filter(Product.id == product_id).first()
|
||||
if not p:
|
||||
raise XeniaError("product.not_found")
|
||||
return {"product_id": p.id, "base_price": p.base_price, "points": cp.product_view(db, p)}
|
||||
|
||||
|
||||
@router.put("/channel-prices/product/{product_id}")
|
||||
def set_product_channel_prices(product_id: int, body: ProductChannelPriceIn, db: Session = Depends(get_db),
|
||||
user: User = Depends(require(MANAGE))):
|
||||
"""The product's own price per sales point: {action_type, value, round_to} sets it, null
|
||||
removes it (the category's or the channel's rule, or the default price, counts again)."""
|
||||
from models.pricing import ChannelPrice
|
||||
from models.product import Product
|
||||
from services import channel_prices as cp
|
||||
p = db.query(Product).filter(Product.id == product_id).first()
|
||||
if not p:
|
||||
raise XeniaError("product.not_found")
|
||||
every = db.query(ChannelPrice).order_by(ChannelPrice.id).all()
|
||||
for point, spec in body.points.items():
|
||||
own = cp.own_rule(every, p.id, point)
|
||||
if spec is None:
|
||||
if own is not None:
|
||||
db.delete(own)
|
||||
continue
|
||||
f = {"name": None, "sales_points": [point], "product_ids": [p.id], "category_ids": [],
|
||||
"action_type": spec.get("action_type"), "value": spec.get("value"), "round_to": spec.get("round_to") or None,
|
||||
"is_active": True}
|
||||
cp.check(f)
|
||||
if own is None:
|
||||
own = ChannelPrice()
|
||||
db.add(own)
|
||||
_cp_store(own, f, user)
|
||||
db.commit()
|
||||
_changed()
|
||||
return {"product_id": p.id, "base_price": p.base_price, "points": cp.product_view(db, p)}
|
||||
|
||||
@@ -26,6 +26,35 @@ from core.errors import XeniaError
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _sub_dump(sub) -> dict:
|
||||
"""A sub-choice (or a shared sub-set) as stored: its names per language cleaned (0042)."""
|
||||
d = sub.model_dump()
|
||||
d["translations"] = menu_languages.normalize_names(d.get("translations"))
|
||||
if "choices" in d:
|
||||
d["choices"] = [_sub_dump(c) for c in sub.choices]
|
||||
return d
|
||||
|
||||
|
||||
def _check_names(body) -> None:
|
||||
"""Every choice's names valid before anything is replaced (a refusal changes nothing)."""
|
||||
subs = lambda xs: [menu_languages.normalize_names(x.translations) for x in xs or []] # noqa: E731
|
||||
for g in body.modifier_groups or []:
|
||||
menu_languages.normalize_names(g.translations)
|
||||
for x in [*(body.quick_options or []), *(body.ingredients or [])]:
|
||||
menu_languages.normalize_names(x.translations)
|
||||
for o in body.options or []:
|
||||
menu_languages.normalize_names(o.translations)
|
||||
subs(o.sub_choices)
|
||||
for ps in body.preference_sets or []:
|
||||
menu_languages.normalize_names(ps.translations)
|
||||
for c in ps.choices:
|
||||
menu_languages.normalize_names(c.translations)
|
||||
subs(c.sub_choices)
|
||||
if ps.shared_subset:
|
||||
menu_languages.normalize_names(ps.shared_subset.translations)
|
||||
subs(ps.shared_subset.choices)
|
||||
|
||||
|
||||
def _broadcast_products_changed():
|
||||
broadcast_sync("products_changed", {})
|
||||
|
||||
@@ -43,6 +72,7 @@ def _replace_modifier_groups(db, product, groups):
|
||||
modifier_type=g.modifier_type,
|
||||
name=g.name,
|
||||
sort_order=i,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(g.translations)),
|
||||
)
|
||||
db.add(new_g)
|
||||
db.flush()
|
||||
@@ -64,6 +94,7 @@ def _replace_quick_options(db, product, quick_options):
|
||||
is_favorite=qo.is_favorite,
|
||||
favorite_sort_order=qo.favorite_sort_order,
|
||||
is_compact=qo.is_compact,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(qo.translations)),
|
||||
))
|
||||
|
||||
|
||||
@@ -72,7 +103,7 @@ def _replace_options(db, product, options, group_id_map=None):
|
||||
db.delete(opt)
|
||||
db.flush()
|
||||
for opt in options:
|
||||
sub_json = json.dumps([s.model_dump() for s in opt.sub_choices]) if opt.sub_choices else None
|
||||
sub_json = json.dumps([_sub_dump(s) for s in opt.sub_choices], ensure_ascii=False) if opt.sub_choices else None
|
||||
resolved_group = group_id_map[opt.group_id] if (group_id_map and opt.group_id is not None and opt.group_id < len(group_id_map)) else None
|
||||
db.add(ProductOption(
|
||||
product_id=product.id,
|
||||
@@ -85,6 +116,7 @@ def _replace_options(db, product, options, group_id_map=None):
|
||||
favorite_sort_order=opt.favorite_sort_order,
|
||||
is_compact=opt.is_compact,
|
||||
group_id=resolved_group,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(opt.translations)),
|
||||
))
|
||||
|
||||
|
||||
@@ -94,7 +126,8 @@ def _replace_ingredients(db, product, ingredients, group_id_map=None):
|
||||
db.flush()
|
||||
for ing in ingredients:
|
||||
resolved_group = group_id_map[ing.group_id] if (group_id_map and ing.group_id is not None and ing.group_id < len(group_id_map)) else None
|
||||
db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id'}), group_id=resolved_group))
|
||||
db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id', 'translations'}), group_id=resolved_group,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(ing.translations))))
|
||||
|
||||
|
||||
def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group_id_map=None):
|
||||
@@ -102,7 +135,7 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
|
||||
db.delete(ps)
|
||||
db.flush()
|
||||
for ps in sets:
|
||||
shared_json = json.dumps(ps.shared_subset.model_dump()) if ps.shared_subset else None
|
||||
shared_json = json.dumps(_sub_dump(ps.shared_subset), ensure_ascii=False) if ps.shared_subset else None
|
||||
resolved_group = group_id_map[ps.group_id] if (group_id_map and ps.group_id is not None and ps.group_id < len(group_id_map)) else None
|
||||
new_set = ProductPreferenceSet(
|
||||
product_id=product.id,
|
||||
@@ -113,12 +146,13 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
|
||||
group_id=resolved_group,
|
||||
allow_multi_select=ps.allow_multi_select,
|
||||
allow_choice_quantity=ps.allow_choice_quantity,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(ps.translations)),
|
||||
)
|
||||
db.add(new_set)
|
||||
db.flush()
|
||||
created_choices = []
|
||||
for ch in ps.choices:
|
||||
sub_json = json.dumps([s.model_dump() for s in ch.sub_choices]) if ch.sub_choices else None
|
||||
sub_json = json.dumps([_sub_dump(s) for s in ch.sub_choices], ensure_ascii=False) if ch.sub_choices else None
|
||||
choice = ProductPreferenceChoice(
|
||||
set_id=new_set.id,
|
||||
name=ch.name,
|
||||
@@ -126,6 +160,7 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
|
||||
sub_choices=sub_json,
|
||||
disables_subset=ch.disables_subset,
|
||||
is_compact=ch.is_compact,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(ch.translations)),
|
||||
)
|
||||
db.add(choice)
|
||||
db.flush()
|
||||
@@ -371,6 +406,7 @@ def reorder_products(items: List[ProductReorderItem], db: Session = Depends(get_
|
||||
|
||||
@router.post("/", response_model=ProductOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_product(body: ProductCreate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
|
||||
_check_names(body)
|
||||
data = body.model_dump(exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags",
|
||||
"category_id", "primary_category_id", "category_ids", "allergens", "translations"})
|
||||
if data.get("sort_order") == 0:
|
||||
@@ -400,11 +436,12 @@ def create_product(body: ProductCreate, db: Session = Depends(get_db), user: Use
|
||||
is_favorite=qo.is_favorite,
|
||||
favorite_sort_order=qo.favorite_sort_order,
|
||||
is_compact=qo.is_compact,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(qo.translations)),
|
||||
))
|
||||
created_groups = _replace_modifier_groups(db, product, body.modifier_groups)
|
||||
group_id_map = [g.id for g in created_groups]
|
||||
for opt in body.options:
|
||||
sub_json = json.dumps([s.model_dump() for s in opt.sub_choices]) if opt.sub_choices else None
|
||||
sub_json = json.dumps([_sub_dump(s) for s in opt.sub_choices], ensure_ascii=False) if opt.sub_choices else None
|
||||
resolved_group = group_id_map[opt.group_id] if (opt.group_id is not None and opt.group_id < len(group_id_map)) else None
|
||||
db.add(ProductOption(
|
||||
product_id=product.id,
|
||||
@@ -417,10 +454,12 @@ def create_product(body: ProductCreate, db: Session = Depends(get_db), user: Use
|
||||
favorite_sort_order=opt.favorite_sort_order,
|
||||
is_compact=opt.is_compact,
|
||||
group_id=resolved_group,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(opt.translations)),
|
||||
))
|
||||
for ing in body.ingredients:
|
||||
resolved_group = group_id_map[ing.group_id] if (ing.group_id is not None and ing.group_id < len(group_id_map)) else None
|
||||
db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id'}), group_id=resolved_group))
|
||||
db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id', 'translations'}), group_id=resolved_group,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(ing.translations))))
|
||||
_replace_preference_sets(db, product, body.preference_sets, group_id_map)
|
||||
db.commit()
|
||||
db.refresh(product)
|
||||
@@ -434,6 +473,7 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
|
||||
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||
if not product:
|
||||
raise XeniaError("product.not_found")
|
||||
_check_names(body)
|
||||
scalar_fields = body.model_dump(
|
||||
exclude_none=True,
|
||||
exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups",
|
||||
@@ -495,7 +535,8 @@ def create_modifier_group(product_id: int, body: ModifierGroupCreate, db: Sessio
|
||||
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
|
||||
if not product:
|
||||
raise XeniaError("product.not_found")
|
||||
g = ProductModifierGroup(product_id=product_id, modifier_type=body.modifier_type, name=body.name, sort_order=body.sort_order)
|
||||
g = ProductModifierGroup(product_id=product_id, modifier_type=body.modifier_type, name=body.name, sort_order=body.sort_order,
|
||||
translations=menu_languages.dump(menu_languages.normalize_names(body.translations)))
|
||||
db.add(g)
|
||||
db.commit()
|
||||
db.refresh(g)
|
||||
|
||||
@@ -10,7 +10,7 @@ import json
|
||||
from fastapi import APIRouter, Depends, Query, BackgroundTasks, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm import Session, contains_eager, selectinload
|
||||
from sqlalchemy import func
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Optional, List
|
||||
@@ -1386,7 +1386,7 @@ def cancellations_log(
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
q = db.query(OrderItem).filter(OrderItem.status == "cancelled")
|
||||
q = db.query(OrderItem).filter(OrderItem.status == "cancelled").options(selectinload(OrderItem.order))
|
||||
|
||||
# Date filter on cancelled_at if available, otherwise fall back to added_at
|
||||
dt_from = history_since(from_dt, 'reports') # clamped even without a "from" (D-6)
|
||||
@@ -1416,16 +1416,9 @@ def cancellations_log(
|
||||
items = q.order_by(OrderItem.added_at.desc()).all()
|
||||
waiters_db = {u.id: u for u in db.query(User).all()}
|
||||
tables_db = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
|
||||
orders_cache = {}
|
||||
|
||||
def _get_order(oid):
|
||||
if oid not in orders_cache:
|
||||
orders_cache[oid] = db.query(Order).filter(Order.id == oid).first()
|
||||
return orders_cache[oid]
|
||||
|
||||
result = []
|
||||
for item in items:
|
||||
order = _get_order(item.order_id)
|
||||
order = item.order # loaded with the items (selectinload above)
|
||||
table_name = tables_db.get(order.table_id, f"#{order.table_id}") if order else "—"
|
||||
waiter = waiters_db.get(item.added_by)
|
||||
waiter_name = (waiter.full_name or waiter.username) if waiter else f"#{item.added_by}"
|
||||
@@ -1712,7 +1705,7 @@ def prep_zones_report(
|
||||
product_zone_map[product.id].append(zone.id)
|
||||
|
||||
# Query order items in the requested range
|
||||
q = db.query(OrderItem).join(Order)
|
||||
q = db.query(OrderItem).join(Order).options(contains_eager(OrderItem.order))
|
||||
_since = history_since(from_dt, 'reports')
|
||||
if _since:
|
||||
q = q.filter(Order.opened_at >= _since)
|
||||
@@ -1879,6 +1872,133 @@ def print_prep_zone(
|
||||
# Phase 2L — Discount audit report
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.get("/moves")
|
||||
def moves_report(
|
||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||
to_dt: Optional[str] = Query(default=None, alias="to"),
|
||||
business_day_id: Optional[int] = None,
|
||||
kind: Optional[str] = None,
|
||||
by: Optional[int] = None,
|
||||
table_id: Optional[int] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
"""Moves between tables and orders (6F.4) in a period or a business day: each move (kind, from /
|
||||
to table and order, who, the lines with their quantity and value), counts per kind and per
|
||||
person. `table_id`: moves from or to that table."""
|
||||
from models.order import OrderMove, OrderItem
|
||||
from services import moves
|
||||
q = db.query(OrderMove)
|
||||
if business_day_id:
|
||||
q = q.filter(OrderMove.business_day_id == business_day_id)
|
||||
elif from_dt and to_dt:
|
||||
q = q.filter(OrderMove.at >= history_since(from_dt, 'reports'), OrderMove.at <= parse_api_datetime(to_dt))
|
||||
if kind:
|
||||
q = q.filter(OrderMove.kind == kind)
|
||||
if by:
|
||||
q = q.filter(OrderMove.by_user_id == by)
|
||||
if table_id:
|
||||
q = q.filter((OrderMove.from_table_id == table_id) | (OrderMove.to_table_id == table_id))
|
||||
rows = q.order_by(OrderMove.at.desc()).all()
|
||||
tables, users = moves._names(db)
|
||||
item_ids = {i.item_id for m in rows for i in m.items}
|
||||
lines = {i.id: i for i in db.query(OrderItem).filter(OrderItem.id.in_(item_ids)).all()} if item_ids else {}
|
||||
names = {i.id: i.product_name for i in lines.values()}
|
||||
out, by_kind, by_person = [], {}, {}
|
||||
for m in rows:
|
||||
row = moves.move_out(m, tables, users, names)
|
||||
row["at"] = _dt(m.at)
|
||||
row["value"] = round(sum(((lines[i.item_id].unit_price or 0) + (lines[i.item_id].price_adjustment or 0)) * (i.quantity or lines[i.item_id].quantity or 0)
|
||||
for i in m.items if i.item_id in lines), 2)
|
||||
out.append(row)
|
||||
by_kind[m.kind] = by_kind.get(m.kind, 0) + 1
|
||||
p = by_person.setdefault(m.by_user_id, {"user_id": m.by_user_id, "name": row["by"], "count": 0})
|
||||
p["count"] += 1
|
||||
return {"moves": out, "count": len(out), "by_kind": by_kind,
|
||||
"by_person": sorted(by_person.values(), key=lambda x: -x["count"])}
|
||||
|
||||
|
||||
@router.get("/moves/export")
|
||||
def moves_export(
|
||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||
to_dt: Optional[str] = Query(default=None, alias="to"),
|
||||
business_day_id: Optional[int] = None,
|
||||
kind: Optional[str] = None,
|
||||
by: Optional[int] = None,
|
||||
table_id: Optional[int] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
data = moves_report(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, kind=kind, by=by, table_id=table_id, db=db, user=user)
|
||||
rows = [{"id": m["id"], "at": m["at"], "kind": m["kind"], "from_table": m["from_table"] or "", "to_table": m["to_table"] or "",
|
||||
"from_order": m["from_order_id"], "to_order": m["to_order_id"], "by": m["by"] or "",
|
||||
"lines": "; ".join(f"{i.get('name') or i['item_id']} ×{i['quantity'] if i['quantity'] is not None else '?'}" for i in m["items"]),
|
||||
"value": m["value"]} for m in data["moves"]]
|
||||
fields = ["id", "at", "kind", "from_table", "to_table", "from_order", "to_order", "by", "lines", "value"]
|
||||
return csv_export.response(db, rows, fields, f"moves-{(from_dt or '')[:10]}.csv", times=("at",))
|
||||
|
||||
|
||||
@router.get("/price-changes")
|
||||
def price_changes_report(
|
||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||
to_dt: Optional[str] = Query(default=None, alias="to"),
|
||||
business_day_id: Optional[int] = None,
|
||||
applied_by: Optional[int] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
"""Prices changed by hand (6F.3) in a period or a business day: each change (the line, before →
|
||||
after, the difference for its quantity, the stage, who, the approving manager, why, the table),
|
||||
totals per person. Needs ordering.prices.view_changes besides the reports key."""
|
||||
from core.access.check import holds
|
||||
from models.pricing import PriceEventLog
|
||||
from services import price_changes
|
||||
if not holds(user, "ordering.prices.view_changes"):
|
||||
raise XeniaError("access.denied", key="ordering.prices.view_changes")
|
||||
q = db.query(PriceEventLog).filter(PriceEventLog.event_type == price_changes.EVENT)
|
||||
if business_day_id:
|
||||
q = q.join(Order, Order.id == PriceEventLog.order_id).filter(Order.business_day_id == business_day_id)
|
||||
elif from_dt and to_dt:
|
||||
q = q.filter(PriceEventLog.applied_at >= history_since(from_dt, 'reports'),
|
||||
PriceEventLog.applied_at <= parse_api_datetime(to_dt))
|
||||
if applied_by:
|
||||
q = q.filter(PriceEventLog.applied_by_user_id == applied_by)
|
||||
events = q.order_by(PriceEventLog.applied_at.desc()).all()
|
||||
tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
|
||||
orders_map = {o.id: o for o in db.query(Order).filter(Order.id.in_({e.order_id for e in events})).all()} if events else {}
|
||||
rows, by_person, total = [], {}, 0.0
|
||||
for ev in events:
|
||||
row = price_changes.event_out(ev, db)
|
||||
row["at"] = _dt(ev.applied_at)
|
||||
order = orders_map.get(ev.order_id)
|
||||
row["table_name"] = tables_map.get(order.table_id) if order is not None and order.table_id else None
|
||||
row["value"] = round((ev.delta_amount or 0.0) * (ev.quantity or 1.0), 2)
|
||||
total += row["value"]
|
||||
p = by_person.setdefault(ev.applied_by_user_id, {"user_id": ev.applied_by_user_id, "name": row["by"], "count": 0, "total_value": 0.0})
|
||||
p["count"] += 1
|
||||
p["total_value"] = round(p["total_value"] + row["value"], 2)
|
||||
rows.append(row)
|
||||
return {"changes": rows, "total_value": round(total, 2), "count": len(rows),
|
||||
"by_person": sorted(by_person.values(), key=lambda x: x["total_value"])}
|
||||
|
||||
|
||||
@router.get("/price-changes/export")
|
||||
def price_changes_export(
|
||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||
to_dt: Optional[str] = Query(default=None, alias="to"),
|
||||
business_day_id: Optional[int] = None,
|
||||
applied_by: Optional[int] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_reports),
|
||||
):
|
||||
data = price_changes_report(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, applied_by=applied_by, db=db, user=user)
|
||||
rows = [{"id": c["id"], "order_id": c["order_id"], "table": c["table_name"] or "", "product": c["product_name"] or "",
|
||||
"quantity": c["quantity"], "before": c["before"], "after": c["after"], "value": c["value"], "stage": c["stage"] or "",
|
||||
"by": c["by"] or "", "approved_by": c["approved_by"] or "", "reason": c["reason"] or "", "at": c["at"]} for c in data["changes"]]
|
||||
fields = ["id", "order_id", "table", "product", "quantity", "before", "after", "value", "stage", "by", "approved_by", "reason", "at"]
|
||||
return csv_export.response(db, rows, fields, f"price-changes-{(from_dt or '')[:10]}.csv", times=("at",))
|
||||
|
||||
|
||||
@router.get("/discounts")
|
||||
def discounts_report(
|
||||
from_dt: Optional[str] = Query(default=None, alias="from"),
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Scenes (owner 2026-11-21): list them (everyone in the dashboard), make, change, delete and turn
|
||||
them on or off (`core.scenes.manage`). services/scenes.py says what follows a scene."""
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Response
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.access.deps import require
|
||||
from core.errors import XeniaError
|
||||
from core.timeutil import utcnow
|
||||
from database import get_db
|
||||
from models.scene import Scene
|
||||
from services import scenes as svc
|
||||
|
||||
router = APIRouter()
|
||||
VIEW = "core.dashboard.access"
|
||||
KEY = "core.scenes.manage"
|
||||
COLOUR = r"^#[0-9a-fA-F]{6}$"
|
||||
|
||||
|
||||
class SceneBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=60)
|
||||
color: Optional[str] = Field(default=None, pattern=COLOUR)
|
||||
description: Optional[str] = Field(default=None, max_length=200)
|
||||
|
||||
|
||||
class ActiveBody(BaseModel):
|
||||
active: bool
|
||||
until: Optional[datetime] = None # on until then (UTC); None: until turned off
|
||||
|
||||
|
||||
def _scene(db, sid: int) -> Scene:
|
||||
s = db.get(Scene, sid)
|
||||
if s is None:
|
||||
raise XeniaError("scene.not_found", scene_id=sid)
|
||||
return s
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_scenes(db: Session = Depends(get_db), user=Depends(require(VIEW))):
|
||||
return [svc.out(s) for s in db.query(Scene).order_by(Scene.sort_order, Scene.id)]
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
def create_scene(body: SceneBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
s = Scene(name=body.name.strip(), color=body.color, description=(body.description or "").strip() or None,
|
||||
sort_order=db.query(Scene).count())
|
||||
db.add(s)
|
||||
db.commit()
|
||||
db.refresh(s)
|
||||
svc.changed(db)
|
||||
return svc.out(s)
|
||||
|
||||
|
||||
@router.put("/{scene_id}")
|
||||
def update_scene(scene_id: int, body: SceneBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
s = _scene(db, scene_id)
|
||||
s.name, s.color, s.description = body.name.strip(), body.color, (body.description or "").strip() or None
|
||||
db.commit()
|
||||
svc.changed(db)
|
||||
return svc.out(s)
|
||||
|
||||
|
||||
@router.put("/{scene_id}/active")
|
||||
def set_active(scene_id: int, body: ActiveBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
s = _scene(db, scene_id)
|
||||
if body.active and body.until is not None and svc._aware(body.until) <= utcnow():
|
||||
raise XeniaError("scene.until_past")
|
||||
s.is_active = body.active
|
||||
s.activated_at = utcnow() if body.active else None
|
||||
s.until = body.until if body.active else None
|
||||
db.commit()
|
||||
svc.changed(db)
|
||||
return svc.out(s)
|
||||
|
||||
|
||||
@router.delete("/{scene_id}", status_code=204)
|
||||
def delete_scene(scene_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
|
||||
"""The signage lines that played only in it are turned off (they would otherwise play always)."""
|
||||
s = _scene(db, scene_id)
|
||||
from models.signage import SignageScheduleItem
|
||||
for item in db.query(SignageScheduleItem).filter(SignageScheduleItem.scene_id == s.id):
|
||||
item.scene_id = None
|
||||
item.enabled = False
|
||||
db.delete(s)
|
||||
db.commit()
|
||||
svc.changed(db)
|
||||
return Response(status_code=204)
|
||||
+994
-190
File diff suppressed because it is too large
Load Diff
@@ -59,11 +59,35 @@ class ExpensePaymentOut(BaseModel):
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
class ExpenseLineIn(BaseModel):
|
||||
description: str
|
||||
quantity: float = 1.0
|
||||
unit_price: float
|
||||
vat_rate: float = 0.0
|
||||
|
||||
|
||||
class ExpenseLineOut(ExpenseLineIn):
|
||||
id: int
|
||||
net: float
|
||||
vat: float
|
||||
total: float
|
||||
|
||||
|
||||
class ExpenseDocumentOut(BaseModel):
|
||||
id: int
|
||||
filename: str
|
||||
content_type: str
|
||||
size: int
|
||||
uploaded_at: datetime
|
||||
uploaded_by_name: Optional[str] = None
|
||||
|
||||
|
||||
class ExpenseCreate(BaseModel):
|
||||
description: str
|
||||
category: str
|
||||
contact_id: Optional[int] = None
|
||||
total_amount: float
|
||||
total_amount: Optional[float] = None # left out when the lines make it
|
||||
lines: Optional[List[ExpenseLineIn]] = None
|
||||
due_date: Optional[datetime] = None
|
||||
business_day_id: Optional[int] = None
|
||||
notes: Optional[str] = None
|
||||
@@ -80,6 +104,7 @@ class ExpenseUpdate(BaseModel):
|
||||
category: Optional[str] = None
|
||||
contact_id: Optional[int] = None
|
||||
total_amount: Optional[float] = None
|
||||
lines: Optional[List[ExpenseLineIn]] = None # given: replaces the lines ([] = none)
|
||||
due_date: Optional[datetime] = None
|
||||
notes: Optional[str] = None
|
||||
|
||||
@@ -107,5 +132,9 @@ class ExpenseOut(BaseModel):
|
||||
created_at: datetime
|
||||
notes: Optional[str] = None
|
||||
payments: List[ExpensePaymentOut] = []
|
||||
lines: List[ExpenseLineOut] = []
|
||||
net_amount: Optional[float] = None # from the lines
|
||||
vat_amount: Optional[float] = None
|
||||
documents: List[ExpenseDocumentOut] = []
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@@ -26,6 +26,9 @@ class OrderItemInput(BaseModel):
|
||||
is_service_item: bool = False # priceless: print-once ephemeral; priced: saved as real item
|
||||
course_id: Optional[int] = None
|
||||
source: Optional[str] = None # set by the server (4.8): waiter | counter | qr | online
|
||||
# a price changed by hand (6F.3), set by the server: the reason and the approving manager
|
||||
price_reason: Optional[str] = None
|
||||
price_approved_by: Optional[int] = None
|
||||
|
||||
|
||||
class AddItemsRequest(BaseModel):
|
||||
@@ -37,6 +40,8 @@ class AddItemsRequest(BaseModel):
|
||||
class ProductNameOut(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
one_more_enabled: bool = False # 6F.5: the line shows +1
|
||||
unit_type: Optional[str] = None
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
@@ -68,6 +73,7 @@ class OrderItemOut(BaseModel):
|
||||
source: Optional[str] = None # waiter | counter | qr | online (4.8); None = before 4.8
|
||||
deal_id: Optional[int] = None
|
||||
linked_item_id: Optional[int] = None
|
||||
split_from_id: Optional[int] = None # 6F.4: the line it was cut from
|
||||
system_key: Optional[str] = None # a line the system added: "delivery_fee" (phase 3S, S.5)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@@ -308,10 +308,15 @@ class PriceEventOut(BaseModel):
|
||||
conditions_snapshot: Optional[dict]
|
||||
selected_item_ids: Optional[List[int]]
|
||||
applied_at: datetime
|
||||
# manual_price (6F.3)
|
||||
approved_by_user_id: Optional[int] = None
|
||||
stage: Optional[str] = None
|
||||
quantity: Optional[float] = None
|
||||
# Resolved names (joined at query time)
|
||||
modifier_name: Optional[str] = None
|
||||
deal_name: Optional[str] = None
|
||||
applied_by_username: Optional[str] = None
|
||||
approved_by_username: Optional[str] = None
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ from typing import Optional, List, Any, Literal, Dict
|
||||
|
||||
from core.sales_points import ALL as _SALES_POINTS, sold_at as _sold_at
|
||||
from core.allergens import of as _allergens_of
|
||||
from core.menu_languages import of as _menu_tr_of, _load as _menu_tr
|
||||
from core.menu_languages import of as _menu_tr_of, _load as _menu_tr, names_of as _choice_names
|
||||
|
||||
SalesPoint = Literal["in_store", "in_store_takeaway", "qr_table", "online_takeaway", "online_delivery", "online_preorder"]
|
||||
|
||||
@@ -76,6 +76,7 @@ class ModifierGroupCreate(BaseModel):
|
||||
modifier_type: str # "option" | "ingredient" | "preference"
|
||||
name: str
|
||||
sort_order: int = 0
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class ModifierGroupOut(BaseModel):
|
||||
@@ -84,9 +85,15 @@ class ModifierGroupOut(BaseModel):
|
||||
modifier_type: str
|
||||
name: str
|
||||
sort_order: int = 0
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@field_validator("translations", mode="before")
|
||||
@classmethod
|
||||
def _names(cls, v):
|
||||
return {k: x for k, x in _menu_tr(v).items() if isinstance(x, str)}
|
||||
|
||||
|
||||
# ── Quick Options ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -98,6 +105,7 @@ class ProductQuickOptionCreate(BaseModel):
|
||||
is_favorite: bool = False
|
||||
favorite_sort_order: int = 0
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class ProductQuickOptionOut(BaseModel):
|
||||
@@ -110,9 +118,15 @@ class ProductQuickOptionOut(BaseModel):
|
||||
is_favorite: bool = False
|
||||
favorite_sort_order: int = 0
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@field_validator("translations", mode="before")
|
||||
@classmethod
|
||||
def _names(cls, v):
|
||||
return {k: x for k, x in _menu_tr(v).items() if isinstance(x, str)}
|
||||
|
||||
|
||||
# ── Options ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -124,6 +138,7 @@ class OptionSubChoice(BaseModel):
|
||||
allow_multiple: bool = False
|
||||
# When True renders as half-width card on the PWA
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class ProductOptionBase(BaseModel):
|
||||
@@ -137,6 +152,7 @@ class ProductOptionBase(BaseModel):
|
||||
# When True renders the option itself as half-width card on the PWA
|
||||
is_compact: bool = False
|
||||
group_id: Optional[int] = None
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class ProductOptionCreate(ProductOptionBase):
|
||||
@@ -168,6 +184,7 @@ class ProductOptionOut(ProductOptionBase):
|
||||
'favorite_sort_order': getattr(data, 'favorite_sort_order', 0) or 0,
|
||||
'is_compact': getattr(data, 'is_compact', False) or False,
|
||||
'group_id': getattr(data, 'group_id', None),
|
||||
'translations': _choice_names(data),
|
||||
}
|
||||
return data
|
||||
|
||||
@@ -182,6 +199,7 @@ class ProductIngredientBase(BaseModel):
|
||||
# When True renders as half-width card on the PWA
|
||||
is_compact: bool = False
|
||||
group_id: Optional[int] = None
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class ProductIngredientCreate(ProductIngredientBase):
|
||||
@@ -194,6 +212,11 @@ class ProductIngredientOut(ProductIngredientBase):
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@field_validator("translations", mode="before")
|
||||
@classmethod
|
||||
def _names(cls, v):
|
||||
return {k: x for k, x in _menu_tr(v).items() if isinstance(x, str)}
|
||||
|
||||
|
||||
# ── Sub-choices (nested under a preference choice) ────────────────────────────
|
||||
|
||||
@@ -202,6 +225,7 @@ class SubChoice(BaseModel):
|
||||
extra_cost: float = 0.0
|
||||
is_default: bool = False
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
# ── Shared subset (set-level, shown for all non-disabling choices) ─────────────
|
||||
@@ -211,10 +235,12 @@ class SharedSubsetChoice(BaseModel):
|
||||
extra_cost: float = 0.0
|
||||
is_default: bool = False
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class SharedSubset(BaseModel):
|
||||
name: str
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
choices: List[SharedSubsetChoice] = []
|
||||
|
||||
|
||||
@@ -227,6 +253,7 @@ class PreferenceChoiceCreate(BaseModel):
|
||||
disables_subset: bool = False
|
||||
# When True renders as half-width card on the PWA
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class PreferenceChoiceOut(BaseModel):
|
||||
@@ -237,6 +264,7 @@ class PreferenceChoiceOut(BaseModel):
|
||||
sub_choices: List[SubChoice] = []
|
||||
disables_subset: bool = False
|
||||
is_compact: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@@ -260,6 +288,7 @@ class PreferenceChoiceOut(BaseModel):
|
||||
'sub_choices': parsed,
|
||||
'disables_subset': data.disables_subset or False,
|
||||
'is_compact': getattr(data, 'is_compact', False) or False,
|
||||
'translations': _choice_names(data),
|
||||
}
|
||||
return data
|
||||
|
||||
@@ -274,6 +303,7 @@ class PreferenceSetCreate(BaseModel):
|
||||
group_id: Optional[int] = None
|
||||
allow_multi_select: bool = False
|
||||
allow_choice_quantity: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
|
||||
class PreferenceSetOut(BaseModel):
|
||||
@@ -288,6 +318,7 @@ class PreferenceSetOut(BaseModel):
|
||||
group_id: Optional[int] = None
|
||||
allow_multi_select: bool = False
|
||||
allow_choice_quantity: bool = False
|
||||
translations: Dict[str, str] = {} # its name per language (0042)
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@@ -315,6 +346,7 @@ class PreferenceSetOut(BaseModel):
|
||||
'group_id': getattr(data, 'group_id', None),
|
||||
'allow_multi_select': getattr(data, 'allow_multi_select', False) or False,
|
||||
'allow_choice_quantity': getattr(data, 'allow_choice_quantity', False) or False,
|
||||
'translations': _choice_names(data),
|
||||
}
|
||||
return data
|
||||
|
||||
@@ -354,6 +386,7 @@ class ProductBase(BaseModel):
|
||||
cost_breakdown: Optional[List[CostBreakdownItem]] = None
|
||||
# Quick Add
|
||||
quick_add_enabled: bool = True
|
||||
one_more_enabled: bool = False # 6F.5
|
||||
# Tags
|
||||
tags: Optional[List[str]] = None
|
||||
# The EU allergens (plan step 6.3): {key: "contains" | "may_contain"}, core/allergens.py
|
||||
@@ -405,6 +438,7 @@ class ProductUpdate(BaseModel):
|
||||
cost_breakdown: Optional[List[CostBreakdownItem]] = None
|
||||
# Quick Add
|
||||
quick_add_enabled: Optional[bool] = None
|
||||
one_more_enabled: Optional[bool] = None # 6F.5
|
||||
# Tags
|
||||
tags: Optional[List[str]] = None
|
||||
allergens: Optional[Dict[str, str]] = None # None = unchanged, {} = none
|
||||
@@ -478,6 +512,7 @@ class ProductOut(ProductBase):
|
||||
'cost_simple': data.cost_simple,
|
||||
'cost_breakdown': parsed,
|
||||
'quick_add_enabled': getattr(data, 'quick_add_enabled', True),
|
||||
'one_more_enabled': bool(getattr(data, 'one_more_enabled', False)),
|
||||
'tags': json.loads(data.tags) if isinstance(getattr(data, 'tags', None), str) else (getattr(data, 'tags', None) or []),
|
||||
'allergens': _allergens_of(data),
|
||||
'translations': _menu_tr_of(data),
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Order channel prices (UI review 2026-11-20): a product's price at a sales point.
|
||||
|
||||
A rule says, for one or more sales points (core/sales_points.py), what happens to the price:
|
||||
`set` it (one product only), `add_amount` (± euros) or `add_percent` (± %), then optionally
|
||||
rounds it (the price modifiers' rounding modes). It applies to the products it lists, to the
|
||||
products of the categories it lists, or — listing neither — to everything sold there.
|
||||
|
||||
The most precise rule wins, one per product and sales point:
|
||||
the product's own rule > a rule of one of its categories > a rule for the whole channel
|
||||
(on a tie, the newest). No rule: the default price. The channel price is the base that the price
|
||||
modifiers and deals (services/pricing.py) then work on, so it reaches every till, phone, menu and
|
||||
the cloud's ordering apps (cloud_sync prices each sales point through resolve_price).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from core import sales_points
|
||||
|
||||
ACTIONS = ("set", "add_amount", "add_percent")
|
||||
ROUNDING = ("0.05", "0.10", "0.20", "0.50", "x.99", "x.00")
|
||||
LEVELS = {"product": 3, "category": 2, "channel": 1}
|
||||
|
||||
|
||||
def _ids(raw) -> list:
|
||||
try:
|
||||
v = json.loads(raw) if isinstance(raw, str) else (raw or [])
|
||||
except ValueError:
|
||||
return []
|
||||
return [x for x in v if x is not None]
|
||||
|
||||
|
||||
def points_of(rule) -> list[str]:
|
||||
return [sp for sp in _ids(rule.sales_points) if sp in sales_points.ALL]
|
||||
|
||||
|
||||
def products_of(rule) -> list[int]:
|
||||
return [int(x) for x in _ids(rule.product_ids)]
|
||||
|
||||
|
||||
def categories_of(rule) -> list[int]:
|
||||
return [int(x) for x in _ids(rule.category_ids)]
|
||||
|
||||
|
||||
def level_of(rule, product) -> int:
|
||||
"""How precisely the rule names this product (0 = not at all)."""
|
||||
if product.id in products_of(rule):
|
||||
return LEVELS["product"]
|
||||
cats = set(categories_of(rule))
|
||||
if cats:
|
||||
mine = set(product.category_ids or []) | ({product.primary_category_id} if product.primary_category_id else set())
|
||||
return LEVELS["category"] if cats & mine else 0
|
||||
return LEVELS["channel"] if not products_of(rule) else 0
|
||||
|
||||
|
||||
def active_rules(db) -> list:
|
||||
from models.pricing import ChannelPrice
|
||||
return db.query(ChannelPrice).filter(ChannelPrice.is_active == True).order_by(ChannelPrice.id).all() # noqa: E712
|
||||
|
||||
|
||||
def winner(rules, product, point: str):
|
||||
"""The rule that sets the product's price at this sales point, or None."""
|
||||
best, best_level = None, 0
|
||||
for r in rules:
|
||||
if point not in points_of(r):
|
||||
continue
|
||||
lv = level_of(r, product)
|
||||
if lv and lv >= best_level: # >=: the newest of the same precision
|
||||
best, best_level = r, lv
|
||||
return best
|
||||
|
||||
|
||||
def apply(rule, price: float) -> float:
|
||||
from services.pricing import _apply_action
|
||||
return _apply_action(price, rule.action_type, rule.value, rule.round_to)
|
||||
|
||||
|
||||
def price_at(db, product, point: str, rules=None) -> tuple[float, object | None]:
|
||||
"""(the product's price at the sales point before modifiers and deals, the rule or None)."""
|
||||
rules = active_rules(db) if rules is None else rules
|
||||
r = winner(rules, product, point)
|
||||
return (round(apply(r, product.base_price), 4), r) if r else (product.base_price, None)
|
||||
|
||||
|
||||
def check(fields: dict) -> None:
|
||||
"""Refuse a rule that can't work (XeniaError)."""
|
||||
from core.errors import XeniaError
|
||||
points = [sp for sp in fields.get("sales_points") or [] if sp in sales_points.ALL]
|
||||
if not points:
|
||||
raise XeniaError("validation.missing", field="sales_points")
|
||||
if fields.get("action_type") not in ACTIONS:
|
||||
raise XeniaError("validation.choice", field="action_type", value=fields.get("action_type"))
|
||||
if fields.get("value") is None:
|
||||
raise XeniaError("validation.missing", field="value")
|
||||
if fields.get("round_to") not in (None, "", *ROUNDING):
|
||||
raise XeniaError("validation.choice", field="round_to", value=fields.get("round_to"))
|
||||
if fields["action_type"] == "set":
|
||||
if fields["value"] < 0:
|
||||
raise XeniaError("validation.positive", field="value")
|
||||
if len(fields.get("product_ids") or []) != 1 or fields.get("category_ids"):
|
||||
raise XeniaError("channel_price.set_one_product")
|
||||
|
||||
|
||||
def out(rule) -> dict:
|
||||
return {
|
||||
"id": rule.id, "name": rule.name, "sales_points": points_of(rule),
|
||||
"product_ids": products_of(rule), "category_ids": categories_of(rule),
|
||||
"level": "product" if products_of(rule) else "category" if categories_of(rule) else "channel",
|
||||
"action_type": rule.action_type, "value": rule.value, "round_to": rule.round_to or None,
|
||||
"is_active": bool(rule.is_active), "created_at": rule.created_at, "updated_at": rule.updated_at,
|
||||
}
|
||||
|
||||
|
||||
def own_rule(rules, product_id: int, point: str):
|
||||
"""The product's own rule for one sales point (what the product editor edits), or None."""
|
||||
for r in rules:
|
||||
if products_of(r) == [product_id] and points_of(r) == [point] and not categories_of(r):
|
||||
return r
|
||||
return None
|
||||
|
||||
|
||||
def product_view(db, product) -> list[dict]:
|
||||
"""Per sales point the product is sold at: the default price, the price there, which rule
|
||||
makes it, the product's own rule (to edit) and the rule that counts without it (fallback)."""
|
||||
from models.pricing import ChannelPrice
|
||||
rules = active_rules(db)
|
||||
every = db.query(ChannelPrice).order_by(ChannelPrice.id).all()
|
||||
rows = []
|
||||
for sp in sales_points.sold_at(product):
|
||||
price, rule = price_at(db, product, sp, rules)
|
||||
own = own_rule(every, product.id, sp)
|
||||
# what counts without the product's own rule (the category's, the channel's or none)
|
||||
fallback = winner([r for r in rules if own is None or r.id != own.id], product, sp)
|
||||
rows.append({"sales_point": sp, "base_price": product.base_price, "price": round(price, 2),
|
||||
"rule": out(rule) if rule else None, "own": out(own) if own else None,
|
||||
"fallback": out(fallback) if fallback else None})
|
||||
return rows
|
||||
@@ -289,7 +289,7 @@ def menu_snapshot(db) -> tuple[dict, list]:
|
||||
"digital_image_url": p.digital_image_url,
|
||||
"image_url": p.image_url,
|
||||
"quick_options": [{"id": o.id, "name": o.name, "price": o.price,
|
||||
"names": menu_languages.quick_texts(o.name, menu_languages.of(p))} for o in p.quick_options],
|
||||
"names": menu_languages.quick_texts(o.name, menu_languages.of(p), menu_languages.names_of(o))} for o in p.quick_options],
|
||||
"allergens": allergens.of(p), # 6.3: {key: "contains" | "may_contain"}
|
||||
**menu_languages.product_texts(p), # 6.4: names / descriptions {language: text}
|
||||
})
|
||||
@@ -713,7 +713,7 @@ async def _wait_for_site_id(max_seconds: int = 30) -> None:
|
||||
# not at the next 5-minute tick (phase 3S): request_menu_push() from any thread wakes the
|
||||
# worker; edits in a row within MENU_SETTLE_SECONDS become one push.
|
||||
MENU_SETTLE_SECONDS = 5
|
||||
MENU_PATHS = ("/api/products", "/api/pricing", "/api/connect/fees", "/api/data-transfer/import",
|
||||
MENU_PATHS = ("/api/products", "/api/pricing", "/api/scenes", "/api/connect/fees", "/api/data-transfer/import",
|
||||
"/api/connect/qr", "/api/tables") # S.7: the tables' QR codes travel with the menu
|
||||
_menu_wake: "asyncio.Event | None" = None
|
||||
_menu_loop = None
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""The files kept with expenses (2026-11-20): an invoice as a PDF or a photo of a receipt.
|
||||
|
||||
Stored under MEDIA_DIR/expenses/<expense id>/<random name><ext> (inside the site's data, next to
|
||||
pos.db, so a backup takes them along). The type comes from the file's first bytes, not from
|
||||
the browser: PDF, JPG, PNG, WebP or HEIC, at most 15 MB.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
|
||||
from core.errors import XeniaError
|
||||
from services.media import MEDIA_DIR
|
||||
|
||||
MAX_BYTES = 15 * 1024 * 1024
|
||||
TYPES = { # magic bytes -> (content type, extension)
|
||||
b"%PDF": ("application/pdf", ".pdf"),
|
||||
b"\xff\xd8\xff": ("image/jpeg", ".jpg"),
|
||||
b"\x89PNG": ("image/png", ".png"),
|
||||
}
|
||||
|
||||
|
||||
def _dir(expense_id: int) -> str:
|
||||
return os.path.join(MEDIA_DIR, "expenses", str(int(expense_id)))
|
||||
|
||||
|
||||
def _kind(head: bytes) -> tuple[str, str] | None:
|
||||
for magic, kind in TYPES.items():
|
||||
if head.startswith(magic):
|
||||
return kind
|
||||
if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
|
||||
return "image/webp", ".webp"
|
||||
if head[4:8] == b"ftyp" and head[8:12] in (b"heic", b"heix", b"mif1", b"msf1", b"hevc"):
|
||||
return "image/heic", ".heic"
|
||||
return None
|
||||
|
||||
|
||||
def save(expense_id: int, upload) -> tuple[str, str, int]:
|
||||
"""Write the upload → (stored name, content type, size). Refuses other types and big files."""
|
||||
head = upload.file.read(16)
|
||||
kind = _kind(head)
|
||||
if not kind:
|
||||
raise XeniaError("expense.document_type")
|
||||
os.makedirs(_dir(expense_id), exist_ok=True)
|
||||
name = uuid.uuid4().hex + kind[1]
|
||||
target = os.path.join(_dir(expense_id), name)
|
||||
size = len(head)
|
||||
with open(target, "wb") as out:
|
||||
out.write(head)
|
||||
while chunk := upload.file.read(1024 * 1024):
|
||||
size += len(chunk)
|
||||
if size > MAX_BYTES:
|
||||
out.close()
|
||||
os.remove(target)
|
||||
raise XeniaError("expense.document_too_big", max_mb=MAX_BYTES // (1024 * 1024))
|
||||
out.write(chunk)
|
||||
return name, kind[0], size
|
||||
|
||||
|
||||
def path(doc) -> str | None:
|
||||
p = os.path.join(_dir(doc.expense_id), os.path.basename(doc.stored_name))
|
||||
return p if os.path.isfile(p) else None
|
||||
|
||||
|
||||
def remove(doc) -> None:
|
||||
p = path(doc)
|
||||
if p:
|
||||
os.remove(p)
|
||||
|
||||
|
||||
def remove_all(expense_id: int) -> None:
|
||||
shutil.rmtree(_dir(expense_id), ignore_errors=True)
|
||||
|
||||
|
||||
def out(doc) -> dict:
|
||||
who = doc.uploaded_by
|
||||
return {"id": doc.id, "filename": doc.filename, "content_type": doc.content_type, "size": doc.size,
|
||||
"uploaded_at": doc.uploaded_at, "uploaded_by_name": (who.full_name or who.username) if who else None}
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Moves on the record (owner 2026-11-23, plan step 6F.4).
|
||||
|
||||
Every move between tables or orders is an `OrderMove` row with the lines that went
|
||||
(`OrderMoveItem`: the line and its quantity then):
|
||||
- `table_transfer`: the whole order went to another (free) table (POST /api/orders/{id}/transfer);
|
||||
- `items_moved`: chosen lines went to another open order (POST /api/orders/{id}/move-items);
|
||||
- `orders_merged`: an order was joined into another (POST /api/orders/{id}/merge).
|
||||
|
||||
A line keeps its id when it moves, so its path is its own moves. A line cut from another
|
||||
(`OrderItem.split_from_id`: a split, later a lowered quantity or a split payment) also carries
|
||||
the moves its parent had **before** the cut, however many times that happened. Combining lines
|
||||
moves the removed lines' moves to the line that stays (routers/orders.combine_items).
|
||||
|
||||
Readers: GET /api/orders/{id}/moves (the order's path and each line's), Reports → Moves
|
||||
(GET /api/reports/moves). The old OrderAuditLog rows stay as they were.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
KINDS = ("table_transfer", "items_moved", "orders_merged")
|
||||
|
||||
|
||||
def record(db, *, kind: str, source, target, items, user_id: int | None, from_table_id=None, to_table_id=None,
|
||||
approved_by: int | None = None):
|
||||
"""One move (flushed with the caller's commit). `source` / `target`: orders; `items`: lines."""
|
||||
from models.order import OrderMove, OrderMoveItem
|
||||
assert kind in KINDS, kind
|
||||
move = OrderMove(
|
||||
kind=kind, from_order_id=getattr(source, "id", None), to_order_id=getattr(target, "id", None),
|
||||
from_table_id=from_table_id if from_table_id is not None else getattr(source, "table_id", None),
|
||||
to_table_id=to_table_id if to_table_id is not None else getattr(target, "table_id", None),
|
||||
by_user_id=user_id, approved_by_user_id=approved_by,
|
||||
business_day_id=getattr(target, "business_day_id", None) or getattr(source, "business_day_id", None),
|
||||
)
|
||||
move.items = [OrderMoveItem(item_id=i.id, quantity=i.quantity) for i in items]
|
||||
db.add(move)
|
||||
return move
|
||||
|
||||
|
||||
def repoint(db, from_ids, to_id: int) -> None:
|
||||
"""Lines removed by a combine: their moves (and children) now belong to the line kept."""
|
||||
from models.order import OrderItem, OrderMoveItem
|
||||
from_ids = [i for i in from_ids if i != to_id]
|
||||
if not from_ids:
|
||||
return
|
||||
for mi in db.query(OrderMoveItem).filter(OrderMoveItem.item_id.in_(from_ids)).all():
|
||||
taken = db.query(OrderMoveItem).filter(OrderMoveItem.move_id == mi.move_id, OrderMoveItem.item_id == to_id).first()
|
||||
if taken is None:
|
||||
db.add(OrderMoveItem(move_id=mi.move_id, item_id=to_id, quantity=mi.quantity))
|
||||
else:
|
||||
taken.quantity = (taken.quantity or 0) + (mi.quantity or 0)
|
||||
db.delete(mi)
|
||||
db.query(OrderItem).filter(OrderItem.split_from_id.in_(from_ids)).update(
|
||||
{OrderItem.split_from_id: to_id}, synchronize_session=False)
|
||||
|
||||
|
||||
def _lineage(db, item):
|
||||
"""[(line id, moves up to when) …]: the line itself (all its moves), then each parent up to the
|
||||
moment the child was cut from it."""
|
||||
from models.order import OrderItem
|
||||
out, seen = [(item.id, None)], {item.id}
|
||||
child = item
|
||||
while child.split_from_id and child.split_from_id not in seen:
|
||||
parent = db.get(OrderItem, child.split_from_id)
|
||||
if parent is None:
|
||||
break
|
||||
out.append((parent.id, child.added_at))
|
||||
seen.add(parent.id)
|
||||
child = parent
|
||||
return out
|
||||
|
||||
|
||||
def item_moves(db, item) -> list:
|
||||
"""The moves a line went through, oldest first (its parents' before it was cut from them)."""
|
||||
from models.order import OrderMove, OrderMoveItem
|
||||
found = {}
|
||||
for line_id, until in _lineage(db, item):
|
||||
q = db.query(OrderMove).join(OrderMoveItem, OrderMoveItem.move_id == OrderMove.id).filter(OrderMoveItem.item_id == line_id)
|
||||
if until is not None:
|
||||
q = q.filter(OrderMove.at <= until)
|
||||
for m in q.all():
|
||||
found[m.id] = m
|
||||
return sorted(found.values(), key=lambda m: (m.at, m.id))
|
||||
|
||||
|
||||
def order_moves(db, order) -> list:
|
||||
"""The whole order's path: table transfers and merges into it, and the orders merged into it
|
||||
(their own transfers too), oldest first."""
|
||||
from models.order import OrderMove
|
||||
ids, todo, found = set(), [order.id], {}
|
||||
while todo:
|
||||
oid = todo.pop()
|
||||
if oid in ids:
|
||||
continue
|
||||
ids.add(oid)
|
||||
for m in db.query(OrderMove).filter(OrderMove.to_order_id == oid,
|
||||
OrderMove.kind.in_(("table_transfer", "orders_merged"))).all():
|
||||
found[m.id] = m
|
||||
if m.kind == "orders_merged" and m.from_order_id:
|
||||
todo.append(m.from_order_id)
|
||||
return sorted(found.values(), key=lambda m: (m.at, m.id))
|
||||
|
||||
|
||||
def _names(db):
|
||||
from models.table import Table
|
||||
from models.user import User
|
||||
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
|
||||
users = {u.id: (u.nickname or u.full_name or u.username) for u in db.query(User).all()}
|
||||
return tables, users
|
||||
|
||||
|
||||
def move_out(m, tables, users, item_names=None) -> dict:
|
||||
return {
|
||||
"id": m.id, "kind": m.kind, "at": m.at,
|
||||
"from_order_id": m.from_order_id, "to_order_id": m.to_order_id,
|
||||
"from_table_id": m.from_table_id, "to_table_id": m.to_table_id,
|
||||
"from_table": tables.get(m.from_table_id), "to_table": tables.get(m.to_table_id),
|
||||
"by_id": m.by_user_id, "by": users.get(m.by_user_id),
|
||||
"approved_by": users.get(m.approved_by_user_id),
|
||||
"items": [{"item_id": i.item_id, "quantity": i.quantity,
|
||||
**({"name": item_names.get(i.item_id)} if item_names is not None else {})} for i in m.items],
|
||||
}
|
||||
|
||||
|
||||
def for_order(db, order) -> dict:
|
||||
"""GET /api/orders/{id}/moves: {order: [moves of the whole order], items: {line id: [moves]}}
|
||||
(only lines that moved)."""
|
||||
tables, users = _names(db)
|
||||
per_item = {}
|
||||
for item in order.items:
|
||||
ms = item_moves(db, item)
|
||||
if ms:
|
||||
per_item[str(item.id)] = [move_out(m, tables, users) for m in ms]
|
||||
return {"order": [move_out(m, tables, users) for m in order_moves(db, order)], "items": per_item}
|
||||
@@ -227,6 +227,8 @@ def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | No
|
||||
from services.pricing import OrderContext, build_active_price_group_ids, resolve_price
|
||||
now = utcnow()
|
||||
active = build_active_price_group_ids(db, now)
|
||||
from services.pricing import build_active_scene_ids
|
||||
scenes = build_active_scene_ids(db, now)
|
||||
channel = point or point_for(order_type)
|
||||
cart = list(existing_cart or [])
|
||||
out = []
|
||||
@@ -236,7 +238,7 @@ def price_lines(db, lines: list[Line], order_type: str, existing_cart: list | No
|
||||
raise _bad(n, "not_sold_here")
|
||||
here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids,
|
||||
"quantity": line.quantity, "unit_price": p.base_price + line.extra}
|
||||
ctx = OrderContext(channel=channel, now=now, cart_items=cart + [here], active_price_group_ids=active)
|
||||
ctx = OrderContext(channel=channel, now=now, cart_items=cart + [here], active_price_group_ids=active, active_scene_ids=scenes)
|
||||
unit, events = resolve_price(p, line.quantity, line.extra, ctx, db)
|
||||
out.append((unit, events))
|
||||
cart.append({**here, "unit_price": unit})
|
||||
@@ -250,11 +252,13 @@ def unit_prices(db, products, point: str, now=None) -> list[float]:
|
||||
from services.pricing import OrderContext, build_active_price_group_ids, resolve_price
|
||||
now = now or utcnow()
|
||||
active = build_active_price_group_ids(db, now)
|
||||
from services.pricing import build_active_scene_ids
|
||||
scenes = build_active_scene_ids(db, now)
|
||||
out = []
|
||||
for p in products:
|
||||
here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids,
|
||||
"quantity": 1, "unit_price": p.base_price}
|
||||
ctx = OrderContext(channel=point, now=now, cart_items=[here], active_price_group_ids=active)
|
||||
ctx = OrderContext(channel=point, now=now, cart_items=[here], active_price_group_ids=active, active_scene_ids=scenes)
|
||||
out.append(resolve_price(p, 1, 0.0, ctx, db)[0])
|
||||
return out
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Prices changed by hand, on the record (owner 2026-11-23, plan step 6F.3).
|
||||
|
||||
Who may change a line's price, in three levels like every permission:
|
||||
- the venue (setting `orders.price_change`): `off` | `before_sending` (only in the cart, before
|
||||
the line is sent) | `anytime` (also a line already sent or served; the default, as before 6F.3);
|
||||
- the keys: `ordering.prices.modify` (in the cart; the counter's % discount too) and
|
||||
`ordering.prices.modify_sent` (a line already sent), role defaults per venue, changed per person;
|
||||
both may be approved once by a manager's PIN (D-10);
|
||||
- `orders.price_change_reason`: when on, a by-hand price needs a reason (the venue's quick
|
||||
reasons, `orders.price_change_reasons`, or typed).
|
||||
|
||||
Every change writes one `PriceEventLog` row, `event_type = "manual_price"`: the line, its unit price
|
||||
before and after, the change, the quantity, who, the approving manager, the stage
|
||||
(cart | sent | served) and the reason (`waiter_note`), plus an `OrderAuditLog` `PRICE_CHANGED`.
|
||||
Rows are never deleted; combining lines moves them to the kept line (orders.combine_items).
|
||||
Who sees them: `ordering.prices.view_changes` (GET /api/pricing/events/order/{id},
|
||||
GET /api/orders/{id}/items/{item}/price-changes, Reports → Cancellations, discounts and price changes).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from core.errors import XeniaError
|
||||
|
||||
EVENT = "manual_price"
|
||||
MODES = ("off", "before_sending", "anytime")
|
||||
STAGES = ("cart", "sent", "served")
|
||||
REASON_MAX = 200
|
||||
|
||||
|
||||
def _setting(db, key: str, default: str) -> str:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
return row.value if row is not None and row.value not in (None, "") else default
|
||||
|
||||
|
||||
def mode(db) -> str:
|
||||
v = _setting(db, "orders.price_change", "anytime")
|
||||
return v if v in MODES else "anytime"
|
||||
|
||||
|
||||
def reason_required(db) -> bool:
|
||||
return _setting(db, "orders.price_change_reason", "false") == "true"
|
||||
|
||||
|
||||
def quick_reasons(db) -> list[str]:
|
||||
try:
|
||||
v = json.loads(_setting(db, "orders.price_change_reasons", "[]"))
|
||||
except ValueError:
|
||||
return []
|
||||
return [str(x).strip() for x in v if isinstance(x, str) and x.strip()] if isinstance(v, list) else []
|
||||
|
||||
|
||||
def clean_reason(reason) -> str | None:
|
||||
text = " ".join(str(reason or "").split())[:REASON_MAX]
|
||||
return text or None
|
||||
|
||||
|
||||
def check(db, *, sent: bool, reason=None, by_hand: bool = True) -> str | None:
|
||||
"""Refuse a price change the venue doesn't allow (order.price_change_off /
|
||||
order.price_change_sent_off) or one without its reason (order.price_reason_required, only for
|
||||
a price typed by hand: the counter's % discount has none). Returns the cleaned reason."""
|
||||
m = mode(db)
|
||||
if m == "off":
|
||||
raise XeniaError("order.price_change_off")
|
||||
if sent and m != "anytime":
|
||||
raise XeniaError("order.price_change_sent_off")
|
||||
text = clean_reason(reason)
|
||||
if by_hand and text is None and reason_required(db):
|
||||
raise XeniaError("order.price_reason_required")
|
||||
return text
|
||||
|
||||
|
||||
def stage_of(item) -> str:
|
||||
"""Where a line is when its price changes: in the cart (being added), sent, or served."""
|
||||
if item is None or getattr(item, "id", None) is None:
|
||||
return "cart"
|
||||
return "served" if getattr(item, "kds_status", None) == "served" else "sent"
|
||||
|
||||
|
||||
def record(db, *, item, before: float, after: float, user_id: int | None, stage: str,
|
||||
reason: str | None = None, approved_by: int | None = None, audit: bool = True):
|
||||
"""One manual_price event for `item` (flushed with the caller's commit) and its audit row."""
|
||||
from models.order import OrderAuditLog
|
||||
from models.pricing import PriceEventLog
|
||||
before, after = round(float(before), 2), round(float(after), 2)
|
||||
if abs(after - before) < 0.005:
|
||||
return None
|
||||
ev = PriceEventLog(
|
||||
order_id=item.order_id, order_item_id=item.id, event_type=EVENT,
|
||||
price_before=before, price_after=after, delta_amount=round(after - before, 2),
|
||||
applied_by_user_id=user_id, approved_by_user_id=approved_by, waiter_note=reason,
|
||||
stage=stage if stage in STAGES else "cart", quantity=item.quantity,
|
||||
)
|
||||
db.add(ev)
|
||||
if audit:
|
||||
db.add(OrderAuditLog(order_id=item.order_id, event_type="PRICE_CHANGED", waiter_id=user_id,
|
||||
item_ids=json.dumps([item.id]),
|
||||
note=f"{before:.2f} → {after:.2f}" + (f" · {reason}" if reason else "")
|
||||
+ (f" · approved by user {approved_by}" if approved_by else "")))
|
||||
return ev
|
||||
|
||||
|
||||
def _name(user) -> str | None:
|
||||
return (user.nickname or user.full_name or user.username) if user is not None else None
|
||||
|
||||
|
||||
def event_out(ev, db) -> dict:
|
||||
"""One manual_price event for the apps and the reports."""
|
||||
item = ev.order_item
|
||||
return {
|
||||
"id": ev.id, "order_id": ev.order_id, "item_id": ev.order_item_id,
|
||||
"product_name": item.product_name if item is not None else None,
|
||||
"before": ev.price_before, "after": ev.price_after, "delta": ev.delta_amount,
|
||||
"quantity": ev.quantity, "stage": ev.stage, "reason": ev.waiter_note,
|
||||
"by_id": ev.applied_by_user_id, "by": _name(ev.applied_by),
|
||||
"approved_by_id": ev.approved_by_user_id, "approved_by": _name(ev.approved_by),
|
||||
"at": ev.applied_at,
|
||||
}
|
||||
|
||||
|
||||
def can_view(user) -> bool:
|
||||
from core.access.check import holds
|
||||
return holds(user, "ordering.prices.view_changes")
|
||||
@@ -38,6 +38,7 @@ class OrderContext:
|
||||
cart_items: list # list of {product_id, category_id (primary), category_ids, quantity, unit_price}
|
||||
active_price_group_ids: set # set of PriceGroup.id that are currently active
|
||||
user_tier: Optional[str] = None # 'bronze'|'silver'|'gold' — placeholder
|
||||
active_scene_ids: set = field(default_factory=set) # the scenes on now (services/scenes.py, 2026-11-21)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -144,6 +145,11 @@ def _eval_condition(ctype: str, params: dict, ctx: OrderContext,
|
||||
passed = pgid in ctx.active_price_group_ids
|
||||
return passed, {"price_group_active": passed}
|
||||
|
||||
if ctype == "scene_active":
|
||||
# a scene is on (owner 2026-11-21): party mode, match night…
|
||||
passed = params.get("scene_id") in ctx.active_scene_ids
|
||||
return passed, {"scene_active": passed}
|
||||
|
||||
if ctype == "user_tier":
|
||||
passed = ctx.user_tier in params.get("tiers", [])
|
||||
return passed, {"user_tier": ctx.user_tier}
|
||||
@@ -236,6 +242,12 @@ def _price_group_is_active(pg, now: datetime) -> bool:
|
||||
return bool(pg.is_active)
|
||||
|
||||
|
||||
def build_active_scene_ids(db: Session, now: datetime) -> set:
|
||||
"""The scenes on at `now` (services/scenes.py), for the condition "a scene is on"."""
|
||||
from services.scenes import active_ids
|
||||
return active_ids(db, now)
|
||||
|
||||
|
||||
def build_active_price_group_ids(db: Session, now: datetime) -> set:
|
||||
"""Fetch all price groups once per request and return active IDs."""
|
||||
from models.pricing import PriceGroup
|
||||
@@ -305,9 +317,17 @@ def resolve_price(
|
||||
order_id must be set on the PriceEvents before writing them; the caller does this.
|
||||
"""
|
||||
from models.pricing import PriceModifier
|
||||
from services import channel_prices
|
||||
|
||||
base = product.base_price + options_extra
|
||||
events: list[PriceEvent] = []
|
||||
# the price at this sales point (order channel prices, 2026-11-20): the base for the rest
|
||||
own, rule = channel_prices.price_at(db, product, ctx.channel) if ctx.channel else (product.base_price, None)
|
||||
base = own + options_extra
|
||||
if rule is not None:
|
||||
events.append(PriceEvent(order_id=0, order_item_id=None, event_type="channel_price",
|
||||
price_before=product.base_price + options_extra, price_after=base,
|
||||
delta_amount=round(base - product.base_price - options_extra, 4),
|
||||
conditions_snapshot={"channel_price_id": rule.id, "sales_point": ctx.channel}))
|
||||
|
||||
# --- Load modifiers ---
|
||||
# Item-scoped modifiers for this product
|
||||
|
||||
@@ -29,6 +29,12 @@ def is_fee(item) -> bool:
|
||||
return getattr(item, "system_key", None) is not None
|
||||
|
||||
|
||||
def _fee_products(db) -> set[int]:
|
||||
"""The system products (the delivery fee…): one query, instead of loading each line's product."""
|
||||
from models.product import Product
|
||||
return {pid for (pid,) in db.query(Product.id).filter(Product.system_key.isnot(None)).all()}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Line:
|
||||
item: object
|
||||
@@ -54,11 +60,12 @@ def lines(db, items) -> list[Line]:
|
||||
from services.refunds import refunded_quantities
|
||||
sold = [i for i in items if i.status in SOLD]
|
||||
back = refunded_quantities(db, [i.id for i in sold if i.status == "paid"])
|
||||
fees = _fee_products(db) if sold else set()
|
||||
out = []
|
||||
for i in sold:
|
||||
r = min(back.get(i.id, 0.0), i.quantity)
|
||||
q = max(i.quantity - r, 0.0)
|
||||
out.append(Line(item=i, quantity=round(q, 3), value=gross(i, q), refunded=gross(i, r), fee=is_fee(i)))
|
||||
out.append(Line(item=i, quantity=round(q, 3), value=gross(i, q), refunded=gross(i, r), fee=i.product_id in fees))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Scenes (owner 2026-11-21, models/scene.py): which are on now, and telling what follows them.
|
||||
|
||||
A scene is on when it was turned on and its `until` (if any) has not passed. When scenes change,
|
||||
the signage screens are told (their schedules may pick another playlist) and the prices are
|
||||
recomputed by whoever asks next (price rules read `active_ids` through the pricing context).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from core.timeutil import utcnow
|
||||
|
||||
|
||||
def _aware(dt):
|
||||
from datetime import timezone
|
||||
return dt if dt is None or dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def is_on(scene, now: datetime | None = None) -> bool:
|
||||
now = now or utcnow()
|
||||
return bool(scene.is_active) and (scene.until is None or _aware(scene.until) > _aware(now))
|
||||
|
||||
|
||||
def active_ids(db, now: datetime | None = None) -> set[int]:
|
||||
from models.scene import Scene
|
||||
return {s.id for s in db.query(Scene).filter(Scene.is_active.is_(True)) if is_on(s, now)}
|
||||
|
||||
|
||||
def out(scene, now: datetime | None = None) -> dict:
|
||||
return {"id": scene.id, "name": scene.name, "color": scene.color, "description": scene.description,
|
||||
"active": is_on(scene, now), "activated_at": scene.activated_at, "until": scene.until, "sort_order": scene.sort_order}
|
||||
|
||||
|
||||
def changed(db) -> None:
|
||||
"""Scenes changed: the signage screens look again; the dashboards refresh their scene lists."""
|
||||
from services.ws_bus import broadcast_sync
|
||||
broadcast_sync("scenes.changed", {})
|
||||
try:
|
||||
from routers.signage import tell_all_screens
|
||||
tell_all_screens(db)
|
||||
except Exception: # signage off or not loaded: nothing to tell
|
||||
pass
|
||||
@@ -0,0 +1,104 @@
|
||||
"""The badges a menu board can put on a product (owner review 5, 2026-11-21): the venue's own list,
|
||||
kept in the setting `signage.badges` (JSON), edited under Signage → Message & settings. Each badge
|
||||
has a key (what boards store), its name in Greek and English, its colours (background, text: None =
|
||||
white or black, whichever reads) and an icon (a name from ICONS, drawn by @xenia/signage). Its
|
||||
colours are the defaults: a board may give all its badges one colour of its own.
|
||||
|
||||
Until the venue changes it, the list is DEFAULTS (the seven badges boards had before)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
SETTING = "signage.badges"
|
||||
HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$"
|
||||
KEY = r"^[a-z0-9][a-z0-9_-]{0,23}$"
|
||||
|
||||
# the icons a badge can have (lucide names; @xenia/signage BADGE_ICONS draws the same list)
|
||||
ICONS = (
|
||||
"sparkles", "chef-hat", "tag", "star", "flame", "sprout", "leaf", "vegan", "wheat", "wheat-off", "fish", "shrimp", "beef",
|
||||
"drumstick", "egg", "milk", "nut", "carrot", "salad", "pizza", "hamburger", "sandwich", "soup", "croissant",
|
||||
"ice-cream-cone", "cake-slice", "coffee", "cup-soda", "wine", "beer", "martini", "glass-water", "citrus", "cherry",
|
||||
"apple", "heart", "award", "thumbs-up", "clock", "percent", "gift", "crown", "zap", "snowflake",
|
||||
)
|
||||
|
||||
DEFAULTS = [
|
||||
{"key": "new", "names": {"el": "Νέο", "en": "New"}, "colour": "#22c55e", "text_colour": None, "icon": "sparkles"},
|
||||
{"key": "chef", "names": {"el": "Πρόταση σεφ", "en": "Chef's pick"}, "colour": "#f59e0b", "text_colour": None, "icon": "chef-hat"},
|
||||
{"key": "offer", "names": {"el": "Προσφορά", "en": "Offer"}, "colour": "#ef4444", "text_colour": None, "icon": "tag"},
|
||||
{"key": "popular", "names": {"el": "Δημοφιλές", "en": "Popular"}, "colour": "#f472b6", "text_colour": None, "icon": "star"},
|
||||
{"key": "spicy", "names": {"el": "Καυτερό", "en": "Spicy"}, "colour": "#dc2626", "text_colour": None, "icon": "flame"},
|
||||
{"key": "vegetarian", "names": {"el": "Χορτοφαγικό", "en": "Vegetarian"}, "colour": "#16a34a", "text_colour": None, "icon": "sprout"},
|
||||
{"key": "vegan", "names": {"el": "Vegan", "en": "Vegan"}, "colour": "#15803d", "text_colour": None, "icon": "vegan"},
|
||||
]
|
||||
|
||||
|
||||
class BadgeDef(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
key: str = Field(pattern=KEY)
|
||||
names: Dict[str, str] = Field(default_factory=dict)
|
||||
colour: str = Field(default="#f59e0b", pattern=HEX)
|
||||
text_colour: Optional[str] = Field(default=None, pattern=HEX)
|
||||
icon: Optional[str] = None
|
||||
|
||||
@field_validator("names")
|
||||
@classmethod
|
||||
def _names(cls, v):
|
||||
out = {k: " ".join(str(x).split())[:24] for k, x in v.items() if k in ("el", "en")}
|
||||
out = {k: x for k, x in out.items() if x}
|
||||
if not out:
|
||||
raise ValueError("a badge has a name")
|
||||
return out
|
||||
|
||||
@field_validator("icon")
|
||||
@classmethod
|
||||
def _icon(cls, v):
|
||||
if v is not None and v not in ICONS:
|
||||
raise ValueError("an icon of the list")
|
||||
return v
|
||||
|
||||
|
||||
class BadgeList(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
badges: List[BadgeDef] = Field(default_factory=list, max_length=30)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _unique(self):
|
||||
keys = [b.key for b in self.badges]
|
||||
if len(set(keys)) != len(keys):
|
||||
raise ValueError("each badge has its own key")
|
||||
return self
|
||||
|
||||
|
||||
def load(db) -> list[dict]:
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == SETTING).first()
|
||||
if row is None or not row.value:
|
||||
return [dict(b) for b in DEFAULTS]
|
||||
try:
|
||||
return BadgeList(badges=json.loads(row.value)).model_dump()["badges"]
|
||||
except Exception: # noqa: BLE001 — a broken setting falls back to the defaults
|
||||
return [dict(b) for b in DEFAULTS]
|
||||
|
||||
|
||||
def save(db, badges: list[BadgeDef]) -> list[dict]:
|
||||
from models.settings import PosSettings
|
||||
value = json.dumps([b.model_dump() for b in badges], ensure_ascii=False)
|
||||
row = db.query(PosSettings).filter(PosSettings.key == SETTING).first()
|
||||
if row is None:
|
||||
db.add(PosSettings(key=SETTING, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
return [b.model_dump() for b in badges]
|
||||
|
||||
|
||||
def new_key(name: str, taken: set) -> str:
|
||||
"""A key for a new badge from its name (the editor makes its own; kept for scripts)."""
|
||||
base = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:20] or "badge"
|
||||
key, n = base, 2
|
||||
while key in taken:
|
||||
key, n = f"{base}-{n}", n + 1
|
||||
return key
|
||||
@@ -34,8 +34,11 @@ def _rank(order: list[int]):
|
||||
return lambda v: (0, pos[v]) if v in pos else (1, 0)
|
||||
|
||||
|
||||
def resolve(db, content: dict, now=None) -> dict:
|
||||
"""{"groups": [{"category": {id, name} | None, "items": [...]}], "count": n} for a menu slide."""
|
||||
def resolve(db, content: dict, now=None, keep_hidden: bool = False) -> dict:
|
||||
"""{"groups": [{"category": {id, name} | None, "items": [...]}], "count": n} for a menu slide.
|
||||
keep_hidden (the editor's list, 2026-11-21): products hidden from the board (`exclude_ids`) stay
|
||||
in the list marked `"hidden": true` (greyed there, shown again with a click); `count` and the
|
||||
TV leave them out."""
|
||||
from models.product import Category, Product, ProductCategory
|
||||
from services import media as media_store
|
||||
from services.pos_cart import unit_prices
|
||||
@@ -55,7 +58,8 @@ def resolve(db, content: dict, now=None) -> dict:
|
||||
ids = in_cats | set(content.get("product_ids") or [])
|
||||
products = q.filter(Product.id.in_(ids)).all() if ids else []
|
||||
excluded = set(content.get("exclude_ids") or [])
|
||||
products = [p for p in products if p.id not in excluded]
|
||||
if not keep_hidden:
|
||||
products = [p for p in products if p.id not in excluded]
|
||||
|
||||
point = content.get("sales_point")
|
||||
if point:
|
||||
@@ -76,29 +80,41 @@ def resolve(db, content: dict, now=None) -> dict:
|
||||
return (prod_rank(p.id), member_order.get((p.primary_category_id, p.id), p.sort_order or 0), (p.name or "").lower())
|
||||
|
||||
prices = dict(zip([p.id for p in products], unit_prices(db, products, point, now=now))) if point and products else {}
|
||||
badges = {int(k): v for k, v in (content.get("badges") or {}).items() if str(k).isdigit()}
|
||||
badges = {int(k): ([v] if isinstance(v, str) else list(v or [])) for k, v in (content.get("badges") or {}).items() if str(k).isdigit()}
|
||||
|
||||
lang = content.get("language") # 6.4: the board's language; None = the base texts
|
||||
|
||||
def text(row, base, field):
|
||||
return menu_languages.texts(base, menu_languages.of(row), field).get(lang, base) if lang else base
|
||||
|
||||
own = content.get("names") or {} # this board's own names (2026-11-21)
|
||||
own_cats = content.get("category_names") or {}
|
||||
|
||||
def named(row, base, mine):
|
||||
"""(the name shown, the catalogue's name when the board has its own)"""
|
||||
shown = text(row, base, "name")
|
||||
return (mine, shown) if mine else (shown, None)
|
||||
|
||||
def item(p):
|
||||
image = media_store.image_of(p.media) if content.get("show_photos") else None
|
||||
return {"id": p.id, "name": text(p, p.digital_name or p.name, "name"),
|
||||
name, original = named(p, p.digital_name or p.name, own.get(str(p.id)))
|
||||
return {"id": p.id, "name": name, **({"original": original} if original and keep_hidden else {}),
|
||||
"description": text(p, p.digital_description or p.description or None, "description") if content.get("show_descriptions") else None,
|
||||
"price": round(prices[p.id], 2) if p.id in prices else None,
|
||||
"available": bool(p.is_available), "image": image["card"] if image else None,
|
||||
"badge": badges.get(p.id)}
|
||||
"badges": badges.get(p.id) or [], **({"hidden": True} if p.id in excluded else {})}
|
||||
|
||||
if content.get("group_by_category", True):
|
||||
groups: dict = {}
|
||||
for p in products:
|
||||
groups.setdefault(p.primary_category_id, []).append(p)
|
||||
out = [{"category": {"id": cid, "name": text(by_id[cid], by_id[cid].name, "name")} if cid in by_id else None,
|
||||
def cat(cid):
|
||||
name, original = named(by_id[cid], by_id[cid].name, own_cats.get(str(cid)))
|
||||
return {"id": cid, "name": name, **({"original": original} if original and keep_hidden else {})}
|
||||
out = [{"category": cat(cid) if cid in by_id else None,
|
||||
"items": [item(p) for p in sorted(ps, key=prod_key)]}
|
||||
for cid, ps in sorted(groups.items(), key=lambda kv: cat_key(kv[0]))]
|
||||
else:
|
||||
ordered = sorted(products, key=lambda p: (prod_rank(p.id), cat_key(p.primary_category_id), prod_key(p)))
|
||||
out = [{"category": None, "items": [item(p) for p in ordered]}] if ordered else []
|
||||
return {"groups": out, "count": len(products)}
|
||||
return {"groups": out, "count": len([p for p in products if p.id not in excluded])}
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
"""Signage schedules (plan step 5.4d): which playlist a screen plays when.
|
||||
"""Signage schedules (plan step 5.4d; lines with their screens and scenes, owner 2026-11-21): which
|
||||
playlist a screen plays when.
|
||||
|
||||
A schedule is a list of entries {playlist_id, days, time_from, time_to, date_from, date_to,
|
||||
priority} and a fallback playlist. At a moment (venue time) the entries that match are:
|
||||
A screen's lines are the schedule lines (models/signage.py SignageScheduleItem) that are on and
|
||||
name it (or no screen = every screen). At a moment (venue time) a line matches when:
|
||||
- its days include today (empty = every day),
|
||||
- its smart days hold (core/calendar_days.py: 1st / last day, first / last week, public
|
||||
holidays or not; empty = every day),
|
||||
- the time is inside [time_from, time_to) (empty = all day; a window that passes midnight,
|
||||
e.g. 22:00-02:00, counts the after-midnight part for the day it started),
|
||||
- today is inside [date_from, date_to] (empty = no limit).
|
||||
- today is inside [date_from, date_to] (empty = no limit),
|
||||
- its scene (if any) is on.
|
||||
The winner is the highest priority, then the most specific (dates > days > hours), then the
|
||||
later entry in the list. No match → the fallback (None = a blank screen).
|
||||
later line. No match → the screen's default playlist (None = a blank screen).
|
||||
|
||||
`pick()` is pure (unit-tested; the player in 5.5a does the same in JavaScript so a screen
|
||||
switches by itself while the server is down). `schedule_worker` tells a screen when its pick
|
||||
@@ -30,12 +34,15 @@ def _minutes(hhmm: str | None) -> int | None:
|
||||
|
||||
|
||||
def _date_ok(e: dict, day) -> bool:
|
||||
from core.calendar_days import month_days_ok
|
||||
d = day.isoformat()
|
||||
return (not e.get("date_from") or d >= e["date_from"]) and (not e.get("date_to") or d <= e["date_to"])
|
||||
return (not e.get("date_from") or d >= e["date_from"]) and (not e.get("date_to") or d <= e["date_to"]) and month_days_ok(e.get("month_days"), day)
|
||||
|
||||
|
||||
def matches(e: dict, local: datetime) -> bool:
|
||||
"""Does entry `e` cover this venue-local moment?"""
|
||||
def matches(e: dict, local: datetime, scenes=None) -> bool:
|
||||
"""Does entry `e` cover this venue-local moment (with these scenes on)?"""
|
||||
if e.get("scene_id") is not None and e["scene_id"] not in (scenes or ()):
|
||||
return False
|
||||
days = e.get("days") or []
|
||||
start, end = _minutes(e.get("time_from")), _minutes(e.get("time_to"))
|
||||
now = local.hour * 60 + local.minute
|
||||
@@ -55,15 +62,15 @@ def matches(e: dict, local: datetime) -> bool:
|
||||
|
||||
|
||||
def _specific(e: dict) -> int:
|
||||
return (4 if (e.get("date_from") or e.get("date_to")) else 0) + (2 if e.get("days") else 0) + \
|
||||
return (4 if (e.get("date_from") or e.get("date_to")) else 0) + (2 if (e.get("days") or e.get("month_days")) else 0) + \
|
||||
(1 if (e.get("time_from") or e.get("time_to")) else 0)
|
||||
|
||||
|
||||
def pick(entries: list[dict], fallback: int | None, local: datetime) -> int | None:
|
||||
def pick(entries: list[dict], fallback: int | None, local: datetime, scenes=None) -> int | None:
|
||||
"""The playlist id that plays at `local` (venue time)."""
|
||||
best, best_key = None, None
|
||||
for i, e in enumerate(entries or []):
|
||||
if e.get("playlist_id") is None or not matches(e, local):
|
||||
if e.get("playlist_id") is None or not matches(e, local, scenes):
|
||||
continue
|
||||
key = (e.get("priority") or 0, _specific(e), i)
|
||||
if best_key is None or key > best_key:
|
||||
@@ -76,20 +83,43 @@ def pick(entries: list[dict], fallback: int | None, local: datetime) -> int | No
|
||||
_playing: dict[int, int | None] = {} # screen id → the playlist it was told about
|
||||
|
||||
|
||||
def due_changes(db, local: datetime | None = None) -> list[int]:
|
||||
"""The screens on a schedule whose pick is different from the last one seen (and remember it)."""
|
||||
ENTRY_KEYS = ("playlist_id", "days", "month_days", "time_from", "time_to", "date_from", "date_to", "priority", "scene_id")
|
||||
|
||||
|
||||
def entry_of(item) -> dict:
|
||||
"""A schedule line as the screens and pick() read it."""
|
||||
return {k: getattr(item, k) for k in ENTRY_KEYS}
|
||||
|
||||
|
||||
def lines_for(db, screen_id: int) -> list:
|
||||
"""The schedule lines that are on and name this screen (or no screen), in order."""
|
||||
from models.signage import SignageScheduleItem
|
||||
return [i for i in db.query(SignageScheduleItem).filter(SignageScheduleItem.enabled.is_(True))
|
||||
.order_by(SignageScheduleItem.position, SignageScheduleItem.id) if not i.screen_ids or screen_id in i.screen_ids]
|
||||
|
||||
|
||||
def now_for(db, dev, local: datetime | None = None, scenes=None) -> tuple[int | str | None, bool]:
|
||||
"""(the playlist a screen plays now, whether a schedule line picked it)."""
|
||||
from core.timeutil import venue_now
|
||||
from models.signage import SignageSchedule
|
||||
from routers.signage import _screen_config, _screens
|
||||
from routers.signage import _screen_config, default_of
|
||||
from services.scenes import active_ids
|
||||
local = local or venue_now()
|
||||
scenes = active_ids(db) if scenes is None else scenes
|
||||
default = default_of(_screen_config(dev)) # a playlist id, or "slide:<id>" (a library slide)
|
||||
got = pick([entry_of(i) for i in lines_for(db, dev.id)], None, local, scenes)
|
||||
return (got, True) if got is not None else (default, False)
|
||||
|
||||
|
||||
def due_changes(db, local: datetime | None = None) -> list[int]:
|
||||
"""The screens whose pick is different from the last one seen (and remember it)."""
|
||||
from core.timeutil import venue_now
|
||||
from routers.signage import _screens
|
||||
from services.scenes import active_ids
|
||||
local = local or venue_now()
|
||||
scenes = active_ids(db)
|
||||
changed = []
|
||||
for d in _screens(db):
|
||||
sid = _screen_config(d).get("schedule")
|
||||
if not sid:
|
||||
_playing.pop(d.id, None)
|
||||
continue
|
||||
s = db.get(SignageSchedule, sid)
|
||||
now = pick(s.entries or [], s.fallback_playlist_id, local) if s else None
|
||||
now = now_for(db, d, local, scenes)[0]
|
||||
if d.id in _playing and _playing[d.id] != now:
|
||||
changed.append(d.id)
|
||||
_playing[d.id] = now
|
||||
|
||||
@@ -6,7 +6,10 @@ editor from a town search). `weather_worker` (a signage module worker) asks Open
|
||||
key) every 30 minutes while it has internet and keeps the last answer in memory. A forecast older
|
||||
than 3 hours counts as none: the screens get `weather: null` and hide the widget.
|
||||
|
||||
current() → {"place", "temperature", "code", "is_day", "days": [{date, max, min, code}], "units", "at"} | None
|
||||
current() → {"place", "temperature", "code", "is_day", "feels_like", "humidity", "wind", "wind_dir",
|
||||
"precipitation", "days": [{date, max, min, code, rain, wind, uv, sunrise, sunset}] (7),
|
||||
"hours": [{time, temp, code, rain, is_day}] (the next 24), "units", "wind_unit", "at"} | None
|
||||
(6R.18: everything the detailed weather widget can show; older answers lack some keys)
|
||||
search(name) → places for the editor's search (name, country, region, latitude, longitude)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -68,9 +71,12 @@ def _key(where: dict) -> tuple:
|
||||
|
||||
|
||||
async def fetch(where: dict, client: httpx.AsyncClient | None = None) -> dict:
|
||||
params = {"latitude": where["latitude"], "longitude": where["longitude"], "timezone": "auto", "forecast_days": 3,
|
||||
"current": "temperature_2m,weather_code,is_day", "daily": "temperature_2m_max,temperature_2m_min,weather_code",
|
||||
"temperature_unit": where["units"]}
|
||||
imperial = where["units"] == "fahrenheit"
|
||||
params = {"latitude": where["latitude"], "longitude": where["longitude"], "timezone": "auto", "forecast_days": 7,
|
||||
"current": "temperature_2m,weather_code,is_day,apparent_temperature,relative_humidity_2m,wind_speed_10m,wind_direction_10m,precipitation",
|
||||
"daily": "temperature_2m_max,temperature_2m_min,weather_code,precipitation_probability_max,wind_speed_10m_max,uv_index_max,sunrise,sunset",
|
||||
"hourly": "temperature_2m,weather_code,precipitation_probability,is_day",
|
||||
"temperature_unit": where["units"], "wind_speed_unit": "mph" if imperial else "kmh"}
|
||||
own = client is None
|
||||
client = client or httpx.AsyncClient(timeout=TIMEOUT_S)
|
||||
try:
|
||||
@@ -80,12 +86,26 @@ async def fetch(where: dict, client: httpx.AsyncClient | None = None) -> dict:
|
||||
finally:
|
||||
if own:
|
||||
await client.aclose()
|
||||
cur, daily = j.get("current") or {}, j.get("daily") or {}
|
||||
days = [{"date": d, "max": mx, "min": mn, "code": c}
|
||||
for d, mx, mn, c in zip(daily.get("time", []), daily.get("temperature_2m_max", []),
|
||||
daily.get("temperature_2m_min", []), daily.get("weather_code", []))]
|
||||
cur, daily, hourly = j.get("current") or {}, j.get("daily") or {}, j.get("hourly") or {}
|
||||
col = lambda src, key, n: (src.get(key) or [None] * n)[:n] + [None] * max(0, n - len(src.get(key) or [])) # noqa: E731
|
||||
n = len(daily.get("time", []))
|
||||
hm = lambda v: v[11:16] if isinstance(v, str) and len(v) >= 16 else None # noqa: E731 "2026-11-17T07:12" → "07:12"
|
||||
days = [{"date": d, "max": mx, "min": mn, "code": c, "rain": rp, "wind": wm, "uv": uv, "sunrise": hm(sr), "sunset": hm(ss)}
|
||||
for d, mx, mn, c, rp, wm, uv, sr, ss in zip(daily.get("time", []), col(daily, "temperature_2m_max", n), col(daily, "temperature_2m_min", n),
|
||||
col(daily, "weather_code", n), col(daily, "precipitation_probability_max", n),
|
||||
col(daily, "wind_speed_10m_max", n), col(daily, "uv_index_max", n),
|
||||
col(daily, "sunrise", n), col(daily, "sunset", n))]
|
||||
# the next 24 hours from now (the place's own time: Open-Meteo answers in it)
|
||||
times = hourly.get("time", [])
|
||||
start = next((i for i, x in enumerate(times) if x >= (cur.get("time") or "")[:13] + ":00"), 0)
|
||||
m = len(times)
|
||||
hours = [{"time": hm(t), "temp": tp, "code": c, "rain": rp, "is_day": bool(dy if dy is not None else 1)}
|
||||
for t, tp, c, rp, dy in list(zip(times, col(hourly, "temperature_2m", m), col(hourly, "weather_code", m),
|
||||
col(hourly, "precipitation_probability", m), col(hourly, "is_day", m)))[start:start + 24]]
|
||||
return {"place": where["name"], "temperature": cur.get("temperature_2m"), "code": cur.get("weather_code"),
|
||||
"is_day": bool(cur.get("is_day", 1)), "days": days, "units": where["units"], "at": cur.get("time")}
|
||||
"is_day": bool(cur.get("is_day", 1)), "feels_like": cur.get("apparent_temperature"), "humidity": cur.get("relative_humidity_2m"),
|
||||
"wind": cur.get("wind_speed_10m"), "wind_dir": cur.get("wind_direction_10m"), "precipitation": cur.get("precipitation"),
|
||||
"days": days, "hours": hours, "units": where["units"], "wind_unit": "mph" if imperial else "km/h", "at": cur.get("time")}
|
||||
|
||||
|
||||
async def refresh(db, client: httpx.AsyncClient | None = None) -> bool:
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Order channel prices (UI review 2026-11-20): a product's price at a sales point, per product,
|
||||
per category or for the whole channel; the most precise rule wins (product > category > channel),
|
||||
and the channel price is the base the price modifiers work on, everywhere prices are made."""
|
||||
from services.pos_cart import unit_prices
|
||||
from tests.test_live import owner_h # noqa: F401 (fixtures)
|
||||
from tests.test_pos import menu # noqa: F401 (fixtures)
|
||||
|
||||
|
||||
def _rule(client, h, **body):
|
||||
r = client.post("/api/pricing/channel-prices", headers=h, json=body)
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def test_the_most_precise_rule_wins(client, db, owner_h, menu):
|
||||
burger, coffee = menu["burger"], menu["coffee"]
|
||||
on = lambda p, sp: round(unit_prices(db, [p], sp)[0], 2) # noqa: E731
|
||||
assert on(burger, "online_delivery") == 10.0
|
||||
# the whole delivery channel: +10 %
|
||||
_rule(client, owner_h, sales_points=["online_delivery"], action_type="add_percent", value=10)
|
||||
assert on(burger, "online_delivery") == 11.0 and on(coffee, "online_delivery") == 3.3 and on(burger, "in_store") == 10.0
|
||||
# the drinks' category: +0.50 on delivery and takeaway (beats the channel rule)
|
||||
_rule(client, owner_h, sales_points=["online_delivery", "online_takeaway"], category_ids=[coffee.primary_category_id],
|
||||
action_type="add_amount", value=0.5)
|
||||
assert on(coffee, "online_delivery") == 3.5 and on(coffee, "online_takeaway") == 3.5 and on(burger, "online_delivery") == 11.0
|
||||
# the coffee itself: set to 2.80 on delivery (beats the category)
|
||||
_rule(client, owner_h, sales_points=["online_delivery"], product_ids=[coffee.id], action_type="set", value=2.8)
|
||||
assert on(coffee, "online_delivery") == 2.8 and on(coffee, "online_takeaway") == 3.5
|
||||
|
||||
|
||||
def test_a_set_price_is_for_one_product(client, owner_h, menu):
|
||||
r = client.post("/api/pricing/channel-prices", headers=owner_h, json={
|
||||
"sales_points": ["qr_table"], "category_ids": [menu["coffee"].primary_category_id], "action_type": "set", "value": 2})
|
||||
assert r.status_code == 400 and r.json()["error"]["code"] == "channel_price.set_one_product"
|
||||
r = client.post("/api/pricing/channel-prices", headers=owner_h, json={"sales_points": [], "action_type": "add_amount", "value": 1})
|
||||
assert r.status_code == 400
|
||||
|
||||
|
||||
def test_the_product_editor_quick_edit(client, db, owner_h, menu):
|
||||
burger = menu["burger"]
|
||||
_rule(client, owner_h, sales_points=["online_takeaway"], action_type="add_amount", value=1)
|
||||
r = client.put(f"/api/pricing/channel-prices/product/{burger.id}", headers=owner_h, json={"points": {
|
||||
"in_store_takeaway": {"action_type": "add_percent", "value": -10, "round_to": "0.50"}}})
|
||||
assert r.status_code == 200, r.text
|
||||
rows = {x["sales_point"]: x for x in r.json()["points"]}
|
||||
assert rows["in_store_takeaway"]["price"] == 9.0 and rows["in_store_takeaway"]["own"]["action_type"] == "add_percent"
|
||||
assert rows["online_takeaway"]["price"] == 11.0 and rows["online_takeaway"]["rule"]["level"] == "channel" and rows["online_takeaway"]["own"] is None
|
||||
assert rows["in_store"]["price"] == 10.0 and rows["in_store"]["rule"] is None
|
||||
# removed: back to the default
|
||||
r = client.put(f"/api/pricing/channel-prices/product/{burger.id}", headers=owner_h, json={"points": {"in_store_takeaway": None}})
|
||||
assert {x["sales_point"]: x for x in r.json()["points"]}["in_store_takeaway"]["price"] == 10.0
|
||||
@@ -122,3 +122,47 @@ def test_tabs_need_their_own_key(client, db, make_user, login):
|
||||
no = login(make_user(role="staff_manager")) # has the dashboard, not tabs.manage
|
||||
assert client.get("/api/tabs/", headers=no).status_code == 403
|
||||
assert client.post("/api/orders/1/items/1/tab", headers=no).status_code == 403
|
||||
|
||||
|
||||
def test_expense_lines_make_the_total(client, make_user, login):
|
||||
"""2026-11-20: an expense can list what it bought (quantity, price before VAT, VAT %);
|
||||
the lines make its total, and editing them changes it (never below what was paid)."""
|
||||
h = login(make_user(role="owner"))
|
||||
r = client.post("/api/expenses/", headers=h, json={"description": "Market", "category": "supplier", "lines": [
|
||||
{"description": "Tomatoes", "quantity": 3, "unit_price": 2.5, "vat_rate": 13},
|
||||
{"description": "Bags", "quantity": 1, "unit_price": 10, "vat_rate": 24}]})
|
||||
assert r.status_code == 201, r.text
|
||||
e = r.json()
|
||||
assert [ln["total"] for ln in e["lines"]] == [8.48, 12.4]
|
||||
assert e["net_amount"] == 17.5 and e["vat_amount"] == 3.38 and e["total_amount"] == 20.88
|
||||
client.post(f"/api/expenses/{e['id']}/pay", headers=h, json={"amount": 15})
|
||||
# fewer lines than what was paid: refused
|
||||
r = client.put(f"/api/expenses/{e['id']}", headers=h, json={"lines": [{"description": "Bags", "quantity": 1, "unit_price": 10}]})
|
||||
assert r.status_code == 400 and r.json()["error"]["code"] == "expense.below_paid"
|
||||
# lines cleared: the total stays as it was and is typed again
|
||||
r = client.put(f"/api/expenses/{e['id']}", headers=h, json={"lines": [], "total_amount": 21})
|
||||
assert r.status_code == 200 and r.json()["lines"] == [] and r.json()["total_amount"] == 21
|
||||
# a line needs a description and a positive quantity
|
||||
bad = client.post("/api/expenses/", headers=h, json={"description": "X", "category": "other", "lines": [{"description": " ", "quantity": 1, "unit_price": 1}]})
|
||||
assert bad.json()["error"]["code"] == "validation.missing"
|
||||
# no lines and no total: refused
|
||||
assert client.post("/api/expenses/", headers=h, json={"description": "X", "category": "other"}).json()["error"]["code"] == "validation.positive"
|
||||
|
||||
|
||||
def test_expense_documents(client, make_user, login, tmp_path, monkeypatch):
|
||||
"""A PDF or a photo kept with an expense: uploaded, read back, removed; other files refused."""
|
||||
import services.expense_docs as docs
|
||||
monkeypatch.setattr(docs, "MEDIA_DIR", str(tmp_path))
|
||||
h = login(make_user(role="owner"))
|
||||
e = client.post("/api/expenses/", headers=h, json={"description": "Gas", "category": "utilities", "total_amount": 40}).json()
|
||||
pdf = b"%PDF-1.4\n%fake\n" + b"0" * 100
|
||||
r = client.post(f"/api/expenses/{e['id']}/documents", headers=h, files={"file": ("bill.pdf", pdf, "application/pdf")})
|
||||
assert r.status_code == 201, r.text
|
||||
doc = r.json()["documents"][0]
|
||||
assert doc["filename"] == "bill.pdf" and doc["content_type"] == "application/pdf" and doc["size"] == len(pdf)
|
||||
got = client.get(f"/api/expenses/{e['id']}/documents/{doc['id']}", headers=h)
|
||||
assert got.status_code == 200 and got.content == pdf
|
||||
assert client.post(f"/api/expenses/{e['id']}/documents", headers=h, files={"file": ("x.exe", b"MZ\x90\x00", "application/pdf")}).status_code == 422
|
||||
r = client.delete(f"/api/expenses/{e['id']}/documents/{doc['id']}", headers=h)
|
||||
assert r.status_code == 200 and r.json()["documents"] == []
|
||||
assert client.get(f"/api/expenses/{e['id']}/documents/{doc['id']}", headers=h).status_code == 404
|
||||
|
||||
@@ -90,3 +90,16 @@ def test_the_live_map_shows_each_table_state_to_the_right_people(client, owner_h
|
||||
assert len(client.get("/api/floor-plans/live", headers=owner_h).json()["tables"]) == 4
|
||||
# only the tables' managers set plans up
|
||||
assert client.post("/api/floor-plans", headers=h, json={"name": "x"}).status_code == 403
|
||||
|
||||
|
||||
def test_an_area_keeps_its_colour(client, owner_h, venue):
|
||||
"""2026-11-20: an area has a colour ("#rrggbb", drawn see-through); other things don't."""
|
||||
p = plan(client, owner_h, group_id=venue["inside"].id)
|
||||
r = client.put(f"/api/floor-plans/{p['id']}/layout", headers=owner_h, json={"items": [
|
||||
{"kind": "area", "x": 300, "y": 300, "width": 300, "height": 200, "text": "Terrace", "color": "#86efac"},
|
||||
{"kind": "wall", "x": 10, "y": 10, "width": 100, "height": 12, "color": "#86efac"}]})
|
||||
assert r.status_code == 200, r.text
|
||||
assert [(i["kind"], i["color"]) for i in r.json()["items"]] == [("area", "#86efac"), ("wall", None)]
|
||||
bad = client.put(f"/api/floor-plans/{p['id']}/layout", headers=owner_h, json={"items": [
|
||||
{"kind": "area", "x": 1, "y": 1, "width": 10, "height": 10, "color": "red; drop"}]})
|
||||
assert bad.status_code == 422
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""The venue's identity (6R.14): name, slogan, colours, logos, Wi-Fi and contact saved together,
|
||||
logos protected in the media library, signage screens told and given it with their venue."""
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers)
|
||||
from tests.test_signage import screens, sent # noqa: F401 (fixtures)
|
||||
|
||||
|
||||
def test_empty_at_first(client, owner_h):
|
||||
r = client.get("/api/identity", headers=owner_h)
|
||||
assert r.status_code == 200
|
||||
j = r.json()
|
||||
assert j["colours"] == [] and j["logos"] == {"main": None, "light": None, "dark": None, "icon": None}
|
||||
assert j["wifi"]["security"] == "WPA" and j["contact"]["phone"] is None
|
||||
|
||||
|
||||
def test_saved_together_and_shown_to_the_screens(client, owner_h, screens, sent, media_dir):
|
||||
logo = up(client, owner_h, jpeg(400, 200)).json()
|
||||
body = {"name": " Taverna Xenia ", "slogan": "Since 1987", "colours": [{"name": "Main", "colour": "#1E3A8A"}, {"name": "Olive", "colour": "#556b2f80"}],
|
||||
"logos": {"main": logo["id"]}, "wifi": {"ssid": "Xenia Guests", "password": "kalimera 2026", "security": "WPA"},
|
||||
"contact": {"phone": " 2310 123456 ", "instagram": "@xenia"}}
|
||||
sent.clear()
|
||||
r = client.put("/api/identity", headers=owner_h, json=body)
|
||||
assert r.status_code == 200, r.text
|
||||
j = r.json()
|
||||
assert j["name"] == "Taverna Xenia" and j["slogan"] == "Since 1987"
|
||||
assert j["colours"] == [{"name": "Main", "colour": "#1e3a8a"}, {"name": "Olive", "colour": "#556b2f80"}]
|
||||
assert j["logos"]["main"]["id"] == logo["id"] and j["logos"]["main"]["card"]
|
||||
assert j["wifi"]["password"] == "kalimera 2026" and j["contact"]["phone"] == "2310 123456"
|
||||
assert ("signage.changed", sorted([screens[1]["id"], screens[2]["id"]])) in sent
|
||||
# the venue name is the one every app already reads
|
||||
assert client.get("/api/settings/", headers=owner_h).json()["venue.name"]["value"] == "Taverna Xenia"
|
||||
# the screens get it with their venue
|
||||
venue = client.get("/api/signage/screen", headers=screens[1]["h"]).json()["venue"]
|
||||
assert venue["name"] == "Taverna Xenia" and venue["identity"]["wifi"]["ssid"] == "Xenia Guests"
|
||||
assert venue["identity"]["logos"]["main"]["id"] == logo["id"]
|
||||
# a logo in use can't be deleted
|
||||
assert err(client.delete(f"/api/media/{logo['id']}", headers=owner_h)) == "media.in_use"
|
||||
|
||||
|
||||
def test_checked(client, owner_h):
|
||||
assert client.put("/api/identity", headers=owner_h, json={"colours": [{"name": "", "colour": "#000000"}]}).status_code == 422
|
||||
assert client.put("/api/identity", headers=owner_h, json={"colours": [{"name": "x", "colour": "red"}]}).status_code == 422
|
||||
assert client.put("/api/identity", headers=owner_h, json={"wifi": {"security": "WPA9"}}).status_code == 422
|
||||
assert client.put("/api/identity", headers=owner_h, json={"nope": 1}).status_code == 422
|
||||
assert err(client.put("/api/identity", headers=owner_h, json={"logos": {"main": 99999}})) == "media.not_found"
|
||||
too_many = [{"name": f"c{i}", "colour": "#000000"} for i in range(13)]
|
||||
assert client.put("/api/identity", headers=owner_h, json={"colours": too_many}).status_code == 422
|
||||
|
||||
|
||||
def test_opening_hours(client, owner_h, screens, sent):
|
||||
assert client.get("/api/identity/hours", headers=owner_h).json() == {"days": [[]] * 7, "note": None, "set": False}
|
||||
days = [[{"from": "18:00", "to": "23:00"}, {"from": "12:00", "to": "15:00"}]] * 5 + [[{"from": "12:00", "to": "01:00"}], []]
|
||||
sent.clear()
|
||||
r = client.put("/api/identity/hours", headers=owner_h, json={"days": days, "note": " Closed on holidays "})
|
||||
assert r.status_code == 200, r.text
|
||||
j = r.json()
|
||||
assert j["set"] is True and j["days"][0] == [{"from": "12:00", "to": "15:00"}, {"from": "18:00", "to": "23:00"}]
|
||||
assert j["days"][6] == [] and j["note"] == "Closed on holidays"
|
||||
assert ("signage.changed", sorted([screens[1]["id"], screens[2]["id"]])) in sent
|
||||
assert client.get("/api/signage/screen", headers=screens[1]["h"]).json()["venue"]["hours"]["days"][5] == [{"from": "12:00", "to": "01:00"}]
|
||||
assert client.put("/api/identity/hours", headers=owner_h, json={"days": [[]] * 6}).status_code == 422
|
||||
assert client.put("/api/identity/hours", headers=owner_h, json={"days": [[{"from": "25:00", "to": "01:00"}]] + [[]] * 6}).status_code == 422
|
||||
|
||||
|
||||
def test_new_widgets_are_typed(client, owner_h):
|
||||
from tests.test_signage import playlist, slide
|
||||
p = playlist(client, owner_h)
|
||||
widgets = [
|
||||
{"kind": "shape", "position": "custom", "box": {"x": 10, "y": 10, "w": 20, "h": 20}, "shape": "star", "shape_sides": 5, "fill": "#ff0000", "fill_to": "#0000ff"},
|
||||
{"kind": "ticker", "position": "bottom-bar", "text": "Fresh fish today " * 10, "ticker_speed": 7},
|
||||
{"kind": "countdown", "countdown_to": "17:00", "countdown_start": "before", "countdown_before": 120, "countdown_done": "Happy hour!"},
|
||||
{"kind": "countdown", "countdown_to": "2026-12-31T23:59"},
|
||||
{"kind": "hours", "hours_style": "today"},
|
||||
{"kind": "wifi", "wifi_qr": False},
|
||||
{"kind": "contact", "contact_fields": ["phone", "instagram"]},
|
||||
]
|
||||
s = slide(client, owner_h, p["id"], "blank", content={"widgets": widgets})
|
||||
got = s["content"]["widgets"]
|
||||
assert [w["kind"] for w in got] == [w["kind"] for w in widgets]
|
||||
assert got[0]["shape"] == "star" and got[2]["countdown_before"] == 120 and got[6]["contact_fields"] == ["phone", "instagram"]
|
||||
bad = client.post(f"/api/signage/playlists/{p['id']}/slides", headers=owner_h,
|
||||
json={"kind": "blank", "content": {"widgets": [{"kind": "countdown", "countdown_to": "5pm"}]}})
|
||||
assert err(bad) == "signage.content_invalid"
|
||||
bad = client.post(f"/api/signage/playlists/{p['id']}/slides", headers=owner_h,
|
||||
json={"kind": "blank", "content": {"widgets": [{"kind": "contact", "contact_fields": ["fax"]}]}})
|
||||
assert err(bad) == "signage.content_invalid"
|
||||
|
||||
|
||||
def test_reviews_typed_in_by_hand(client, owner_h, screens, sent):
|
||||
body = {"reviews": [{"name": " Maria K. ", "stars": 5, "text": "Best octopus on the island", "date": "2026-11-01", "source": "Google"},
|
||||
{"name": "John", "stars": 3, "text": "OK"}]}
|
||||
sent.clear()
|
||||
r = client.put("/api/signage/reviews", headers=owner_h, json=body)
|
||||
assert r.status_code == 200, r.text
|
||||
got = r.json()["reviews"]
|
||||
assert got[0]["name"] == "Maria K." and got[0]["text"] == "Best octopus on the island" and got[1]["date"] is None
|
||||
assert ("signage.changed", sorted([screens[1]["id"], screens[2]["id"]])) in sent
|
||||
assert client.get("/api/signage/screen", headers=screens[1]["h"]).json()["venue"]["reviews"][0]["stars"] == 5
|
||||
assert client.get("/api/signage/reviews", headers=owner_h).json()["reviews"][1]["name"] == "John"
|
||||
assert client.put("/api/signage/reviews", headers=owner_h, json={"reviews": [{"name": "x", "stars": 6, "text": "y"}]}).status_code == 422
|
||||
assert client.put("/api/signage/reviews", headers=owner_h, json={"reviews": [{"name": "x", "stars": 5, "text": ""}]}).status_code == 422
|
||||
|
||||
|
||||
def test_more_settings_of_widgets(client, owner_h, media_dir):
|
||||
from tests.test_signage import playlist, slide
|
||||
logo = up(client, owner_h, jpeg(200, 200)).json()
|
||||
p = playlist(client, owner_h)
|
||||
w = {"kind": "date", "opacity": 60, "rotation": -15, "shadow": "glow", "border_width": 4, "border_colour": "#ff0000", "border_radius": 20,
|
||||
"animation": "pop", "animation_delay": 5, "weight": 300, "highlight": "#ffff0080", "text_effect": "typewriter",
|
||||
"date_format": "numeric", "date_separator": "."}
|
||||
q = {"kind": "qr", "media_id": logo["id"], "clock_format": "12", "clock_blink": True}
|
||||
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [w, q]})
|
||||
got = s["content"]["widgets"][0]
|
||||
assert {k: got[k] for k in w} == w
|
||||
assert s["content"]["widgets"][1]["media_id"] == logo["id"]
|
||||
for bad in ({"kind": "date", "opacity": 5}, {"kind": "date", "animation": "spin"}, {"kind": "date", "date_separator": "|"}, {"kind": "clock", "weight": 1000}):
|
||||
r = client.post(f"/api/signage/playlists/{p['id']}/slides", headers=owner_h, json={"kind": "blank", "content": {"widgets": [bad]}})
|
||||
assert err(r) == "signage.content_invalid", bad
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Media folders (6R.16): made, renamed, deleted (files stay), files moved and uploaded into one,
|
||||
the list filtered; a gallery widget showing a folder gets its files (and the screen their addresses)."""
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers)
|
||||
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
|
||||
|
||||
|
||||
def test_folders(client, owner_h, media_dir):
|
||||
f = client.post("/api/media/folders", headers=owner_h, json={"name": " Summer menu "}).json()
|
||||
assert f["name"] == "Summer menu" and f["count"] == 0
|
||||
a = up(client, owner_h, jpeg(300, 200)).json()
|
||||
b = up(client, owner_h, jpeg(300, 200, (9, 9, 9))).json()
|
||||
assert client.post("/api/media/move", headers=owner_h, json={"ids": [a["id"], b["id"]], "folder_id": f["id"]}).json()["moved"] == 2
|
||||
got = client.get("/api/media/folders", headers=owner_h).json()
|
||||
assert got["folders"] == [{"id": f["id"], "name": "Summer menu", "count": 2}]
|
||||
listed = client.get(f"/api/media?folder={f['id']}", headers=owner_h).json()
|
||||
assert {i["id"] for i in listed["items"]} == {a["id"], b["id"]} and listed["items"][0]["folder_id"] == f["id"]
|
||||
assert all(i["folder_id"] is None for i in client.get("/api/media?folder=none", headers=owner_h).json()["items"])
|
||||
r = client.patch(f"/api/media/{a['id']}", headers=owner_h, json={"folder_id": None})
|
||||
assert r.status_code == 200 and r.json()["folder_id"] is None and r.json()["name"] == a["name"]
|
||||
assert client.patch(f"/api/media/folders/{f['id']}", headers=owner_h, json={"name": "Winter"}).json()["name"] == "Winter"
|
||||
# an upload straight into a folder
|
||||
c = client.post("/api/media", headers=owner_h, files={"file": ("x.jpg", jpeg(100, 100, (1, 2, 3)), "image/jpeg")}, data={"folder_id": str(f["id"])}).json()
|
||||
assert c["folder_id"] == f["id"]
|
||||
assert err(client.post("/api/media/move", headers=owner_h, json={"ids": [a["id"]], "folder_id": 9999})) == "media.folder_unknown"
|
||||
assert client.delete(f"/api/media/folders/{f['id']}", headers=owner_h).status_code == 204
|
||||
assert client.get(f"/api/media/{b['id']}", headers=owner_h).json()["folder_id"] is None # the file stays
|
||||
|
||||
|
||||
def test_a_gallery_of_a_folder(client, owner_h, screens, media_dir):
|
||||
f = client.post("/api/media/folders", headers=owner_h, json={"name": "Dishes"}).json()
|
||||
pics = [up(client, owner_h, jpeg(400, 300, (i * 40, 10, 10))).json() for i in range(3)]
|
||||
client.post("/api/media/move", headers=owner_h, json={"ids": [p["id"] for p in pics], "folder_id": f["id"]})
|
||||
p = playlist(client, owner_h)
|
||||
slide(client, owner_h, p["id"], "blank", content={"widgets": [
|
||||
{"kind": "gallery", "position": "custom", "box": {"x": 0, "y": 0, "w": 50, "h": 50}, "gallery_source": "folder", "gallery_folder": f["id"], "gallery_seconds": 4},
|
||||
{"kind": "gallery", "position": "top-left", "media_ids": [pics[0]["id"]], "gallery_transition": "slide"}]})
|
||||
client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"playlist_id": p["id"]})
|
||||
pl = client.get("/api/signage/screen", headers=screens[1]["h"]).json()["playlist"]
|
||||
s = pl["slides"][0]
|
||||
assert s["extras"]["0"]["gallery"] == [x["id"] for x in pics]
|
||||
assert all(str(x["id"]) in pl["media"] for x in pics)
|
||||
# the pictures in a gallery's own list are protected
|
||||
assert err(client.delete(f"/api/media/{pics[0]['id']}", headers=owner_h)) == "media.in_use"
|
||||
@@ -82,3 +82,71 @@ def test_the_frontend_list_matches_the_backend():
|
||||
js = (Path(__file__).resolve().parents[2] / "packages" / "access" / "src" / "menuLanguages.js").read_text(encoding="utf-8")
|
||||
listed = re.search(r"export const MENU_LANGUAGES = \[([^\]]*)\]", js).group(1)
|
||||
assert [x.strip().strip("'") for x in listed.split(",") if x.strip()] == list(MENU_LANGUAGES)
|
||||
|
||||
|
||||
def test_every_choice_keeps_its_names_per_language(client, db, owner_h, menu):
|
||||
"""Owner 2026-11-21 (0042): every choice has its name per language; empty ones dropped,
|
||||
unknown languages refused; sub-choices and the shared sub-set keep theirs in their JSON."""
|
||||
pid = menu["souvlaki"].id
|
||||
body = {
|
||||
"modifier_groups": [{"modifier_type": "ingredient", "name": "Sauces", "translations": {"el": "Σάλτσες", "en": "Sauces"}}],
|
||||
"quick_options": [{"name": "Πίτα", "translations": {"el": "Πίτα", "en": " Pitta ", "fr": ""}}],
|
||||
"ingredients": [{"name": "Κρεμμύδι", "group_id": 0, "translations": {"el": "Κρεμμύδι"}}],
|
||||
"options": [{"name": "Σιρόπι", "translations": {"en": "Syrup"}, "sub_choices": [{"name": "Καραμέλα", "translations": {"en": "Caramel", "el": ""}}]}],
|
||||
"preference_sets": [{"name": "Ζάχαρη", "translations": {"en": "Sugar"},
|
||||
"choices": [{"name": "Σκέτος", "translations": {"en": "No sugar"}, "sub_choices": [{"name": "Στέβια", "translations": {"en": "Stevia"}}]}],
|
||||
"shared_subset": {"name": "Γάλα", "translations": {"en": "Milk"}, "choices": [{"name": "Φρέσκο", "translations": {"en": "Fresh"}}]}}],
|
||||
}
|
||||
r = client.put(f"/api/products/{pid}", headers=owner_h, json=body)
|
||||
assert r.status_code == 200, r.text
|
||||
p = r.json()
|
||||
assert p["modifier_groups"][0]["translations"] == {"el": "Σάλτσες", "en": "Sauces"}
|
||||
assert p["quick_options"][0]["translations"] == {"el": "Πίτα", "en": "Pitta"}
|
||||
assert p["ingredients"][0]["translations"] == {"el": "Κρεμμύδι"}
|
||||
assert p["options"][0]["translations"] == {"en": "Syrup"}
|
||||
assert p["options"][0]["sub_choices"][0]["translations"] == {"en": "Caramel"}
|
||||
ps = p["preference_sets"][0]
|
||||
assert ps["translations"] == {"en": "Sugar"} and ps["choices"][0]["translations"] == {"en": "No sugar"}
|
||||
assert ps["choices"][0]["sub_choices"][0]["translations"] == {"en": "Stevia"}
|
||||
assert ps["shared_subset"]["translations"] == {"en": "Milk"} and ps["shared_subset"]["choices"][0]["translations"] == {"en": "Fresh"}
|
||||
bad = client.put(f"/api/products/{pid}", headers=owner_h, json={"quick_options": [{"name": "x", "translations": {"de": "x"}}]})
|
||||
assert bad.status_code == 422 and err(bad) == "catalog.translation"
|
||||
# the cloud's quick option names come from the option itself now
|
||||
from services.cloud_sync import menu_snapshot
|
||||
db.expire_all()
|
||||
snap, _ = menu_snapshot(db)
|
||||
souv = next(x for c in snap["categories"] for x in c["products"] if x["id"] == pid)
|
||||
assert souv["quick_options"][0]["names"] == {"el": "Πίτα", "en": "Pitta"}
|
||||
|
||||
|
||||
def test_migration_0042_puts_the_texts_in_their_language(tmp_path):
|
||||
"""0042: texts typed before had no language: Greek letters → el, else the venue's language;
|
||||
the product's old quick translations move onto the quick options."""
|
||||
import json
|
||||
from alembic import command
|
||||
from sqlalchemy import create_engine, text
|
||||
from core.schema import alembic_config, upgrade_to_head
|
||||
eng = create_engine(f"sqlite:///{(tmp_path / 'm.db').as_posix()}")
|
||||
with eng.begin() as conn:
|
||||
command.upgrade(alembic_config(conn), "0041_floor_item_color")
|
||||
conn.execute(text("insert into pos_settings (key, value, updated_at) values ('venue.language', 'el', '2026-01-01')"))
|
||||
conn.execute(text("insert into categories (id, name, sort_order, general_sort_order, auto_expanded) values (1, 'Ψητά', 0, 0, 0)"))
|
||||
conn.execute(text("insert into products (id, name, description, base_price, is_available, lifecycle_status, sort_order, sold_at, digital_available, "
|
||||
"unit_type, quick_add_enabled, is_service_item, translations) values (1, 'Burger', 'Με πατάτες', 8, 1, 'active', 0, '[]', 1, 'piece', 1, 0, "
|
||||
"'{\"en\": {\"description\": \"With fries\", \"quick\": {\"Μπέικον\": \"Bacon\"}}}')"))
|
||||
conn.execute(text("insert into product_quick_options (id, product_id, name, price, allow_multiple, sort_order, is_favorite, favorite_sort_order, is_compact) "
|
||||
"values (1, 1, 'Μπέικον', 1, 0, 0, 0, 0, 0)"))
|
||||
conn.execute(text("insert into product_options (id, product_id, name, extra_cost, allow_multiple, multi_select, is_favorite, favorite_sort_order, is_compact, sub_choices) "
|
||||
"values (1, 1, 'Σάλτσα', 0, 0, 0, 0, 0, 0, '[{\"name\": \"BBQ\"}]')"))
|
||||
upgrade_to_head(eng)
|
||||
with eng.connect() as conn:
|
||||
p = json.loads(conn.execute(text("select translations from products where id = 1")).scalar())
|
||||
q = json.loads(conn.execute(text("select translations from product_quick_options where id = 1")).scalar())
|
||||
o = conn.execute(text("select translations, sub_choices from product_options where id = 1")).fetchone()
|
||||
c = json.loads(conn.execute(text("select translations from categories where id = 1")).scalar())
|
||||
eng.dispose()
|
||||
# "Burger" has no Greek letters: the venue's language (el); the description is Greek; the English one is kept
|
||||
assert p == {"el": {"name": "Burger", "description": "Με πατάτες"}, "en": {"description": "With fries"}}
|
||||
assert q == {"el": "Μπέικον", "en": "Bacon"}
|
||||
assert json.loads(o[0]) == {"el": "Σάλτσα"} and json.loads(o[1])[0]["translations"] == {"el": "BBQ"}
|
||||
assert c == {"el": {"name": "Ψητά"}}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Moves on the record (owner 2026-11-23, plan 6F.4, services/moves.py).
|
||||
|
||||
A table transfer, lines moved to another order and two orders merged each leave one move with its
|
||||
lines; a line's path survives being moved three times, being split (the part carries the moves made
|
||||
before the split, not after) and being combined; the order shows where it came from; Reports →
|
||||
Moves lists them.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from tests.test_waiter_keys import shop # noqa: F401 (fixture)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_printing(monkeypatch):
|
||||
import routers.orders as orders
|
||||
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: [])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def floor(db, shop):
|
||||
"""Four free tables and the shop's waiter's order put on the first."""
|
||||
from models.table import Table, TableGroup
|
||||
g = TableGroup(name="Hall")
|
||||
db.add(g)
|
||||
db.flush()
|
||||
ts = [Table(number=n, group_id=g.id, is_active=True) for n in (1, 2, 3, 4)]
|
||||
db.add_all(ts)
|
||||
db.flush()
|
||||
shop["order"].table_id = ts[0].id
|
||||
shop["order"].status = "open"
|
||||
for i in shop["items"]:
|
||||
i.status = "active"
|
||||
db.commit()
|
||||
return ts
|
||||
|
||||
|
||||
def new_order(db, shop, table, n=1):
|
||||
from models.order import Order, OrderItem
|
||||
o = Order(opened_by=shop["waiter"].id, table_id=table.id, status="open")
|
||||
db.add(o)
|
||||
db.flush()
|
||||
items = [OrderItem(order_id=o.id, product_id=shop["items"][0].product_id, added_by=shop["waiter"].id, quantity=1, unit_price=4.0)
|
||||
for _ in range(n)]
|
||||
db.add_all(items)
|
||||
db.commit()
|
||||
return o, items
|
||||
|
||||
|
||||
def test_a_transfer_is_one_move_with_its_lines(client, db, shop, floor):
|
||||
o = shop["order"]
|
||||
r = client.post(f"/api/orders/{o.id}/transfer", headers=shop["h"], json={"target_table_id": floor[1].id})
|
||||
assert r.status_code == 200, r.text
|
||||
got = client.get(f"/api/orders/{o.id}/moves", headers=shop["h"]).json()
|
||||
[m] = got["order"]
|
||||
assert m["kind"] == "table_transfer" and (m["from_table_id"], m["to_table_id"]) == (floor[0].id, floor[1].id)
|
||||
assert m["from_table"] == "T1" and m["to_table"] == "T2" and m["by_id"] == shop["waiter"].id
|
||||
assert {i["item_id"] for i in m["items"]} == {i.id for i in shop["items"]}
|
||||
assert set(got["items"]) == {str(i.id) for i in shop["items"]}
|
||||
|
||||
|
||||
def test_a_line_moved_three_times_shows_every_step(client, db, shop, floor):
|
||||
o1 = shop["order"]
|
||||
o2, _ = new_order(db, shop, floor[1])
|
||||
o3, _ = new_order(db, shop, floor[2])
|
||||
line = shop["items"][0]
|
||||
for src, dst in ((o1, o2), (o2, o3), (o3, o1)):
|
||||
r = client.post(f"/api/orders/{src.id}/move-items", headers=shop["h"], json={"item_ids": [line.id], "target_order_id": dst.id})
|
||||
assert r.status_code == 200, r.text
|
||||
path = client.get(f"/api/orders/{o1.id}/moves", headers=shop["h"]).json()["items"][str(line.id)]
|
||||
assert [(m["from_table"], m["to_table"]) for m in path] == [("T1", "T2"), ("T2", "T3"), ("T3", "T1")]
|
||||
assert all(m["kind"] == "items_moved" for m in path)
|
||||
|
||||
|
||||
def test_a_split_part_keeps_the_moves_before_the_split_only(client, db, shop, floor):
|
||||
o1 = shop["order"]
|
||||
o2, _ = new_order(db, shop, floor[1])
|
||||
o3, _ = new_order(db, shop, floor[2])
|
||||
line = shop["items"][0]
|
||||
line.quantity = 3
|
||||
line.price_adjustment = -0.5
|
||||
line.kds_status = "served"
|
||||
db.commit()
|
||||
client.post(f"/api/orders/{o1.id}/move-items", headers=shop["h"], json={"item_ids": [line.id], "target_order_id": o2.id})
|
||||
r = client.post(f"/api/orders/{o2.id}/items/{line.id}/split", headers=shop["h"], json={"quantity": 1})
|
||||
assert r.status_code == 200, r.text
|
||||
part = [x for x in r.json() if x["id"] != line.id][0]
|
||||
assert part["split_from_id"] == line.id
|
||||
# the part keeps what the line was (its price change, the kitchen state)
|
||||
from models.order import OrderItem
|
||||
db.expire_all()
|
||||
p = db.get(OrderItem, part["id"])
|
||||
assert p.price_adjustment == -0.5 and p.kds_status == "served"
|
||||
# the original moves on; the part stays
|
||||
client.post(f"/api/orders/{o2.id}/move-items", headers=shop["h"], json={"item_ids": [line.id], "target_order_id": o3.id})
|
||||
part_path = client.get(f"/api/orders/{o2.id}/moves", headers=shop["h"]).json()["items"][str(part["id"])]
|
||||
assert [(m["from_table"], m["to_table"]) for m in part_path] == [("T1", "T2")]
|
||||
line_path = client.get(f"/api/orders/{o3.id}/moves", headers=shop["h"]).json()["items"][str(line.id)]
|
||||
assert [(m["from_table"], m["to_table"]) for m in line_path] == [("T1", "T2"), ("T2", "T3")]
|
||||
|
||||
|
||||
def test_a_merge_brings_the_other_orders_path(client, db, shop, floor):
|
||||
o1 = shop["order"]
|
||||
o2, lines2 = new_order(db, shop, floor[1])
|
||||
client.post(f"/api/orders/{o2.id}/transfer", headers=shop["h"], json={"target_table_id": floor[3].id})
|
||||
r = client.post(f"/api/orders/{o2.id}/merge", headers=shop["h"], json={"target_order_id": o1.id})
|
||||
assert r.status_code == 200, r.text
|
||||
got = client.get(f"/api/orders/{o1.id}/moves", headers=shop["h"]).json()
|
||||
assert [m["kind"] for m in got["order"]] == ["table_transfer", "orders_merged"]
|
||||
merged = got["order"][1]
|
||||
assert (merged["from_order_id"], merged["to_order_id"], merged["from_table"], merged["to_table"]) == (o2.id, o1.id, "T4", "T1")
|
||||
assert [m["kind"] for m in got["items"][str(lines2[0].id)]] == ["table_transfer", "orders_merged"]
|
||||
|
||||
|
||||
def test_combining_lines_keeps_their_moves(client, db, shop, floor):
|
||||
o1 = shop["order"]
|
||||
o2, _ = new_order(db, shop, floor[1])
|
||||
a, b = shop["items"][0], shop["items"][1]
|
||||
client.post(f"/api/orders/{o1.id}/move-items", headers=shop["h"], json={"item_ids": [a.id, b.id], "target_order_id": o2.id})
|
||||
r = client.post(f"/api/orders/{o2.id}/items/combine", headers=shop["h"], json={"item_ids": [a.id, b.id]})
|
||||
assert r.status_code == 200, r.text
|
||||
from models.order import OrderMoveItem
|
||||
db.expire_all()
|
||||
[mi] = db.query(OrderMoveItem).all()
|
||||
assert mi.item_id == a.id and mi.quantity == 2
|
||||
|
||||
|
||||
def test_the_moves_report(client, db, shop, floor, make_user, login):
|
||||
o1 = shop["order"]
|
||||
o2, _ = new_order(db, shop, floor[1])
|
||||
client.post(f"/api/orders/{o1.id}/move-items", headers=shop["h"], json={"item_ids": [shop["items"][0].id], "target_order_id": o2.id})
|
||||
client.post(f"/api/orders/{o2.id}/transfer", headers=shop["h"], json={"target_table_id": floor[2].id})
|
||||
boss = login(make_user(role="owner"))
|
||||
rep = client.get("/api/reports/moves", headers=boss).json()
|
||||
assert rep["count"] == 2 and rep["by_kind"] == {"items_moved": 1, "table_transfer": 1}
|
||||
moved = next(m for m in rep["moves"] if m["kind"] == "items_moved")
|
||||
assert moved["value"] == 4.0 and moved["items"][0]["name"] and rep["by_person"][0]["count"] == 2
|
||||
assert client.get(f"/api/reports/moves?table_id={floor[2].id}", headers=boss).json()["count"] == 1
|
||||
assert client.get("/api/reports/moves?kind=table_transfer", headers=boss).json()["count"] == 1
|
||||
csv = client.get("/api/reports/moves/export", headers=boss)
|
||||
assert csv.status_code == 200 and "items_moved" in csv.text
|
||||
@@ -105,7 +105,8 @@ def test_message_in_the_readers_language(client, db, make_user, login):
|
||||
|
||||
def test_license_expiring_steps(client, db, people):
|
||||
owner = people["owner"]
|
||||
end = "2026-11-20T00:00:00+00:00"
|
||||
# a date still ahead (the fixed "2026-11-20" became the past on that very day and the test began failing)
|
||||
end = (datetime.now(timezone.utc) + timedelta(days=30)).replace(microsecond=0).isoformat()
|
||||
check_license_expiry(end, 20, True, db)
|
||||
assert keys(client, owner[1]) == []
|
||||
check_license_expiry(end, 12, True, db)
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""One more, and a sent line's quantity (owner 2026-11-23, plan 6F.5).
|
||||
|
||||
- POST /api/orders/{id}/items/{item}/again: a new line like the old one, priced now, printed as new;
|
||||
only with the product's one_more_enabled, from active / paid / tabbed lines in pieces.
|
||||
- POST /api/orders/{id}/items/{item}/quantity: the venue's switch (off | add_only | add_and_remove),
|
||||
the key ordering.items.change_quantity; up changes the line only (no ticket); down cuts a
|
||||
cancelled part ("quantity lowered") and prints a cancellation only when asked.
|
||||
"""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.test_live import err
|
||||
from tests.test_waiter_keys import shop # noqa: F401 (fixture)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def printed(monkeypatch):
|
||||
"""What went to the kitchen: new lines (route_and_print_sync) and cancellations."""
|
||||
import routers.orders as orders
|
||||
got = {"tickets": [], "cancellations": []}
|
||||
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: (got["tickets"].append(a), [])[1])
|
||||
monkeypatch.setattr(orders, "print_cancellation_ticket", lambda order_id, ids: got["cancellations"].append(list(ids)))
|
||||
return got
|
||||
|
||||
|
||||
def setting(db, key, value):
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
if row is None:
|
||||
db.add(PosSettings(key=key, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
db.commit()
|
||||
|
||||
|
||||
def lines(db, order_id):
|
||||
from models.order import OrderItem
|
||||
db.expire_all()
|
||||
return db.query(OrderItem).filter(OrderItem.order_id == order_id).order_by(OrderItem.id).all()
|
||||
|
||||
|
||||
def test_one_more_needs_the_products_switch(client, db, shop, printed):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/again"
|
||||
assert err(client.post(url, headers=shop["h"], json={})) == "order.one_more_off"
|
||||
item.product.one_more_enabled = True
|
||||
item.notes = "no ice"
|
||||
item.selected_options = json.dumps([{"id": None, "name": "Sweet", "price_delta": 0.0, "type": "quick"}])
|
||||
db.commit()
|
||||
before = len(lines(db, o.id))
|
||||
r = client.post(url, headers=shop["h"], json={"quantity": 2})
|
||||
assert r.status_code == 200, r.text
|
||||
new = lines(db, o.id)[-1]
|
||||
assert len(lines(db, o.id)) == before + 1 and new.id != item.id
|
||||
assert (new.product_id, new.quantity, new.notes, new.status) == (item.product_id, 2, "no ice", "active")
|
||||
assert json.loads(new.selected_options)[0]["name"] == "Sweet" and new.unit_price == 4.0
|
||||
assert len(printed["tickets"]) == 1 # sent to the kitchen like any new line
|
||||
# from a paid line too; never from a cancelled one
|
||||
paid = shop["items"][2]
|
||||
assert client.post(f"/api/orders/{o.id}/items/{paid.id}/again", headers=shop["h"], json={}).status_code == 200
|
||||
paid.status = "cancelled"
|
||||
db.commit()
|
||||
assert err(client.post(f"/api/orders/{o.id}/items/{paid.id}/again", headers=shop["h"], json={})) == "order.one_more_line"
|
||||
|
||||
|
||||
def test_one_more_needs_ordering_orders_open(client, db, shop, login, printed):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
item.product.one_more_enabled = True
|
||||
db.commit()
|
||||
h = login(shop["new_waiter"](remove=("ordering.orders.open",)), client="waiter")
|
||||
assert err(client.post(f"/api/orders/{o.id}/items/{item.id}/again", headers=h, json={})) == "access.denied"
|
||||
|
||||
|
||||
def test_quantity_follows_the_venue_and_the_key(client, db, shop, login, printed):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/quantity"
|
||||
assert err(client.post(url, headers=shop["h"], json={"quantity": 3})) == "order.quantity_change_off"
|
||||
setting(db, "orders.quantity_change", "add_only")
|
||||
# a waiter without the key: a manager may approve it
|
||||
assert err(client.post(url, headers=shop["h"], json={"quantity": 3})) == "access.override_possible"
|
||||
h = login(shop["new_waiter"](add=("ordering.items.change_quantity",)), client="waiter")
|
||||
r = client.post(url, headers=h, json={"quantity": 3})
|
||||
assert r.status_code == 200, r.text
|
||||
assert lines(db, o.id)[0].quantity == 3 and printed["tickets"] == [] and printed["cancellations"] == []
|
||||
assert err(client.post(url, headers=h, json={"quantity": 2})) == "order.quantity_remove_off"
|
||||
from models.order import OrderAuditLog
|
||||
log = db.query(OrderAuditLog).filter(OrderAuditLog.event_type == "QUANTITY_CHANGED").one()
|
||||
assert log.note.startswith("1 → 3")
|
||||
|
||||
|
||||
def test_lowering_cancels_the_difference_and_asks_about_the_ticket(client, db, shop, login, printed):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
item.quantity = 5
|
||||
db.commit()
|
||||
setting(db, "orders.quantity_change", "add_and_remove")
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/quantity"
|
||||
# the key, but not the cancel key: a manager's approval for the cancel part
|
||||
h = login(shop["new_waiter"](add=("ordering.items.change_quantity",), remove=("ordering.orders.cancel",)), client="waiter")
|
||||
assert err(client.post(url, headers=h, json={"quantity": 3})) == "access.override_possible"
|
||||
h = login(shop["new_waiter"](add=("ordering.items.change_quantity", "ordering.orders.cancel")), client="waiter")
|
||||
r = client.post(url, headers=h, json={"quantity": 3, "print_cancellation": False})
|
||||
assert r.status_code == 200, r.text
|
||||
part_id = r.json()["cancelled_item_id"]
|
||||
rows = {i.id: i for i in lines(db, o.id)}
|
||||
assert rows[item.id].quantity == 3 and rows[item.id].status == "active"
|
||||
part = rows[part_id]
|
||||
assert (part.quantity, part.status, part.cancel_reason, part.split_from_id) == (2, "cancelled", "quantity lowered", item.id)
|
||||
assert printed["cancellations"] == []
|
||||
r = client.post(url, headers=h, json={"quantity": 2, "print_cancellation": True})
|
||||
assert printed["cancellations"] == [[r.json()["cancelled_item_id"]]]
|
||||
|
||||
|
||||
def test_only_unpaid_lines_in_pieces(client, db, shop, printed, login):
|
||||
setting(db, "orders.quantity_change", "add_and_remove")
|
||||
o = shop["order"]
|
||||
paid = shop["items"][2]
|
||||
boss = login(shop["owner"])
|
||||
assert err(client.post(f"/api/orders/{o.id}/items/{paid.id}/quantity", headers=boss, json={"quantity": 2})) == "order.quantity_line"
|
||||
item = shop["items"][0]
|
||||
item.product.unit_type = "kg"
|
||||
db.commit()
|
||||
assert err(client.post(f"/api/orders/{o.id}/items/{item.id}/quantity", headers=boss, json={"quantity": 2})) == "order.quantity_line"
|
||||
@@ -94,7 +94,7 @@ def test_waiter_cancels_after_manager_pin(client, db, venue, login):
|
||||
|
||||
def test_token_is_bound_to_its_key(client, db, venue, make_user, login):
|
||||
v = venue
|
||||
token = approve(client, v["waiter_h"], "ordering.prices.modify", make_user(role="owner").username).json()["override_token"]
|
||||
token = approve(client, v["waiter_h"], "ordering.prices.modify_sent", make_user(role="owner").username).json()["override_token"]
|
||||
# used for another key: refused, and NOT burned
|
||||
r = cancel(client, v, v["items"][0], token)
|
||||
assert err(r) == "access.override_invalid"
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Prices changed by hand, on the record (owner 2026-11-23, plan 6F.3, services/price_changes.py).
|
||||
|
||||
- The venue's switch `orders.price_change`: off refuses every by-hand price, before_sending refuses
|
||||
a sent line's, anytime allows both.
|
||||
- A sent line needs ordering.prices.modify_sent (modify alone is the cart); a manager's PIN is
|
||||
recorded as the approver.
|
||||
- `orders.price_change_reason`: a typed price needs a reason; the counter's % discount doesn't.
|
||||
- Every change is one manual_price event (before → after, quantity, who, stage, reason) and a
|
||||
PRICE_CHANGED audit row; only holders of ordering.prices.view_changes see them.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from conftest import TEST_PIN
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
from tests.test_order_lines import items_of, open_order
|
||||
from tests.test_pos import burger_line, menu, on_shift, till # noqa: F401 (fixtures)
|
||||
from tests.test_pos_tables import floor, phone # noqa: F401 (fixtures)
|
||||
from tests.test_waiter_keys import shop # noqa: F401 (fixture)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_printing(monkeypatch):
|
||||
import routers.orders as orders
|
||||
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: [])
|
||||
|
||||
|
||||
def setting(db, key, value):
|
||||
from models.settings import PosSettings
|
||||
row = db.query(PosSettings).filter(PosSettings.key == key).first()
|
||||
if row is None:
|
||||
db.add(PosSettings(key=key, value=value))
|
||||
else:
|
||||
row.value = value
|
||||
db.commit()
|
||||
|
||||
|
||||
def manual_events(db, order_id=None):
|
||||
from models.pricing import PriceEventLog
|
||||
db.expire_all()
|
||||
q = db.query(PriceEventLog).filter(PriceEventLog.event_type == "manual_price")
|
||||
if order_id is not None:
|
||||
q = q.filter(PriceEventLog.order_id == order_id)
|
||||
return q.order_by(PriceEventLog.id).all()
|
||||
|
||||
|
||||
def test_a_sent_line_changed_by_hand_is_recorded(client, db, shop, login):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
item.kds_status = "served"
|
||||
db.commit()
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
|
||||
r = client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h,
|
||||
json={"price_adjustment": -1.5, "reason": " regular customer "})
|
||||
assert r.status_code == 200, r.text
|
||||
[ev] = manual_events(db, o.id)
|
||||
assert (ev.order_item_id, ev.price_before, ev.price_after, ev.delta_amount) == (item.id, 4.0, 2.5, -1.5)
|
||||
assert ev.stage == "served" and ev.quantity == 1 and ev.waiter_note == "regular customer" and ev.approved_by_user_id is None
|
||||
# a second change records from the changed price, the first stays
|
||||
r = client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": 0})
|
||||
assert r.status_code == 200
|
||||
evs = manual_events(db, o.id)
|
||||
assert [(e.price_before, e.price_after) for e in evs] == [(4.0, 2.5), (2.5, 4.0)]
|
||||
from models.order import OrderAuditLog
|
||||
assert db.query(OrderAuditLog).filter(OrderAuditLog.order_id == o.id, OrderAuditLog.event_type == "PRICE_CHANGED").count() == 2
|
||||
|
||||
|
||||
def test_the_venue_switch(client, db, shop, login):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/price-adjust"
|
||||
boss = login(shop["owner"])
|
||||
setting(db, "orders.price_change", "before_sending")
|
||||
assert err(client.patch(url, headers=boss, json={"price_adjustment": -1})) == "order.price_change_sent_off"
|
||||
setting(db, "orders.price_change", "off")
|
||||
assert err(client.patch(url, headers=boss, json={"price_adjustment": -1})) == "order.price_change_off"
|
||||
setting(db, "orders.price_change", "anytime")
|
||||
assert client.patch(url, headers=boss, json={"price_adjustment": -1}).status_code == 200
|
||||
assert len(manual_events(db, o.id)) == 1
|
||||
|
||||
|
||||
def test_a_reason_when_the_venue_asks(client, db, shop, login):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/price-adjust"
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
|
||||
setting(db, "orders.price_change_reason", "true")
|
||||
assert err(client.patch(url, headers=h, json={"price_adjustment": -1})) == "order.price_reason_required"
|
||||
assert err(client.patch(url, headers=h, json={"price_adjustment": -1, "reason": " "})) == "order.price_reason_required"
|
||||
assert client.patch(url, headers=h, json={"price_adjustment": -1, "reason": "Burnt a bit"}).status_code == 200
|
||||
assert manual_events(db, o.id)[0].waiter_note == "Burnt a bit"
|
||||
|
||||
|
||||
def test_a_managers_pin_is_the_approver(client, db, shop, make_user, login):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
boss = make_user(role="owner")
|
||||
approved = client.post("/api/access/override", headers=shop["h"],
|
||||
json={"key": "ordering.prices.modify_sent", "username": boss.username, "pin": TEST_PIN})
|
||||
assert approved.status_code == 200, approved.text
|
||||
h = dict(shop["h"], **{"X-Xenia-Override": approved.json()["override_token"]})
|
||||
assert client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": 1}).status_code == 200
|
||||
[ev] = manual_events(db, o.id)
|
||||
assert ev.approved_by_user_id == boss.id and ev.applied_by_user_id == shop["waiter"].id
|
||||
|
||||
|
||||
def test_a_price_typed_in_the_cart(client, db, menu, phone, floor, make_user, login):
|
||||
oid = open_order(client, phone["h"], floor["t1"])
|
||||
line = {"product_id": menu["coffee"].id, "quantity": 2, "price_adjustment": -0.5, "price_reason": "Friend of the house"}
|
||||
from models.user import WaiterZone
|
||||
w = make_user(role="waiter", add=("ordering.prices.modify",))
|
||||
db.add(WaiterZone(waiter_id=w.id, group_id=None))
|
||||
db.commit()
|
||||
h = login(w, "waiter")
|
||||
r = client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [line]})
|
||||
assert r.status_code == 200, r.text
|
||||
[item] = items_of(db, oid)
|
||||
[ev] = manual_events(db, oid)
|
||||
assert ev.order_item_id == item.id and ev.stage == "cart" and ev.quantity == 2
|
||||
assert (ev.price_before, ev.price_after) == (item.unit_price, item.unit_price - 0.5) and ev.waiter_note == "Friend of the house"
|
||||
# the venue asks for a reason: a typed price without one is refused, nothing is added
|
||||
setting(db, "orders.price_change_reason", "true")
|
||||
assert err(client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [{**line, "price_reason": None}]})) == "order.price_reason_required"
|
||||
assert len(items_of(db, oid)) == 1
|
||||
setting(db, "orders.price_change", "off")
|
||||
assert err(client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [line]})) == "order.price_change_off"
|
||||
|
||||
|
||||
def test_the_counters_discount_is_recorded_without_a_reason(client, db, menu, pair, make_user):
|
||||
from core.timeutil import business_date_of, utcnow
|
||||
from models.business_day import BusinessDay
|
||||
from models.shift import WaiterShift
|
||||
from tests.test_live import terminal_login
|
||||
token, _ = pair("pos_counter", "Till 2")
|
||||
boss = make_user(role="owner")
|
||||
h = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, boss)}"}
|
||||
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() or BusinessDay(
|
||||
status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()), opened_by_id=boss.id)
|
||||
db.add(day)
|
||||
db.flush()
|
||||
db.add(WaiterShift(waiter_id=boss.id, business_day_id=day.id))
|
||||
db.commit()
|
||||
setting(db, "orders.price_change_reason", "true")
|
||||
r = client.post("/api/pos/sales", headers=h, json={"lines": [{"product_id": menu["coffee"].id, "discount_pct": 10}], "payments": [{"method": "card"}]})
|
||||
assert r.status_code == 201, r.text
|
||||
[ev] = manual_events(db, r.json()["order_id"])
|
||||
assert ev.stage == "cart" and ev.waiter_note == "−10 %" and ev.delta_amount < 0
|
||||
|
||||
|
||||
def test_only_holders_see_the_changes(client, db, shop, make_user, login):
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
|
||||
client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": -1, "reason": "x"})
|
||||
seer = login(make_user(role="store_manager"))
|
||||
blind = login(make_user(role="store_manager", remove=("ordering.prices.view_changes",)))
|
||||
assert [e["event_type"] for e in client.get(f"/api/pricing/events/order/{o.id}", headers=seer).json()] == ["manual_price"]
|
||||
assert client.get(f"/api/pricing/events/order/{o.id}", headers=blind).json() == []
|
||||
got = client.get(f"/api/orders/{o.id}/price-changes", headers=seer).json()
|
||||
assert len(got) == 1 and got[0]["before"] == 4.0 and got[0]["after"] == 3.0 and got[0]["reason"] == "x" and got[0]["product_name"]
|
||||
assert client.get(f"/api/orders/{o.id}/price-changes", headers=blind).status_code == 403
|
||||
rep = client.get(f"/api/reports/price-changes?business_day_id={o.business_day_id}" if o.business_day_id else
|
||||
"/api/reports/price-changes", headers=seer).json()
|
||||
assert rep["count"] >= 1 and rep["total_value"] <= -1.0 and rep["by_person"][0]["count"] >= 1
|
||||
assert client.get("/api/reports/price-changes", headers=blind).status_code == 403
|
||||
|
||||
|
||||
def test_combining_lines_keeps_their_changes(client, db, shop, login):
|
||||
o, items = shop["order"], shop["items"]
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
|
||||
for it in items[:2]:
|
||||
assert client.patch(f"/api/orders/{o.id}/items/{it.id}/price-adjust", headers=h, json={"price_adjustment": -1}).status_code == 200
|
||||
r = client.post(f"/api/orders/{o.id}/items/combine", headers=h, json={"item_ids": [items[0].id, items[1].id]})
|
||||
assert r.status_code == 200, r.text
|
||||
assert {e.order_item_id for e in manual_events(db, o.id)} == {items[0].id}
|
||||
assert len(manual_events(db, o.id)) == 2
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Scenes (owner 2026-11-21): named modes of the venue (party mode) that are on or off; price
|
||||
rules follow them ("a scene is on"), signage lines too (tests/test_signage_schedule.py)."""
|
||||
from datetime import timedelta
|
||||
|
||||
from core.timeutil import utcnow
|
||||
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
|
||||
from tests.test_pos import menu, till # noqa: F401 (fixtures)
|
||||
from tests.test_pricing_setup import happy_hour
|
||||
|
||||
|
||||
def test_scenes_are_made_and_switched(client, owner_h, make_user, login):
|
||||
r = client.post("/api/scenes", headers=owner_h, json={"name": " Party mode ", "color": "#ff6699"})
|
||||
assert r.status_code == 201 and r.json()["name"] == "Party mode" and r.json()["active"] is False
|
||||
sid = r.json()["id"]
|
||||
assert client.put(f"/api/scenes/{sid}/active", headers=owner_h, json={"active": True}).json()["active"] is True
|
||||
soon = (utcnow() + timedelta(hours=2)).isoformat()
|
||||
on = client.put(f"/api/scenes/{sid}/active", headers=owner_h, json={"active": True, "until": soon}).json()
|
||||
assert on["active"] is True and on["until"]
|
||||
past = (utcnow() - timedelta(minutes=1)).isoformat()
|
||||
assert err(client.put(f"/api/scenes/{sid}/active", headers=owner_h, json={"active": True, "until": past})) == "scene.until_past"
|
||||
assert err(client.put("/api/scenes/99999/active", headers=owner_h, json={"active": True})) == "scene.not_found"
|
||||
assert client.post("/api/scenes", headers=owner_h, json={"name": "x", "color": "pink"}).status_code == 422
|
||||
# a waiter can't switch scenes
|
||||
h = login(make_user(role="waiter"), client="waiter")
|
||||
assert client.put(f"/api/scenes/{sid}/active", headers=h, json={"active": False}).status_code == 403
|
||||
|
||||
|
||||
def test_a_scene_turns_itself_off(db, client, owner_h):
|
||||
from models.scene import Scene
|
||||
from services.scenes import active_ids
|
||||
s = Scene(name="Brunch", is_active=True, until=utcnow() - timedelta(seconds=1), sort_order=0)
|
||||
db.add(s)
|
||||
db.commit()
|
||||
assert s.id not in active_ids(db)
|
||||
assert client.get("/api/scenes", headers=owner_h).json()[0]["active"] is False
|
||||
|
||||
|
||||
def test_a_price_rule_follows_a_scene(client, owner_h, till, menu):
|
||||
line = {"product_id": menu["coffee"].id, "quantity": 2}
|
||||
sid = client.post("/api/scenes", headers=owner_h, json={"name": "Party mode"}).json()["id"]
|
||||
rule = happy_hour(targets=[{"target_type": "item", "target_ids": [menu["coffee"].id]}])
|
||||
rule["conditions"] = [{"condition_type": "scene_active", "params": {"scene_id": sid}}]
|
||||
r = client.post("/api/pricing/modifiers", headers=owner_h, json=rule)
|
||||
assert r.status_code == 201, r.text
|
||||
assert client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json()["total"] == 6.0
|
||||
client.put(f"/api/scenes/{sid}/active", headers=owner_h, json={"active": True})
|
||||
assert client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json()["total"] == 4.8
|
||||
client.put(f"/api/scenes/{sid}/active", headers=owner_h, json={"active": False})
|
||||
assert client.post("/api/pos/quote", headers=till["h"], json={"lines": [line]}).json()["total"] == 6.0
|
||||
bad = dict(rule, conditions=[{"condition_type": "scene_active", "params": {}}])
|
||||
assert err(client.post("/api/pricing/modifiers", headers=owner_h, json=bad)) == "pricing.bad_condition"
|
||||
@@ -56,7 +56,8 @@ def test_a_screen_plays_its_playlist_in_order(client, owner_h, screens, sent):
|
||||
assert [s["transition"] for s in pl["slides"]] == ["fade", "fade", "zoom"] # the playlist's default
|
||||
assert pl["media"][str(pic["id"])]["url"] == pic["urls"]["full"] and pl["media"][str(vid["id"])]["url"] == vid["urls"]["original"]
|
||||
assert pl["media"][str(bg["id"])]["kind"] == "image" and pl["slides"][2]["content"]["background"]["dim"] == 40
|
||||
assert got["screen"] == {"id": screens[1]["id"], "name": "TV 1", "orientation": "landscape", "rotation": 0}
|
||||
assert got["screen"] == {"id": screens[1]["id"], "name": "TV 1", "orientation": "landscape", "rotation": 0,
|
||||
"area": {"left": 0, "top": 0, "right": 0, "bottom": 0}, "fit": "keep", "calibrating": False}
|
||||
assert len(got["version"]) == 16
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""The signage Slides library and what came with it (owner 2026-11-21): slides kept with a name and a
|
||||
description, added to playlists as copies, shown alone as a screen's default (also behind a
|
||||
schedule); blank slides (a background and widgets); widgets moved and sized by hand (their own
|
||||
box); a menu board narrower than the screen, placed left / centre / right."""
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers)
|
||||
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
|
||||
|
||||
|
||||
def keep(client, h, **body):
|
||||
r = client.post("/api/signage/library", headers=h, json={"name": "Logo", "kind": "blank", **body})
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def test_the_library_keeps_slides(client, owner_h):
|
||||
s = keep(client, owner_h, description=" Our logo, big ", orientation="portrait", duration_s=15,
|
||||
content={"background": {"kind": "colour", "colour": "#102030"}, "widgets": [{"kind": "name", "position": "top-center"}]})
|
||||
assert s["kind"] == "blank" and s["orientation"] == "portrait" and s["description"] == "Our logo, big" and s["duration_s"] == 15
|
||||
assert s["content"]["widgets"][0]["size"] == "medium" and s["screens"] == []
|
||||
r = client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"name": "Logo 2", "description": "", "days": [5, 6]})
|
||||
assert r.json()["name"] == "Logo 2" and r.json()["description"] is None and r.json()["days"] == [5, 6]
|
||||
assert err(client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"kind": "text"})) == "signage.content_invalid"
|
||||
assert err(client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"name": " "})) == "signage.content_invalid"
|
||||
assert err(client.post("/api/signage/library", headers=owner_h, json={"name": "x"})) == "signage.content_invalid" # no kind
|
||||
copy = client.post(f"/api/signage/library/{s['id']}/duplicate", headers=owner_h).json()
|
||||
assert copy["name"] == "Logo 2 (2)" and copy["content"] == r.json()["content"]
|
||||
listed = client.get("/api/signage/library", headers=owner_h).json()
|
||||
assert [x["name"] for x in listed["slides"]] == ["Logo 2", "Logo 2 (2)"] and listed["media"] == {}
|
||||
assert client.delete(f"/api/signage/library/{copy['id']}", headers=owner_h).status_code == 204
|
||||
assert err(client.get(f"/api/signage/library/{copy['id']}", headers=owner_h)) == "signage.slide_unknown"
|
||||
|
||||
|
||||
def test_a_library_slide_protects_its_pictures(client, owner_h, media_dir):
|
||||
pic = up(client, owner_h, jpeg(800, 800)).json()
|
||||
keep(client, owner_h, kind="image", name="Promo", content={"media_id": pic["id"]})
|
||||
r = client.delete(f"/api/media/{pic['id']}", headers=owner_h)
|
||||
assert r.status_code == 409, r.text
|
||||
|
||||
|
||||
def test_a_screen_shows_a_library_slide_when_nothing_else_plays(client, owner_h, screens, sent):
|
||||
s = keep(client, owner_h, content={"widgets": [{"kind": "qr", "position": "bottom-right"}]})
|
||||
tv = screens[1]
|
||||
r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"slide_id": s["id"]})
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["slide_id"] == s["id"] and r.json()["playlist_id"] is None
|
||||
assert r.json()["now"] == {"id": f"slide:{s['id']}", "name": "Logo", "scheduled": False, "slide": True}
|
||||
got = client.get("/api/signage/screen", headers=tv["h"]).json()
|
||||
pl = got["playlist"]
|
||||
assert pl["id"] == f"slide:{s['id']}" and [x["id"] for x in pl["slides"]] == [s["id"]]
|
||||
assert pl["slides"][0]["content"]["widgets"][0]["link"] # the QR's address, as in a playlist
|
||||
# a change to it reaches that screen only
|
||||
sent.clear()
|
||||
client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"duration_s": 20})
|
||||
assert sent == [("signage.changed", [tv["id"]])]
|
||||
# behind a schedule: the slide is the fallback, under its own key
|
||||
p = playlist(client, owner_h, "Lunch")
|
||||
slide(client, owner_h, p["id"], "text", content={"title": "Lunch"})
|
||||
client.put("/api/signage/schedules", headers=owner_h, json={"lines": [
|
||||
{"playlist_id": p["id"], "screen_ids": [tv["id"]], "date_from": "2000-01-01", "date_to": "2000-01-02"}]})
|
||||
got = client.get("/api/signage/screen", headers=tv["h"]).json()
|
||||
assert got["schedule"]["fallback_playlist_id"] == f"slide:{s['id']}" and f"slide:{s['id']}" in got["playlists"]
|
||||
assert got["playlist"]["id"] == f"slide:{s['id']}"
|
||||
# a playlist as the default takes its place (one or the other)
|
||||
r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"playlist_id": p["id"]})
|
||||
assert r.json()["playlist_id"] == p["id"] and r.json()["slide_id"] is None
|
||||
r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"slide_id": s["id"]})
|
||||
assert r.json()["playlist_id"] is None and r.json()["slide_id"] == s["id"]
|
||||
# deleting the slide: the screen shows nothing and is told
|
||||
sent.clear()
|
||||
client.delete(f"/api/signage/library/{s['id']}", headers=owner_h)
|
||||
assert ("signage.changed", [tv["id"]]) in sent
|
||||
assert client.get("/api/signage/screens", headers=owner_h).json()[0]["slide_id"] is None
|
||||
|
||||
|
||||
def test_blank_slides_and_widgets_placed_by_hand(client, owner_h):
|
||||
p = playlist(client, owner_h)
|
||||
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [
|
||||
{"kind": "clock", "position": "custom", "box": {"x": 90, "y": 5, "w": 20, "h": 10}, "align": "right"},
|
||||
{"kind": "date", "position": "top-left", "size": "custom", "box": {"x": 1, "y": 1, "w": 5, "h": 5}},
|
||||
{"kind": "text", "text": "Big", "position": "custom", "box": {"x": 99, "y": -50, "w": 30, "h": 20}}]})
|
||||
clock, date, big = s["content"]["widgets"]
|
||||
# owner review 6: a box may run off the slide (here past the right edge), a strip of it stays on it
|
||||
assert clock["size"] == "custom" and clock["box"] == {"x": 90, "y": 5, "w": 20, "h": 10} and clock["align"] == "right"
|
||||
assert big["box"] == {"x": 95, "y": -15, "w": 30, "h": 20}
|
||||
assert date["size"] == "medium" and date["box"] is None # a corner: no box, a real size
|
||||
# owner 2026-11-23: a picture made larger than the slide (cut off at its edges); a gallery's title below
|
||||
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"widgets": [
|
||||
{"kind": "logo", "position": "custom", "box": {"x": -60, "y": -40, "w": 220, "h": 180}},
|
||||
{"kind": "gallery", "text": "Our dishes", "title_position": "below", "position": "top-left"}]}})
|
||||
logo, gallery = r.json()["content"]["widgets"]
|
||||
assert logo["box"] == {"x": -60, "y": -40, "w": 220, "h": 180}
|
||||
assert gallery["text"] == "Our dishes" and gallery["title_position"] == "below"
|
||||
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"widgets": [
|
||||
{"kind": "logo", "position": "custom", "box": {"x": 0, "y": 0, "w": 401, "h": 10}}]}})
|
||||
assert err(r) == "signage.content_invalid" # at most four times the slide
|
||||
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"widgets": [{"kind": "clock", "position": "custom"}]}})
|
||||
assert err(r) == "signage.content_invalid" # placed by hand needs its box
|
||||
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"title": "x"}})
|
||||
assert err(r) == "signage.content_invalid" # a blank slide has no title
|
||||
|
||||
|
||||
def test_a_menu_board_narrower_than_the_screen(client, owner_h):
|
||||
p = playlist(client, owner_h)
|
||||
s = slide(client, owner_h, p["id"], "menu", content={"select": "all", "board_width": 60, "board_align": "center"})
|
||||
assert s["content"]["board_width"] == 60 and s["content"]["board_align"] == "center"
|
||||
assert slide(client, owner_h, p["id"], "menu")["content"]["board_width"] == 100
|
||||
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"board_width": 20}})
|
||||
assert err(r) == "signage.content_invalid"
|
||||
@@ -97,7 +97,7 @@ def test_prices_sold_out_badges_photos(client, owner_h, tv, menu, db):
|
||||
badges={str(menu["souvlaki"].id): "chef"})
|
||||
_, m = board(client, owner_h, tv, **content)
|
||||
souv, steak = m["groups"][0]["items"]
|
||||
assert (souv["price"], souv["badge"], souv["description"], souv["image"]) == (3.5, "chef", "Pork, on a stick", photo["urls"]["card"])
|
||||
assert (souv["price"], souv["badges"], souv["description"], souv["image"]) == (3.5, ["chef"], "Pork, on a stick", photo["urls"]["card"])
|
||||
assert steak["available"] is False and steak["price"] == 12.0 and steak["image"] is None
|
||||
_, m = board(client, owner_h, tv, **content, sold_out="hide")
|
||||
assert [i["name"] for i in m["groups"][0]["items"]] == ["Souvlaki"]
|
||||
@@ -136,7 +136,7 @@ def test_menu_settings_are_checked(client, owner_h, tv):
|
||||
url = f"/api/signage/playlists/{tv['playlist']}/slides"
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"sales_point": "moon"}})) == "signage.content_invalid"
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"x": "new"}}})) == "signage.content_invalid"
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"3": "shiny"}}})) == "signage.content_invalid"
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"3": "Shiny!"}}})) == "signage.content_invalid"
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"columns": 4}})) == "signage.content_invalid"
|
||||
|
||||
|
||||
@@ -148,4 +148,5 @@ def test_the_editor_previews(client, owner_h, tv, menu):
|
||||
assert names(draft["menu"]) == [["Grill", ["Steak"]]] and draft["content"]["columns"] == 2
|
||||
assert err(client.post("/api/signage/preview/menu", headers=owner_h, json={"content": {"columns": 9}})) == "signage.content_invalid"
|
||||
client.put("/api/signage/message", headers=owner_h, json={"text": "Hello"})
|
||||
assert client.get("/api/signage/venue", headers=owner_h).json() == {"name": None, "message": "Hello", "weather": None}
|
||||
v = client.get("/api/signage/venue", headers=owner_h).json()
|
||||
assert {k: v[k] for k in ("name", "message", "weather")} == {"name": None, "message": "Hello", "weather": None} and len(v["badges"]) == 7
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
"""Signage schedules (plan step 5.4d): which playlist plays when (days, hours that may pass
|
||||
midnight, dates, priority, a fallback); a screen on a schedule gets every playlist in it so it
|
||||
switches by itself, and the server tells it when the pick changes."""
|
||||
from datetime import datetime
|
||||
"""Signage schedules (plan step 5.4d; lines with their screens, smart days and scenes, owner
|
||||
2026-11-21): which playlist plays when (days, hours that may pass midnight, dates, smart days,
|
||||
priority, a scene); no line → the screen's default playlist. A screen with lines gets every
|
||||
playlist they name so it switches by itself, and the server tells it when the pick changes."""
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from core.calendar_days import is_holiday, month_days_ok, orthodox_easter
|
||||
from services.signage_schedule import matches, pick
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
from tests.test_signage import playlist, slide
|
||||
@@ -27,18 +29,37 @@ def test_which_entries_match():
|
||||
assert matches(xmas, datetime(2026, 12, 24, 20, 0)) and not matches(xmas, datetime(2026, 12, 28, 9, 0))
|
||||
assert matches({"playlist_id": 4}, MON_10) # always
|
||||
assert matches({"playlist_id": 5, "time_from": "18:00"}, datetime(2026, 11, 16, 23, 59)) # until the end of the day
|
||||
party = {"playlist_id": 6, "scene_id": 7}
|
||||
assert not matches(party, MON_10) and matches(party, MON_10, {7}) # only while the scene is on
|
||||
|
||||
|
||||
def test_smart_days():
|
||||
"""The same dates as packages/signage/tests/logic.test.mjs."""
|
||||
assert [orthodox_easter(y) for y in (2025, 2026, 2027)] == [date(2025, 4, 20), date(2026, 4, 12), date(2027, 5, 2)]
|
||||
assert is_holiday(date(2026, 3, 25)) and is_holiday(date(2026, 2, 23)) # Independence Day; Clean Monday 2026
|
||||
assert is_holiday(date(2026, 4, 10)) and is_holiday(date(2026, 4, 13)) # Good Friday, Easter Monday
|
||||
assert is_holiday(date(2026, 6, 1)) and not is_holiday(date(2026, 6, 2)) # Whit Monday
|
||||
assert month_days_ok(["first"], date(2026, 11, 1)) and not month_days_ok(["first"], date(2026, 11, 2))
|
||||
assert month_days_ok(["last"], date(2026, 2, 28)) and not month_days_ok(["last"], date(2026, 2, 27))
|
||||
assert month_days_ok(["first_week"], date(2026, 11, 7)) and not month_days_ok(["first_week"], date(2026, 11, 8))
|
||||
assert month_days_ok(["last_week"], date(2026, 11, 24)) and not month_days_ok(["last_week"], date(2026, 11, 23))
|
||||
assert month_days_ok(["first", "last"], date(2026, 11, 30)) # any one is enough
|
||||
assert not month_days_ok(["not_holiday"], date(2026, 12, 25)) and month_days_ok(["not_holiday"], date(2026, 12, 24))
|
||||
assert matches({"playlist_id": 1, "month_days": ["last"], "time_from": "18:00"}, datetime(2026, 11, 30, 19, 0))
|
||||
|
||||
|
||||
def test_the_winner():
|
||||
entries = [{"playlist_id": 10, "time_from": "12:00", "time_to": "15:00"},
|
||||
{"playlist_id": 20, "days": [5, 6]},
|
||||
{"playlist_id": 30, "days": [5, 6], "time_from": "12:00", "time_to": "15:00"},
|
||||
{"playlist_id": 40, "date_from": "2026-11-21", "date_to": "2026-11-21", "priority": 5}]
|
||||
assert pick(entries, 99, MON_10) == 99 # nothing → the fallback
|
||||
{"playlist_id": 40, "date_from": "2026-11-21", "date_to": "2026-11-21", "priority": 5},
|
||||
{"playlist_id": 50, "scene_id": 1, "priority": 9}]
|
||||
assert pick(entries, 99, MON_10) == 99 # nothing → the default
|
||||
assert pick(entries, 99, MON_13) == 10
|
||||
assert pick(entries, 99, datetime(2026, 11, 22, 13, 0)) == 30 # Sunday lunch: days + hours beat hours alone
|
||||
assert pick(entries, 99, SAT_13) == 40 # the higher priority wins
|
||||
assert pick(entries, None, MON_10) is None # no fallback → blank
|
||||
assert pick(entries, 99, SAT_13, {1}) == 50 # party mode on: its line, the highest priority
|
||||
assert pick(entries, None, MON_10) is None # no default → blank
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -64,31 +85,59 @@ def setup(client, owner_h, pair):
|
||||
lunch, weekend, normal = (playlist(client, owner_h, n) for n in ("Lunch", "Weekend", "Normal"))
|
||||
for p in (lunch, weekend, normal):
|
||||
slide(client, owner_h, p["id"], "text", content={"title": p["name"]})
|
||||
r = client.post("/api/signage/schedules", headers=owner_h, json={
|
||||
"name": "The week", "fallback_playlist_id": normal["id"],
|
||||
"entries": [{"playlist_id": lunch["id"], "time_from": "12:00", "time_to": "15:00"},
|
||||
{"playlist_id": weekend["id"], "days": [5, 6], "priority": 1}]})
|
||||
assert r.status_code == 201, r.text
|
||||
token, dev = pair("signage", "TV")
|
||||
client.put(f"/api/signage/screens/{dev.json()['id']}", headers=owner_h, json={"schedule_id": r.json()["id"]})
|
||||
return {"h": {"X-Xenia-Device": token}, "id": dev.json()["id"], "schedule": r.json(),
|
||||
_, other = pair("signage", "Bar TV")
|
||||
tv, bar = dev.json()["id"], other.json()["id"]
|
||||
client.put(f"/api/signage/screens/{tv}", headers=owner_h, json={"playlist_id": normal["id"]})
|
||||
r = client.put("/api/signage/schedules", headers=owner_h, json={"lines": [
|
||||
{"playlist_id": lunch["id"], "screen_ids": [tv], "time_from": "12:00", "time_to": "15:00"},
|
||||
{"playlist_id": weekend["id"], "days": [5, 6], "priority": 1}]}) # no screens: every screen
|
||||
assert r.status_code == 200, r.text
|
||||
return {"h": {"X-Xenia-Device": token}, "id": tv, "bar": bar, "lines": r.json(),
|
||||
"lunch": lunch["id"], "weekend": weekend["id"], "normal": normal["id"]}
|
||||
|
||||
|
||||
def test_a_screen_gets_its_schedule_and_every_playlist(client, owner_h, setup, at):
|
||||
def test_a_screen_gets_its_lines_and_every_playlist(client, owner_h, setup, at):
|
||||
at(MON_10)
|
||||
got = client.get("/api/signage/screen", headers=setup["h"]).json()
|
||||
assert got["playlist"]["name"] == "Normal"
|
||||
assert got["playlist"]["name"] == "Normal" # its default
|
||||
assert sorted(got["playlists"]) == sorted(str(i) for i in (setup["lunch"], setup["weekend"], setup["normal"]))
|
||||
assert got["schedule"]["timezone"] == "Europe/Athens" and len(got["schedule"]["entries"]) == 2
|
||||
assert got["schedule"]["fallback_playlist_id"] == setup["normal"]
|
||||
at(MON_13)
|
||||
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Lunch"
|
||||
at(SAT_13)
|
||||
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Weekend"
|
||||
s = client.get("/api/signage/schedules", headers=owner_h).json()[0]
|
||||
assert s["playing_now"]["name"] == "Weekend" and [x["name"] for x in s["screens"]] == ["TV"]
|
||||
screen = client.get("/api/signage/screens", headers=owner_h).json()[0]
|
||||
assert screen["schedule_name"] == "The week" and screen["orientation_mismatch"] is False
|
||||
lines = client.get("/api/signage/schedules", headers=owner_h).json()
|
||||
assert sorted(x["name"] for x in lines[1]["playing_on"]) == ["Bar TV", "TV"] # the weekend line is for every screen
|
||||
screens = {s["name"]: s for s in client.get("/api/signage/screens", headers=owner_h).json()}
|
||||
assert screens["TV"]["playlist_name"] == "Normal" and screens["TV"]["now"] == {"id": setup["weekend"], "name": "Weekend", "scheduled": True}
|
||||
assert screens["TV"]["orientation_mismatch"] is False
|
||||
|
||||
|
||||
def test_scenes_switch_screens_and_prices(client, db, owner_h, setup, at, sent):
|
||||
"""A scene (party mode): its schedule line plays while it is on; a price rule follows it too."""
|
||||
at(MON_10)
|
||||
party = playlist(client, owner_h, "Party")
|
||||
slide(client, owner_h, party["id"], "text", content={"title": "Party"})
|
||||
scene = client.post("/api/scenes", headers=owner_h, json={"name": "Party mode", "color": "#ff6699"}).json()
|
||||
lines = client.get("/api/signage/schedules", headers=owner_h).json()
|
||||
body = [{k: x[k] for k in ("id", "playlist_id", "screen_ids", "priority", "days", "time_from", "time_to")} for x in lines]
|
||||
body.append({"playlist_id": party["id"], "scene_id": scene["id"], "priority": 50})
|
||||
assert client.put("/api/signage/schedules", headers=owner_h, json={"lines": body}).status_code == 200
|
||||
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Normal"
|
||||
sent.clear()
|
||||
r = client.put(f"/api/scenes/{scene['id']}/active", headers=owner_h, json={"active": True})
|
||||
assert r.status_code == 200 and r.json()["active"] is True
|
||||
assert ("signage.changed", sorted([setup["id"], setup["bar"]])) in sent
|
||||
got = client.get("/api/signage/screen", headers=setup["h"]).json()
|
||||
assert got["playlist"]["name"] == "Party" and got["schedule"]["scenes"] == [scene["id"]]
|
||||
client.put(f"/api/scenes/{scene['id']}/active", headers=owner_h, json={"active": False})
|
||||
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Normal"
|
||||
# deleting the scene turns its line off (it would otherwise play always)
|
||||
assert client.delete(f"/api/scenes/{scene['id']}", headers=owner_h).status_code == 204
|
||||
left = [x for x in client.get("/api/signage/schedules", headers=owner_h).json() if x["playlist_id"] == party["id"]]
|
||||
assert left[0]["enabled"] is False and left[0]["scene_id"] is None
|
||||
|
||||
|
||||
def test_the_server_tells_a_screen_when_its_playlist_switches(client, db, setup, at):
|
||||
@@ -100,7 +149,7 @@ def test_the_server_tells_a_screen_when_its_playlist_switches(client, db, setup,
|
||||
at(datetime(2026, 11, 16, 11, 59, 40))
|
||||
assert ss.due_changes(db) == []
|
||||
at(datetime(2026, 11, 16, 12, 0))
|
||||
assert ss.due_changes(db) == [setup["id"]] # lunch starts
|
||||
assert ss.due_changes(db) == [setup["id"]] # lunch starts (only on the TV)
|
||||
assert ss.due_changes(db) == []
|
||||
at(datetime(2026, 11, 16, 15, 0))
|
||||
assert ss.due_changes(db) == [setup["id"]] # and ends
|
||||
@@ -108,31 +157,31 @@ def test_the_server_tells_a_screen_when_its_playlist_switches(client, db, setup,
|
||||
|
||||
|
||||
def test_changes_and_deletes(client, owner_h, setup, sent, at):
|
||||
at(MON_10)
|
||||
sid = setup["schedule"]["id"]
|
||||
at(MON_13)
|
||||
lines = client.get("/api/signage/schedules", headers=owner_h).json()
|
||||
sent.clear()
|
||||
client.put(f"/api/signage/schedules/{sid}", headers=owner_h, json={"name": "The week", "fallback_playlist_id": setup["lunch"], "entries": []})
|
||||
assert sent == [("signage.changed", [setup["id"]])]
|
||||
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Lunch"
|
||||
# a slide changed in a playlist of the schedule reaches the screen
|
||||
lunch = client.get(f"/api/signage/playlists/{setup['lunch']}", headers=owner_h).json()
|
||||
assert client.put("/api/signage/schedules", headers=owner_h, json={"lines": [{"id": lines[1]["id"], "playlist_id": setup["weekend"], "days": [5, 6]}]}).status_code == 200
|
||||
assert sorted(sent[0][1]) == sorted([setup["id"], setup["bar"]])
|
||||
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Normal" # the lunch line is gone
|
||||
# a slide changed in a playlist of its lines reaches the screen
|
||||
wk = client.get(f"/api/signage/playlists/{setup['weekend']}", headers=owner_h).json()
|
||||
sent.clear()
|
||||
client.put(f"/api/signage/slides/{lunch['slides'][0]['id']}", headers=owner_h, json={"duration_s": 20})
|
||||
assert sent == [("signage.changed", [setup["id"]])]
|
||||
# deleting a playlist takes it out of the schedule
|
||||
client.delete(f"/api/signage/playlists/{setup['lunch']}", headers=owner_h)
|
||||
assert client.get("/api/signage/schedules", headers=owner_h).json()[0]["fallback_playlist_id"] is None
|
||||
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"] is None
|
||||
# deleting the schedule: the screen goes back to its playlist (none here)
|
||||
assert client.delete(f"/api/signage/schedules/{sid}", headers=owner_h).status_code == 204
|
||||
client.put(f"/api/signage/slides/{wk['slides'][0]['id']}", headers=owner_h, json={"duration_s": 20})
|
||||
assert sorted(sent[0][1]) == sorted([setup["id"], setup["bar"]])
|
||||
# deleting a playlist takes its lines with it
|
||||
client.delete(f"/api/signage/playlists/{setup['weekend']}", headers=owner_h)
|
||||
assert client.get("/api/signage/schedules", headers=owner_h).json() == []
|
||||
got = client.get("/api/signage/screen", headers=setup["h"]).json()
|
||||
assert got["schedule"] is None and got["playlist"] is None
|
||||
assert got["schedule"] is None and got["playlist"]["name"] == "Normal"
|
||||
|
||||
|
||||
def test_schedules_are_checked(client, owner_h, setup):
|
||||
body = {"name": "Bad", "entries": [{"playlist_id": 99999}]}
|
||||
assert err(client.post("/api/signage/schedules", headers=owner_h, json=body)) == "signage.playlist_unknown"
|
||||
assert client.post("/api/signage/schedules", headers=owner_h, json={"name": "x", "entries": [{"playlist_id": setup["lunch"], "days": [9]}]}).status_code == 422
|
||||
assert client.post("/api/signage/schedules", headers=owner_h, json={"name": "x", "entries": [{"playlist_id": setup["lunch"], "time_to": "24:00"}]}).status_code == 422
|
||||
assert err(client.put(f"/api/signage/screens/{setup['id']}", headers=owner_h, json={"schedule_id": 99999})) == "validation.device_config"
|
||||
assert err(client.get("/api/signage/schedules/99999", headers=owner_h)) in ("http.404", "http.405")
|
||||
put = lambda line: client.put("/api/signage/schedules", headers=owner_h, json={"lines": [line]}) # noqa: E731
|
||||
assert err(put({"playlist_id": 99999})) == "signage.playlist_unknown"
|
||||
assert err(put({"playlist_id": setup["lunch"], "screen_ids": [99999]})) == "signage.screen_unknown"
|
||||
assert err(put({"playlist_id": setup["lunch"], "scene_id": 99999})) == "signage.scene_unknown"
|
||||
assert put({"playlist_id": setup["lunch"], "days": [9]}).status_code == 422
|
||||
assert put({"playlist_id": setup["lunch"], "month_days": ["fullmoon"]}).status_code == 422
|
||||
assert put({"playlist_id": setup["lunch"], "time_to": "24:00"}).status_code == 422
|
||||
assert put({"playlist_id": setup["lunch"], "month_days": ["last", "first"]}).json()[0]["month_days"] == ["first", "last"]
|
||||
assert err(client.put(f"/api/signage/screens/{setup['id']}", headers=owner_h, json={"playlist_id": 99999})) == "validation.device_config"
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Slide shapes and a screen's picture (6R.13, owner 2026-11-22): custom shapes for playlists and
|
||||
library slides, a screen's picture area (insets) and fit, calibrating told to that screen only,
|
||||
the window size a screen reports."""
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
|
||||
|
||||
|
||||
def test_custom_shapes_for_playlists_and_library_slides(client, owner_h):
|
||||
p = playlist(client, owner_h, aspect="21:9")
|
||||
assert (p["orientation"], p["aspect"]) == ("landscape", "21:9")
|
||||
r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "10:16"})
|
||||
assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", "10:16")
|
||||
# the plain shapes are landscape / portrait; picking one drops a custom shape
|
||||
r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "16:9"})
|
||||
assert (r.json()["orientation"], r.json()["aspect"]) == ("landscape", None)
|
||||
client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "32:9"})
|
||||
r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"orientation": "portrait"})
|
||||
assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", None)
|
||||
for bad in ("21x9", "9:1", "0:5"):
|
||||
assert client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": bad}).status_code == 422
|
||||
dup = client.post(f"/api/signage/playlists/{p['id']}/duplicate", headers=owner_h).json()
|
||||
assert dup["orientation"] == "portrait"
|
||||
s = client.post("/api/signage/library", headers=owner_h, json={"name": "Wide", "kind": "text", "aspect": "16:10"}).json()
|
||||
assert (s["orientation"], s["aspect"]) == ("landscape", "16:10")
|
||||
r = client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"aspect": None, "orientation": "portrait"})
|
||||
assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", None)
|
||||
|
||||
|
||||
def test_a_screens_picture_area_and_calibration(client, owner_h, screens, sent):
|
||||
tv, other = screens[1], screens[2]
|
||||
p = playlist(client, owner_h, aspect="21:9")
|
||||
slide(client, owner_h, p["id"], "text", content={"title": "Wide"})
|
||||
client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"playlist_id": p["id"]})
|
||||
got = client.get("/api/signage/screen", headers=tv["h"]).json()
|
||||
assert got["playlist"]["aspect"] == "21:9" and got["screen"]["fit"] == "keep" and got["screen"]["calibrating"] is False
|
||||
# the TV reports its window; the manager sees it
|
||||
assert client.post("/api/signage/screen/viewport", headers=tv["h"], json={"width": 2560, "height": 1080, "ratio": 1}).status_code == 200
|
||||
one = next(s for s in client.get("/api/signage/screens", headers=owner_h).json() if s["id"] == tv["id"])
|
||||
assert one["viewport"] == {"width": 2560, "height": 1080, "ratio": 1.0} and one["area"] == {"left": 0, "top": 0, "right": 0, "bottom": 0}
|
||||
# calibrating: only that TV hears it, with its area; every change of the insets follows at once
|
||||
sent.clear()
|
||||
r = client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": True})
|
||||
assert r.json()["calibrating"] is True and sent == [("signage.calibrate", [tv["id"]])]
|
||||
sent.clear()
|
||||
r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": 320, "area_right": 320, "fit": "stretch"})
|
||||
assert r.json()["area"] == {"left": 320, "top": 0, "right": 320, "bottom": 0} and r.json()["fit"] == "stretch"
|
||||
assert sent[0] == ("signage.calibrate", [tv["id"]]) and ("signage.changed", [tv["id"]]) in sent
|
||||
scr = client.get("/api/signage/screen", headers=tv["h"]).json()["screen"]
|
||||
assert scr["area"]["left"] == 320 and scr["calibrating"] is True
|
||||
sent.clear()
|
||||
client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": False})
|
||||
assert sent == [("signage.calibrate", [tv["id"]])]
|
||||
sent.clear()
|
||||
client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_top": 5})
|
||||
assert ("signage.calibrate", [tv["id"]]) not in sent
|
||||
# limits; not a screen
|
||||
assert client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": 5000}).status_code == 422
|
||||
# owner 2026-11-23: an edge may reach past the window the TV reported (its real picture is larger)
|
||||
r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": -60, "area_top": 0})
|
||||
assert r.status_code == 200 and r.json()["area"]["left"] == -60
|
||||
assert client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": -2001}).status_code == 422
|
||||
assert err(client.post("/api/signage/screens/99999/calibrate", headers=owner_h, json={"on": True})) == "signage.not_a_screen"
|
||||
# a screen can't calibrate itself or report for another
|
||||
assert client.post(f"/api/signage/screens/{other['id']}/calibrate", headers=tv["h"], json={"on": True}).status_code in (401, 403)
|
||||
|
||||
|
||||
def test_calibration_ends_by_itself(client, owner_h, screens, monkeypatch):
|
||||
import routers.signage as sg
|
||||
tv = screens[1]
|
||||
client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": True})
|
||||
assert sg.calibrating(tv["id"]) is True
|
||||
sg._calibrating[tv["id"]] -= sg.CALIBRATE_S + 1
|
||||
assert client.get("/api/signage/screen", headers=tv["h"]).json()["screen"]["calibrating"] is False
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Signage widgets, owner review 2026-11-21: a text of its own, a menu widget (a board's list in the
|
||||
widget's place), stacks (parts side by side or one over the other, each with a widget, another
|
||||
stack one level deep, or a whole library slide), weather for tomorrow / the day after and in three
|
||||
styles; products hidden from a board stay in the editor's list (greyed), never on the TV."""
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
|
||||
from tests.test_signage_menu import menu, names # noqa: F401 (fixture + helper)
|
||||
|
||||
BOX = {"x": 5, "y": 10, "w": 90, "h": 80}
|
||||
|
||||
|
||||
def stack(*cells, direction="row"):
|
||||
return {"kind": "stack", "direction": direction, "position": "custom", "box": BOX, "cells": list(cells)}
|
||||
|
||||
|
||||
def keep(client, h, **body):
|
||||
r = client.post("/api/signage/library", headers=h, json={"name": "Promo", "kind": "text", **body})
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def test_text_weather_and_stack_widgets_are_checked(client, owner_h):
|
||||
p = playlist(client, owner_h)
|
||||
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [
|
||||
{"kind": "text", "text": "Happy hour 18-20"},
|
||||
{"kind": "weather", "weather_from": 5, "weather_days": 3, "weather_style": "icon"},
|
||||
stack({"share": 30, "widget": {"kind": "clock"}}, {"share": 70, "widget": stack({"share": 50}, {"share": 50}, direction="column")}),
|
||||
]})
|
||||
ws = s["content"]["widgets"]
|
||||
assert ws[0]["text"] == "Happy hour 18-20"
|
||||
assert ws[1]["weather_from"] == 5 and ws[1]["weather_days"] == 2 and ws[1]["weather_style"] == "icon" # the forecast has 7 days (6R.18)
|
||||
assert [c["share"] for c in ws[2]["cells"]] == [30, 70] and ws[2]["cells"][1]["widgets"][0]["direction"] == "column"
|
||||
assert ws[0]["cells"] == [] and ws[0]["board"] is None
|
||||
url = f"/api/signage/playlists/{p['id']}/slides"
|
||||
bad = [
|
||||
stack(), # no parts
|
||||
stack({"share": 50, "widget": {"kind": "clock"}, "slide_id": 1}), # a widget and a slide
|
||||
stack({"share": 50, "widget": stack({"share": 50, "widget": stack({"share": 100})})}), # three stacks deep
|
||||
stack(*[{"share": 10}] * 7), # more than 6 parts
|
||||
]
|
||||
for w in bad:
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": [w]}})) == "signage.content_invalid", w
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": [stack({"share": 100, "slide_id": 999})]}})) == "signage.slide_unknown"
|
||||
|
||||
|
||||
def test_a_stack_shows_a_library_slide_and_a_menu_widget(client, owner_h, screens, sent, menu, db):
|
||||
promo = keep(client, owner_h, content={"title": "Fresh fish", "widgets": [{"kind": "qr", "position": "bottom-right"}]})
|
||||
p = playlist(client, owner_h, "Split")
|
||||
tv = screens[1]
|
||||
client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"playlist_id": p["id"]})
|
||||
board = {"kind": "menu", "board": {"category_ids": [menu["cats"]["drinks"]], "exclude_ids": [menu["beer"].id], "columns": 1}}
|
||||
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [
|
||||
{"kind": "qr", "position": "top-left"},
|
||||
stack({"share": 25, "widget": board}, {"share": 75, "slide_id": promo["id"]}),
|
||||
]})
|
||||
# the screen: extras by widget path (the QR's link, the menu's products, the slide inside the part)
|
||||
got = client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]
|
||||
ex = got["extras"]
|
||||
assert ex["0"]["link"] and got["content"]["widgets"][0]["link"] == ex["0"]["link"]
|
||||
assert names(ex["1.0.0"]["menu"]) == [] and ex["1.0.0"]["menu"]["count"] == 0 # Beer hidden; Wine: delivery only
|
||||
inner = ex["1.1"]["slide"]
|
||||
assert inner["id"] == promo["id"] and inner["kind"] == "text" and inner["content"]["title"] == "Fresh fish"
|
||||
assert inner["extras"]["0"]["link"] # its own widgets' extras
|
||||
# the editor: the hidden product stays in the list, marked
|
||||
ed = client.get(f"/api/signage/playlists/{p['id']}", headers=owner_h).json()["slides"][0]["extras"]["1.0.0"]["menu"]
|
||||
assert [(i["name"], i.get("hidden", False)) for g in ed["groups"] for i in g["items"]] == [("Beer", True)] and ed["count"] == 0
|
||||
# a change to the library slide reaches the screens that show it inside a stack
|
||||
sent.clear()
|
||||
client.put(f"/api/signage/library/{promo['id']}", headers=owner_h, json={"content": {"title": "Fresh octopus"}})
|
||||
assert sent == [("signage.changed", [tv["id"]])]
|
||||
assert client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]["extras"]["1.1"]["slide"]["content"]["title"] == "Fresh octopus"
|
||||
# products change: a slide with a menu widget is told too
|
||||
import routers.signage as sg
|
||||
sent.clear()
|
||||
sg.menu_changed(db)
|
||||
assert sent == [("signage.changed", [tv["id"]])]
|
||||
# the library slide deleted: the part shows nothing, the screen is told
|
||||
sent.clear()
|
||||
client.delete(f"/api/signage/library/{promo['id']}", headers=owner_h)
|
||||
assert sent == [("signage.changed", [tv["id"]])]
|
||||
assert "1.1" not in client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]["extras"]
|
||||
assert s["content"]["widgets"][1]["cells"][1]["slide_id"] == promo["id"]
|
||||
|
||||
|
||||
def test_the_editor_previews_any_slide(client, owner_h, menu):
|
||||
promo = keep(client, owner_h, content={"title": "Inside"})
|
||||
r = client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "blank", "content": {"widgets": [
|
||||
stack({"share": 50, "widget": {"kind": "menu", "board": {"product_ids": [menu["steak"].id], "exclude_ids": [menu["steak"].id]}}},
|
||||
{"share": 50, "slide_id": promo["id"]})]}})
|
||||
assert r.status_code == 200, r.text
|
||||
got = r.json()
|
||||
assert [i.get("hidden") for g in got["extras"]["0.0.0"]["menu"]["groups"] for i in g["items"]] == [True]
|
||||
assert got["extras"]["0.1"]["slide"]["content"]["title"] == "Inside" and got["menu"] is None and got["media"] == {}
|
||||
r = client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "menu", "content": {"select": "all", "exclude_ids": [menu["beer"].id]}})
|
||||
m = r.json()["menu"]
|
||||
assert "Beer" in [i["name"] for g in m["groups"] for i in g["items"] if i.get("hidden")] and m["count"] == 3
|
||||
assert err(client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "text", "content": {"widgets": [stack()]}})) == "signage.content_invalid"
|
||||
|
||||
|
||||
def test_a_board_has_its_own_names_and_the_look_of_each_part(client, owner_h, menu):
|
||||
"""Owner review 3 (2026-11-21): names only for this board (the catalogue keeps its own), the look
|
||||
of headings, names, prices and the dots, spacing, photos."""
|
||||
content = {"category_ids": [menu["cats"]["drinks"]], "names": {str(menu["beer"].id): " Craft beer "}, "category_names": {str(menu["cats"]["drinks"]): "Bar"},
|
||||
"heading_style": {"size": 180, "colour": "#ff0000", "font": "serif", "align": "center", "italic": True},
|
||||
"price_style": {"align": "right", "bold": False}, "dot_style": {"style": "dashed", "size": 150},
|
||||
"line_height": 1.4, "letter_spacing": 0.05, "photo_size": 150, "photo_shape": "round"}
|
||||
r = client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "menu", "content": content})
|
||||
assert r.status_code == 200, r.text
|
||||
g = r.json()["menu"]["groups"][0]
|
||||
assert g["category"] == {"id": menu["cats"]["drinks"], "name": "Bar", "original": "Drinks"}
|
||||
assert g["items"][0]["name"] == "Craft beer" and g["items"][0]["original"] == "Beer"
|
||||
p = playlist(client, owner_h)
|
||||
s = slide(client, owner_h, p["id"], "menu", content=content)
|
||||
c = s["content"]
|
||||
assert c["names"] == {str(menu["beer"].id): "Craft beer"} and c["heading_style"]["italic"] and c["item_style"]["bold"]
|
||||
assert c["price_style"] == {"size": None, "colour": None, "font": None, "bold": False, "italic": False, "underline": False, "align": "right"}
|
||||
url = f"/api/signage/playlists/{p['id']}/slides"
|
||||
for bad in ({"names": {"x": "a"}}, {"heading_style": {"size": 20}}, {"dot_style": {"style": "wavy"}}, {"line_height": 9}, {"photo_shape": "star"}):
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": bad})) == "signage.content_invalid", bad
|
||||
|
||||
|
||||
def test_a_part_holds_several_widgets_and_colours_can_be_see_through(client, owner_h, menu):
|
||||
"""Owner review 4 (2026-11-21): a stack's part holds several widgets (each with its own extras,
|
||||
by path "stack.part.place"); a part stored with one `widget` still reads; colours #rrggbbaa; a
|
||||
board's badges have their own text colour."""
|
||||
p = playlist(client, owner_h)
|
||||
s = slide(client, owner_h, p["id"], "blank", content={"background": {"colour": "#11182780"}, "widgets": [
|
||||
stack({"share": 40, "widgets": [{"kind": "clock"}, {"kind": "qr"}, {"kind": "menu", "board": {"product_ids": [menu["steak"].id]}}]},
|
||||
{"share": 60, "widget": {"kind": "date"}}),
|
||||
]})
|
||||
cells = s["content"]["widgets"][0]["cells"]
|
||||
assert [w["kind"] for w in cells[0]["widgets"]] == ["clock", "qr", "menu"] and [w["kind"] for w in cells[1]["widgets"]] == ["date"]
|
||||
assert "widget" not in cells[1] and s["content"]["background"]["colour"] == "#11182780"
|
||||
ex = client.get(f"/api/signage/playlists/{p['id']}", headers=owner_h).json()["slides"][0]["extras"]
|
||||
assert ex["0.0.1"]["link"] and names(ex["0.0.2"]["menu"]) == [["Grill", ["Steak"]]]
|
||||
url = f"/api/signage/playlists/{p['id']}/slides"
|
||||
for bad in (stack({"share": 50, "widgets": [{"kind": "clock"}], "slide_id": 1}),
|
||||
stack({"share": 50, "widgets": [{"kind": "clock"}] * 7})):
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": [bad]}})) == "signage.content_invalid", bad
|
||||
m = slide(client, owner_h, p["id"], "menu", content={"accent_colour": "#1e3a8a", "badge_text_colour": "#fde68aCC"})["content"]
|
||||
assert m["badge_text_colour"] == "#fde68aCC" and m["accent_colour"] == "#1e3a8a"
|
||||
for bad in ({"badge_text_colour": "#fff"}, {"text_colour": "#12345"}):
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": bad})) == "signage.content_invalid", bad
|
||||
|
||||
|
||||
def test_the_venues_badges_and_a_widgets_own_look(client, owner_h, menu, screens):
|
||||
"""Owner review 5 (2026-11-21): the venue's badges (names, colours, icons) edited in one place and
|
||||
sent with the venue; a product with several badges; a widget's own look; a board's list placed
|
||||
up or down."""
|
||||
got = client.get("/api/signage/badges", headers=owner_h).json()
|
||||
assert [b["key"] for b in got["badges"]][:3] == ["new", "chef", "offer"] and "flame" in got["icons"]
|
||||
mine = got["badges"][:2] + [{"key": "gluten-free", "names": {"el": "Χωρίς γλουτένη", "en": "Gluten free"}, "colour": "#0ea5e9", "text_colour": "#ffffff", "icon": "wheat-off"}]
|
||||
r = client.put("/api/signage/badges", headers=owner_h, json={"badges": mine})
|
||||
assert r.status_code == 200, r.text and [b["key"] for b in r.json()["badges"]] == ["new", "chef", "gluten-free"]
|
||||
for bad in ([{"key": "x", "names": {}}], [{"key": "x", "names": {"en": "X"}, "icon": "unicorn"}],
|
||||
[{"key": "x", "names": {"en": "X"}}, {"key": "x", "names": {"en": "Y"}}]):
|
||||
assert err(client.put("/api/signage/badges", headers=owner_h, json={"badges": bad})) == "signage.content_invalid", bad
|
||||
assert client.get("/api/signage/venue", headers=owner_h).json()["badges"][2]["icon"] == "wheat-off"
|
||||
p = playlist(client, owner_h)
|
||||
sid = str(menu["steak"].id)
|
||||
s = slide(client, owner_h, p["id"], "menu", content={"product_ids": [menu["steak"].id], "badges": {sid: ["chef", "gluten-free"]},
|
||||
"board_valign": "middle", "badge_colour": "#000000", "widgets": [
|
||||
{"kind": "qr", "qr_colour": "#1e3a8a", "qr_background": "#fde68a", "colour": "#ff0000", "bold": False, "italic": True, "font": "serif", "text_size": 150,
|
||||
"background_colour": "#00000080"},
|
||||
stack({"share": 100, "widgets": [{"kind": "clock", "vertical": "bottom", "align": "right"},
|
||||
{"kind": "date", "position": "custom", "box": {"x": 10, "y": 10, "w": 50, "h": 40}}]})]})
|
||||
c = s["content"]
|
||||
assert c["badges"] == {sid: ["chef", "gluten-free"]} and c["board_valign"] == "middle" and c["badge_colour"] == "#000000"
|
||||
q = c["widgets"][0]
|
||||
assert (q["qr_colour"], q["qr_background"], q["bold"], q["italic"], q["text_size"], q["font"]) == ("#1e3a8a", "#fde68a", False, True, 150, "serif")
|
||||
part = c["widgets"][1]["cells"][0]["widgets"]
|
||||
assert part[0]["vertical"] == "bottom" and part[1]["box"] == {"x": 10, "y": 10, "w": 50, "h": 40}
|
||||
url = f"/api/signage/playlists/{p['id']}/slides"
|
||||
for bad in ({"badges": {sid: ["a", "b", "c", "d", "e"]}}, {"board_valign": "centre"}, {"widgets": [{"kind": "clock", "text_size": 400}]}):
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": bad})) == "signage.content_invalid", bad
|
||||
|
||||
|
||||
def test_how_many_widgets_a_slide_may_hold_is_the_venues(client, owner_h):
|
||||
"""Owner review 6 (2026-11-21): 10 widgets a slide (recommended), more when the venue allows them
|
||||
(Signage → Message & settings → Performance), never over 50; a menu with pages may now turn them
|
||||
every second."""
|
||||
assert client.get("/api/signage/performance", headers=owner_h).json() == {"max_widgets": 10, "recommended": 10, "cap": 50}
|
||||
p = playlist(client, owner_h)
|
||||
url = f"/api/signage/playlists/{p['id']}/slides"
|
||||
eleven = [{"kind": "clock"}] * 11
|
||||
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": eleven}})) == "signage.too_many_widgets"
|
||||
assert client.put("/api/signage/performance", headers=owner_h, json={"max_widgets": 12}).json()["max_widgets"] == 12
|
||||
assert client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": eleven}}).status_code == 201
|
||||
assert err(client.put("/api/signage/performance", headers=owner_h, json={"max_widgets": 51})) is not None
|
||||
s = slide(client, owner_h, p["id"], "menu", content={"page_seconds": 1}, duration_s=1)
|
||||
assert s["content"]["page_seconds"] == 1 and s["duration_s"] == 1
|
||||
@@ -104,6 +104,8 @@ def test_the_weather_shows_with_internet_and_hides_without(client, owner_h, tv,
|
||||
assert ("signage.changed", [tv["id"]]) in sent
|
||||
w = client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["weather"]
|
||||
assert w["place"] == "Kalavryta" and w["code"] == 2 and [d["max"] for d in w["days"]] == [19.0, 16.5] and w["units"] == "celsius"
|
||||
# 6R.18: an answer without the detailed fields still reads (they are None)
|
||||
assert w["feels_like"] is None and w["days"][0]["sunrise"] is None and w["hours"] == [] and w["wind_unit"] == "km/h"
|
||||
# the internet goes: the last forecast stays while it is fresh, then the widget hides
|
||||
internet["up"] = False
|
||||
sent.clear()
|
||||
@@ -128,3 +130,28 @@ def test_who_may(client, make_user, login):
|
||||
waiter = login(make_user(role="waiter"))
|
||||
assert client.put("/api/signage/message", headers=waiter, json={"text": "x"}).status_code == 403
|
||||
assert client.get("/api/signage/weather", headers=waiter).status_code == 403
|
||||
|
||||
|
||||
def test_the_detailed_weather(monkeypatch):
|
||||
"""6R.18: humidity, feels like, wind, rain chance, sunrise / sunset, UV and the next 24 hours."""
|
||||
import asyncio
|
||||
import httpx
|
||||
from services import weather
|
||||
hours = [f"2026-11-17T{h:02d}:00" for h in range(24)] + [f"2026-11-18T{h:02d}:00" for h in range(24)]
|
||||
answer = {"current": {"time": "2026-11-17T12:15", "temperature_2m": 17.4, "weather_code": 2, "is_day": 1, "apparent_temperature": 15.9,
|
||||
"relative_humidity_2m": 62, "wind_speed_10m": 12.3, "wind_direction_10m": 200, "precipitation": 0},
|
||||
"daily": {"time": ["2026-11-17", "2026-11-18"], "temperature_2m_max": [19.0, 16.5], "temperature_2m_min": [9.1, 8.0],
|
||||
"weather_code": [2, 61], "precipitation_probability_max": [10, 80], "wind_speed_10m_max": [20, 35], "uv_index_max": [3.2, 1.0],
|
||||
"sunrise": ["2026-11-17T07:12", "2026-11-18T07:13"], "sunset": ["2026-11-17T17:08", "2026-11-18T17:07"]},
|
||||
"hourly": {"time": hours, "temperature_2m": list(range(48)), "weather_code": [0] * 48, "precipitation_probability": [5] * 48, "is_day": [1] * 48}}
|
||||
seen = {}
|
||||
|
||||
def handler(req):
|
||||
seen.update(dict(req.url.params))
|
||||
return httpx.Response(200, json=answer)
|
||||
c = httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
||||
w = asyncio.run(weather.fetch({"name": "X", "latitude": 1, "longitude": 2, "units": "fahrenheit"}, c))
|
||||
assert seen["forecast_days"] == "7" and seen["wind_speed_unit"] == "mph" and "hourly" in seen
|
||||
assert w["feels_like"] == 15.9 and w["humidity"] == 62 and w["wind"] == 12.3 and w["wind_unit"] == "mph"
|
||||
assert w["days"][1] == {"date": "2026-11-18", "max": 16.5, "min": 8.0, "code": 61, "rain": 80, "wind": 35, "uv": 1.0, "sunrise": "07:13", "sunset": "17:07"}
|
||||
assert len(w["hours"]) == 24 and w["hours"][0]["time"] == "12:00" and w["hours"][0]["temp"] == 12 and w["hours"][-1]["time"] == "11:00"
|
||||
|
||||
@@ -8,3 +8,13 @@ def test_venue_theme_reaches_bootstrap(client, make_user, login):
|
||||
assert client.get("/api/platform/bootstrap").json()["venue"]["theme"] == "blue"
|
||||
r = client.put("/api/settings/venue.theme", headers=owner, json={"value": "neon"})
|
||||
assert r.status_code in (400, 422)
|
||||
|
||||
|
||||
def test_the_identity_as_the_staff_apps_colour(client, make_user, login):
|
||||
"""6R.20: venue.theme "identity" = the first colour of the venue's identity; bootstrap carries it and the logos."""
|
||||
owner = login(make_user(role="owner"))
|
||||
assert client.get("/api/platform/bootstrap").json()["venue"]["identity"]["colour"] is None
|
||||
client.put("/api/identity", headers=owner, json={"colours": [{"name": "Main", "colour": "#1E3A8A"}], "slogan": "Since 1987"})
|
||||
assert client.put("/api/settings/venue.theme", headers=owner, json={"value": "identity"}).status_code == 200
|
||||
v = client.get("/api/platform/bootstrap").json()["venue"]
|
||||
assert v["theme"] == "identity" and v["identity"]["colour"] == "#1e3a8a" and v["identity"]["slogan"] == "Since 1987" and v["identity"]["logo"] is None
|
||||
|
||||
@@ -98,10 +98,13 @@ def test_revert_payment_is_a_key_a_manager_can_approve(client, db, shop):
|
||||
|
||||
|
||||
def test_price_change_needs_only_the_key_no_venue_switch(client, shop, login):
|
||||
"""A sent line's price: ordering.prices.modify_sent since 6F.3 (modify alone is for the cart)."""
|
||||
o, item = shop["order"], shop["items"][0]
|
||||
url = f"/api/orders/{o.id}/items/{item.id}/price-adjust"
|
||||
assert err(client.patch(url, headers=shop["h"], json={"price_adjustment": -1})) == "access.override_possible"
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify",)), client="waiter")
|
||||
assert err(client.patch(url, headers=h, json={"price_adjustment": -1})) == "access.override_possible"
|
||||
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
|
||||
r = client.patch(url, headers=h, json={"price_adjustment": -1})
|
||||
assert r.status_code == 200, r.text
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { lazy, Suspense } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { BrowserRouter, Routes, Route, Navigate, Outlet } from 'react-router-dom'
|
||||
import { AccessProvider } from '@xenia/access'
|
||||
import { VenueIdentity } from './shell/VenueIdentity'
|
||||
import { createI18n } from '@xenia/i18n'
|
||||
import { Spinner } from '@xenia/ui'
|
||||
import useAuthStore from './store/authStore'
|
||||
@@ -22,8 +23,6 @@ import OverviewPage from './pages/overview/OverviewPage'
|
||||
import TablesPage from './pages/orders/TablesPage'
|
||||
import OrderPage from './pages/orders/OrderPage'
|
||||
import OnlineOrdersPage from './pages/online/OnlineOrdersPage'
|
||||
import FeesPage from './pages/online/FeesPage'
|
||||
import QrCodesPage from './pages/online/QrCodesPage'
|
||||
|
||||
// CRM
|
||||
import ContactsPage from './pages/finance/ContactsPage'
|
||||
@@ -44,6 +43,7 @@ import ApprovalsPage from './pages/staff/ApprovalsPage'
|
||||
import ManagementSchedulePage from './pages/schedule/SchedulePage'
|
||||
import PrepZonesConfigPage from './pages/printing/PrepZonesPage'
|
||||
import PricingPage from './pages/pricing/PricingPage'
|
||||
import ScenesPage from './pages/scenes/ScenesPage'
|
||||
|
||||
// Inventory
|
||||
import ThrowawaysPage from './pages/inventory/ThrowawaysPage'
|
||||
@@ -58,6 +58,7 @@ import PrepZonesPage from './pages/reports/prepzones/PrepZonesReport'
|
||||
import ExpensesReportPage from './pages/reports/expenses/ExpensesReport'
|
||||
import TechnicalPage from './pages/reports/technical/TechnicalReport'
|
||||
import MiscPage from './pages/reports/misc/MiscReport'
|
||||
import MovesPage from './pages/reports/moves/MovesReport'
|
||||
|
||||
// Other
|
||||
import { AppsPage, IntegrationsPage } from './pages/platform/ModulesPage'
|
||||
@@ -111,7 +112,7 @@ function ManagerRoot() {
|
||||
return (
|
||||
<AccessProvider client={client} token={token} i18n={i18n} loading={<Loading />}>
|
||||
<AuthRehydrator>
|
||||
<Outlet />
|
||||
<VenueIdentity><Outlet /></VenueIdentity>
|
||||
</AuthRehydrator>
|
||||
</AccessProvider>
|
||||
)
|
||||
@@ -134,8 +135,8 @@ export default function App() {
|
||||
<Route path="dashboard" element={<OverviewPage />} />
|
||||
<Route path="tables" element={<TablesPage />} />
|
||||
<Route path="online-orders" element={<OnlineOrdersPage />} />
|
||||
<Route path="online/fees" element={<FeesPage />} />
|
||||
<Route path="online/qr" element={<QrCodesPage />} />
|
||||
<Route path="online/fees" element={<Navigate to="/online-orders?tab=settings" replace />} />
|
||||
<Route path="online/qr" element={<Navigate to="/tables?view=qr" replace />} />
|
||||
<Route path="orders/:orderId" element={<OrderPage />} />
|
||||
|
||||
{/* ── CRM ── */}
|
||||
@@ -157,6 +158,7 @@ export default function App() {
|
||||
<Route path="management/schedule" element={<ManagementSchedulePage />} />
|
||||
<Route path="management/prep-zones" element={<PrepZonesConfigPage />} />
|
||||
<Route path="management/pricing" element={<PricingPage />} />
|
||||
<Route path="management/scenes" element={<ScenesPage />} />
|
||||
|
||||
{/* ── Inventory ── */}
|
||||
<Route path="inventory/throwaways" element={<ThrowawaysPage />} />
|
||||
@@ -171,6 +173,7 @@ export default function App() {
|
||||
<Route path="reports/expenses" element={<ExpensesReportPage />} />
|
||||
<Route path="reports/technical" element={<TechnicalPage />} />
|
||||
<Route path="reports/misc" element={<MiscPage />} />
|
||||
<Route path="reports/moves" element={<MovesPage />} />
|
||||
|
||||
{/* ── Apps & Settings ── */}
|
||||
<Route path="apps" element={<AppsPage />} />
|
||||
|
||||
@@ -75,7 +75,7 @@ export default function UserMenuButton({ displayName, onEditProfile, onSignOut }
|
||||
</button>
|
||||
|
||||
<div className="my-1 border-t border-line" />
|
||||
<div className="flex items-center gap-2.5 px-3.5 pt-1.5 pb-1 text-[11px] font-semibold uppercase tracking-wide text-ink-3">
|
||||
<div className="flex items-center gap-2.5 px-3.5 pt-1.5 pb-1 text-overline font-semibold uppercase tracking-wide text-ink-3">
|
||||
<Languages className="h-3.5 w-3.5" />
|
||||
{t('profile.language')}
|
||||
</div>
|
||||
@@ -94,7 +94,7 @@ export default function UserMenuButton({ displayName, onEditProfile, onSignOut }
|
||||
))}
|
||||
|
||||
<div className="my-1 border-t border-line" />
|
||||
<div className="flex items-center gap-2.5 px-3.5 pt-1.5 pb-1 text-[11px] font-semibold uppercase tracking-wide text-ink-3">
|
||||
<div className="flex items-center gap-2.5 px-3.5 pt-1.5 pb-1 text-overline font-semibold uppercase tracking-wide text-ink-3">
|
||||
<Palette className="h-3.5 w-3.5" />
|
||||
{t('profile.look')}
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
// Management → Tables: the tables and their zones (the list, for typing and bulk changes), and
|
||||
// the floor plans (plan step 6.8: where the tables stand, drawn on a map).
|
||||
import { useState } from 'react'
|
||||
// the floor plans (plan step 6.8: where the tables stand, drawn on a map). On the page rule
|
||||
// (2026-11-20): the tabs above, the tab in the address (?tab=).
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Page, Tabs } from '@xenia/ui'
|
||||
import FloorPlansTab from '../floor/FloorPlansTab'
|
||||
import TablesListTab from '../tables/TablesListTab'
|
||||
|
||||
@@ -9,21 +11,14 @@ const TABS = ['list', 'floor']
|
||||
|
||||
export default function TablesConfigPage() {
|
||||
const { t } = useTranslation('manager')
|
||||
const [tab, setTab] = useState('list')
|
||||
const [params, setParams] = useSearchParams()
|
||||
const tab = TABS.includes(params.get('tab')) ? params.get('tab') : 'list'
|
||||
const setTab = v => setParams(p => { const n = new URLSearchParams(p); n.set('tab', v); return n }, { replace: true })
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
<div className="flex flex-wrap gap-1 border-b border-line px-4 md:px-6 pt-3 shrink-0" role="tablist" aria-label={t('floor.pageTabs')}>
|
||||
{TABS.map(k => (
|
||||
<button key={k} type="button" role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`tables-tab-${k}`}
|
||||
className={`px-3 py-2 -mb-px border-b-2 text-label font-medium transition-colors duration-fast
|
||||
${tab === k ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink'}`}>
|
||||
{t(`floor.tabs.${k}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
{tab === 'list' ? <TablesListTab /> : <FloorPlansTab />}
|
||||
</div>
|
||||
</div>
|
||||
<Page testId="tables-config"
|
||||
top={<Tabs size="lg" value={tab} onChange={setTab} aria-label={t('floor.pageTabs')}
|
||||
tabs={TABS.map(k => ({ id: k, label: t(`floor.tabs.${k}`), testId: `tables-tab-${k}` }))} />}>
|
||||
{tab === 'list' ? <TablesListTab /> : <FloorPlansTab />}
|
||||
</Page>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useCallback, useEffect, useState } from 'react'
|
||||
import { PhoneIncoming } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { EmptyState, Spinner } from '@xenia/ui'
|
||||
import { EmptyState, Page, Spinner } from '@xenia/ui'
|
||||
import client from '../api/client'
|
||||
import { useLiveEvent } from '../live/useLiveEvent'
|
||||
import usePhoneStore from '../store/phoneStore'
|
||||
@@ -26,7 +26,7 @@ export default function PhonePage() {
|
||||
|
||||
const hook = `${window.location.protocol}//${window.location.hostname}/api/phone/call-event?caller=\${CALLERID}&ext=\${EXTEN}`
|
||||
return (
|
||||
<div className="p-4 md:p-6 grid gap-6 max-w-3xl" data-testid="phone-page">
|
||||
<Page testId="phone-page">
|
||||
<header className="grid gap-1">
|
||||
<h1 className="text-heading font-semibold text-ink">{t('calls.title')}</h1>
|
||||
<p className="text-body text-ink-2">{t('calls.intro')}</p>
|
||||
@@ -62,6 +62,6 @@ export default function PhonePage() {
|
||||
<code className="text-label text-ink break-all bg-surface p-2 rounded-control border border-line">{hook}</code>
|
||||
<p className="text-caption text-ink-3">{t('calls.setupSecret')}</p>
|
||||
</section>
|
||||
</div>
|
||||
</Page>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import { useCan, useModule } from '@xenia/access'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button } from '@xenia/ui'
|
||||
import { Columns, Page, Tabs } from '@xenia/ui'
|
||||
import PrintingSettings from '../printing/PrintingSettings'
|
||||
import CustomerDisplaySettings from './sections/CustomerDisplaySettings'
|
||||
import DevelopmentSettings from './sections/DevelopmentSettings'
|
||||
@@ -16,12 +16,14 @@ import SecuritySettings from './sections/SecuritySettings'
|
||||
import SystemSettings from './sections/SystemSettings'
|
||||
import TableColours from './sections/TableColours'
|
||||
import VenueSettings from './sections/VenueSettings'
|
||||
import IdentitySettings from './sections/IdentitySettings'
|
||||
|
||||
const TABS = {
|
||||
'app-info': () => <SystemSettings />,
|
||||
venue: () => <div className="max-w-3xl"><VenueSettings /></div>,
|
||||
'customer-display': () => <div className="max-w-4xl"><CustomerDisplaySettings /></div>,
|
||||
'menu-tablets': () => <div className="max-w-3xl"><MenuTabletSettings /></div>,
|
||||
venue: () => <Columns><VenueSettings /></Columns>,
|
||||
identity: () => <IdentitySettings />,
|
||||
'customer-display': () => <CustomerDisplaySettings />,
|
||||
'menu-tablets': () => <Columns><MenuTabletSettings /></Columns>,
|
||||
security: () => <SecuritySettings />,
|
||||
operation: () => <OperationSettings />,
|
||||
colours: () => <TableColours />,
|
||||
@@ -47,16 +49,11 @@ export default function SettingsPage() {
|
||||
const active = tabs.includes(params.get('tab')) ? params.get('tab') : tabs[0]
|
||||
const Tab = TABS[active]
|
||||
return (
|
||||
<div className="h-full flex flex-col min-h-0" data-testid="settings-page">
|
||||
<div className="shrink-0 border-b border-line bg-surface px-4 lg:px-6 overflow-x-auto">
|
||||
<div className="flex gap-1 py-2" role="tablist" aria-label={t('settings.title')}>
|
||||
{tabs.map(id => (
|
||||
<Button key={id} size="sm" variant={active === id ? 'primary' : 'ghost'} role="tab" aria-selected={active === id}
|
||||
onClick={() => setParams({ tab: id }, { replace: true })} data-testid={`settings-tab-${id}`}>{t(`settings.tabs.${id}`)}</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto p-4 lg:p-6"><Tab /></div>
|
||||
</div>
|
||||
// full width like every page (6F.0, owner 2026-11-23); each tab's cards sit in <Columns>
|
||||
<Page testId="settings-page" aria-label={t('settings.title')}
|
||||
top={<Tabs size="lg" value={active} onChange={id => setParams({ tab: id }, { replace: true })}
|
||||
tabs={tabs.map(id => ({ id, label: t(`settings.tabs.${id}`), testId: `settings-tab-${id}` }))} />}>
|
||||
<Tab />
|
||||
</Page>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -138,6 +138,12 @@ export default function CustomerDisplaySettings() {
|
||||
<option value="light">{t('display.themes.light')}</option>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label={t('display.brand')} hint={t('display.brandHint')}>
|
||||
<Select value={form.brand || 'own'} onChange={e => set('brand', e.target.value)} data-testid="display-brand">
|
||||
<option value="own">{t('display.brands.own')}</option>
|
||||
<option value="identity">{t('display.brands.identity')}</option>
|
||||
</Select>
|
||||
</Field>
|
||||
{shows('slides') && (
|
||||
<Field label={t('display.slideSeconds')}>
|
||||
<Input inputMode="numeric" value={String(form.slide_seconds)} data-testid="display-slide-seconds"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Settings → Development (plan step 6.14a; was the v1 DevelopmentTab): for testing only. Printing
|
||||
// "spoof": every print job is dropped silently and the apps behave as if it printed.
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Spinner, Switch } from '@xenia/ui'
|
||||
import { Columns, Spinner, Switch } from '@xenia/ui'
|
||||
import { SettingRow, SettingsCard } from './SettingsCard'
|
||||
import { useSettings } from './useSettings'
|
||||
|
||||
@@ -11,13 +11,13 @@ export default function DevelopmentSettings() {
|
||||
if (s.loading) return <div className="py-8 flex justify-center"><Spinner /></div>
|
||||
const spoof = s.get('dev.spoof_printing', 'false') === 'true'
|
||||
return (
|
||||
<div className="grid gap-5 max-w-3xl" data-testid="settings-development">
|
||||
<p className="rounded-card bg-danger-soft text-danger-ink p-3 text-label" role="note">{t('settings.dev.warning')}</p>
|
||||
<Columns testId="settings-development">
|
||||
<p className="x-columns__wide rounded-card bg-danger-soft text-danger-ink p-3 text-label" role="note">{t('settings.dev.warning')}</p>
|
||||
<SettingsCard title={t('settings.dev.title')}>
|
||||
<SettingRow label={t('settings.dev.spoof')} hint={t('settings.dev.spoofHint')} warning={spoof ? t('settings.dev.spoofOn') : undefined}>
|
||||
<Switch checked={spoof} disabled={s.saving} onChange={v => s.save('dev.spoof_printing', v)} aria-label={t('settings.dev.spoof')} data-testid="setting-dev.spoof_printing" />
|
||||
</SettingRow>
|
||||
</SettingsCard>
|
||||
</div>
|
||||
</Columns>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import toast from 'react-hot-toast'
|
||||
import { CheckCircle2, Plus, Trash2, XCircle } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, Field, IconButton, Input, Select, Spinner, Switch } from '@xenia/ui'
|
||||
import { Button, Columns, Field, IconButton, Input, Select, Spinner, Switch } from '@xenia/ui'
|
||||
import client from '../../../api/client'
|
||||
import { SettingRow, SettingsCard } from './SettingsCard'
|
||||
import { cleanVatGroups, endLines, readJson } from './settingsLogic'
|
||||
@@ -21,9 +21,9 @@ export default function FiscalSettings() {
|
||||
if (s.loading) return <div className="py-8 flex justify-center"><Spinner /></div>
|
||||
const on = s.get('fiscal.enabled', 'false') === 'true'
|
||||
return (
|
||||
<div className="grid gap-5 max-w-3xl" data-testid="settings-fiscal">
|
||||
<Columns testId="settings-fiscal">
|
||||
<SettingsCard title={t('settings.fiscal.title')} description={t('settings.fiscal.intro')}>
|
||||
<SettingRow label={t('settings.fiscal.enabled')} hint={t('settings.fiscal.enabledHint')}
|
||||
<SettingRow label={t('settings.fiscal.enabled')} hint={t('settings.fiscal.enabledHint')} tip={t('settings.fiscal.enabledTip')}
|
||||
warning={on ? t('settings.fiscal.onWarning') : undefined}>
|
||||
<Switch checked={on} disabled={s.saving} onChange={v => s.save('fiscal.enabled', v)} aria-label={t('settings.fiscal.enabled')} data-testid="setting-fiscal.enabled" />
|
||||
</SettingRow>
|
||||
@@ -37,7 +37,7 @@ export default function FiscalSettings() {
|
||||
<Folders s={s} />
|
||||
<EndMessage s={s} />
|
||||
<VatGroups s={s} />
|
||||
</div>
|
||||
</Columns>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user