Compare commits

..
21 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 83551714f7 feat(signage): Slides library, widgets placed on the preview, blank slides, slide editor rework
- Slides library (Alembic 0044, /api/signage/library): slides kept with a name and a
  description, added to playlists as copies ("Add a slide" → Your slides, "Keep in Slides"),
  or shown alone as a screen's default (device config `slide`, played as "slide:<id>",
  also as a schedule's fallback). Signage → Slides: gallery + a two-pane editor.
- Widgets moved and sized by hand on the preview (WidgetCanvas: handles, snapping, arrow
  keys): position/size "custom" with a box the TV draws the same; alignment per widget.
- Blank slides (background + widgets); menu boards narrower and placed left/centre/right.
- Slide editor reworked: name | show, transition effect | seconds; sections; text look on
  one row with ready colours; one card per widget, settings on one row.
- Questions inside the page (@xenia/ui ConfirmDialog/useConfirm), Switch boxed, Segmented
  fill; the timeline's drop line; schedule lines run on weekdays or smart days, not both;
  the playlist editor stays within 1080p with a long timeline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:53:27 +02:00
bonaminandClaude Opus 5.5 60e6a16217 feat(signage,scenes): schedule lines with screens and smart days, screens' defaults, horizontal timeline, scenes
- Scenes (Alembic 0043, models/scene.py, /api/scenes, core.scenes.manage): named
  modes on or off (optionally until a time); price rules / deals get the
  condition "a scene is on"; signage lines can play only during a scene;
  turning one on tells every screen and pushes the online menu.
- Signage schedules are lines (signage_schedule_items): playlist, screens
  ([] = every screen), priority, days, smart days (1st / last day, first / last
  week, Greek public holidays or not: core/calendar_days.py, mirrored in
  @xenia/signage), hours, dates, scene. No line → the screen's default
  playlist. 0043 turns the old named schedules into lines for their screens.
- Screens: default playlist, TV shape, turn; what plays now and why.
- Manager: tabs Screens · Playlists · Schedules · Slides (placeholder) ·
  Message and weather; schedule lines with playlist / screens / priority /
  delete on one line; the playlist editor's horizontal timeline of fixed
  cards, the slide's basics beside its preview (one height), then its content;
  Management → Scenes; the scene condition in pricing.
- Tests: backend (lines, smart days, scenes, prices), player logic, e2e.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:22:47 +02:00
bonaminandClaude Opus 5.5 abab158b7c fix(manager): UI review pass 5 small fixes (fee tabs, category actions and drop line, card buttons, floor plan chips, staff buttons)
- Tabs inset: no line under the strip, the labels level with the end button.
- Products: a chosen category's actions share the width equally, toned (quiet,
  coloured on hover); the drop line shows above / below the row by the pointer's
  half and the category lands exactly there (moveIdTo); grid cards' edit and
  archive centred.
- Floor plans: the plan chips as tall as "New floor plan".
- Staff: PIN and password toned like the other row buttons; toned buttons light
  up (soft background) under the pointer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:22:46 +02:00
bonaminandClaude Opus 5.5 15413dea1b feat(products): every menu text per language, the editor's language picker, service item dialog
- Alembic 0042: a `translations` column on every choice (groups, quick options,
  extras, ingredients, preference sets and choices; sub-choices and shared
  sub-sets in their JSON); the texts typed so far become the text in their
  language (Greek letters → el, else the venue's); the product's old quick map
  moves onto the quick options. API, catalogue bundle and the cloud's quick
  option names carry them; names are checked before anything is replaced.
- Editor: a language picker beside the close button (Default = the venue's
  language, plus every menu language) drives every name and description, left
  and right; an empty language shows what is used instead as its placeholder.
  The shown name is the venue language's, else any (never mixed).
- Choices: one name field; the shared controls at one height (heart red when on,
  several / compact… chips coloured when on, delete red on hover); "+ Preference"
  at the right end of the tab strip; preference groups made inside a preference.
- Categories: the shared dropdown to add one; the category dialog per language.
- The service item switch is gone: "New service item" opens its own small dialog.
- UI: Dialog headerEnd; a toned toggle keeps its colour while pressed.
- Tests: backend (choice names, migration 0042), access, editor logic, e2e.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:21:50 +02:00
bonaminandClaude Opus 5.5 301502965c feat(manager): UI review pass 3 (fees tabs, products panes, floor editor, permissions search, pricing heads)
- Online orders → Settings: the fee tabs breathe (inset strip); a rule's buttons
  and switch centred together.
- Products: categories and list as panes that scroll on their own, headers and
  footers stay; the list sunken with white rows; the category search is the
  shared SearchInput. Product editor: "Make main" text instead of a star, the
  left tabs share the width.
- Floor editor: no "+" next to a corner; − / fit width / whole plan / +;
  "Edit the floor's shape" → "Save shape" (saves the shape and size at once);
  sizes in grid cells by half cells (steppers; typing snapped every keystroke
  before), resize handles on every unrotated table and thing, half-cell snapping.
- MediaField: the picture's name under the buttons, Remove red on hover.
- Staff permissions: a search box at the top.
- Prep zone name hint fixed. Offers & pricing: title first, then tabs; every tab
  has its head with the New button at the top right.
- Tests: floor cells, e2e (cell steppers, no + near a corner, Save shape,
  permission search, products panes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:51:17 +02:00
bonaminandClaude Opus 5.5 181b2f16b0 feat(ui): Pane and Page fit/header, inset/fill Tabs, quiet tones, dialog toolbar
- Page `fit` + `Pane`: panes scroll on their own, the page doesn't (from 768 px);
  Page `header`: the title and description above the tabs; the scrollbar's room
  is always kept, so short and long tabs are the same width.
- Tabs `inset` (a card's header: room around the end button) and `fill`.
- IconButton tone: grey at rest, the colour on hover; Button tone (ghost text
  that turns red on hover).
- Dialog / Sheet `toolbar`: stays under the title while the body scrolls.
- A Switch without a label lines up with the buttons beside it.
- DESIGN.md updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:51:16 +02:00
bonaminandClaude Opus 5.5 1053703f0d fix(backend): the license-expiring test used a fixed end date that became the past on 2026-11-20
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:29:14 +02:00
bonaminandClaude Opus 5.5 f158124aff docs(design): pass 2 components (IconButton tones, Switch info, wide dialog and drawer, PrintArea), every page on Page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:28:31 +02:00
bonaminandClaude Opus 5.5 9021373a6b feat(manager): every report on the shared controls (one toolbar height, modern dropdowns, shared tabs)
- The period: one toolbar (range / day as a Segmented, dates, quick choices, the report's own
  filters and export / print on the right), every control 44 px; the business day a searchable
  Dropdown.
- Report filters (person, category, status, waiter, table, printer) are the shared Dropdown;
  export / print buttons as tall as the rest; trends' step a Segmented.
- A report's tabs are the shared tab strip above the page; a day's and an order's sections too.
- e2e: the floor editor's edge '+' and the layout check cover products, tables set-up and the
  channel prices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:27:07 +02:00
bonaminandClaude Opus 5.5 244e93f827 feat(manager): the floor plan editor reworked; Management -> Tables on the page rule; area colours
- Floor editor: one toolbar over the map and the panels (grid on / off, grid resolution Ultra high
  ... Very low, edit the shape, Fit width / Whole plan, undo, save), panels top-aligned and sticky.
- The floor's shape: a '+' on the edge under the pointer, press to add a corner (and drag it);
  resting on a corner shows a bubble to remove it (never below 3).
- Areas: resize handles on the sides and corners, a colour (pastel, see-through; floor_items.color,
  migration 0041), the name repeated in the corner when tables cover it (live maps too).
- Labels can be clicked again after they're placed (transparent fill, not none).
- Management -> Tables: <Page> with the tabs above (?tab=), the list as a container, toolbar
  buttons one height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:17:45 +02:00
bonaminandClaude Opus 5.5 476c55abc0 feat(manager): products on the page rule, a wide product editor, alternate prices per sales point
- Products: the categories and the list as two containers side by side (the tree sticky), the
  toolbar on the shared controls (search, filters, list/grid, New all one height), archive /
  delete red in a container.
- Product editor: a wide dialog (Dialog size=wide: ~88% of a 16:9 screen, capped on ultrawides),
  the shared tab strip (no up/down scrollbar), one name and description with a language switch
  above them, unit (modern dropdown) and price on one row, 'Edit alternate prices' under Where
  it's sold (the product's own price per sales point: default / set / +- amount / +- %, rounding).
- Pricing: shared tabs in the address, a new 'Order channel prices' tab (rules per product,
  category or sales point, multi-select, the most precise wins).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:11:35 +02:00
bonaminandClaude Opus 5.5 94c10944ed feat(backend): order channel prices: a product's price per sales point, per product / category / channel
channel_prices rules (migration 0040, services/channel_prices.py): for one or more sales points,
set the price (one product), add an amount or a percentage (with rounding), for listed products,
the products of listed categories, or everything sold there. The most precise rule wins (product
> category > channel, newest on a tie); resolve_price starts from it, so tills, phones, menus and
the cloud's per-sales-point prices all follow. /api/pricing/channel-prices (CRUD) and
/product/{id} (the product editor's quick edit of its own rules, with the fallback shown).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:11:35 +02:00
bonaminandClaude Opus 5.5 f3fc3340d2 feat(manager): online ordering settings in tabs beside Test an order; expense lines and documents
- Online orders -> Settings: takeaway / delivery / any time side by side (wrapping, with room),
  the days of the week apart; fee rules, delivery areas and fee settings (the fee line) as tabs
  on the left, Test an order on the right; a rule's switch at the far right, equal padding,
  'Order price from' / 'Total items count from' in the rule editor.
- Expenses: the dialog lists what was bought (quantity, price before VAT, VAT; they make the
  total, with net / VAT / total) and keeps documents (attach a PDF or photo, open, remove;
  picked for a new expense, uploaded when it's saved); a paperclip in the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:57:58 +02:00
bonaminandClaude Opus 5.5 9297cbcd3b feat(backend): expense lines (quantity, price before VAT, VAT %) and documents (PDF / photo)
An expense can list what it bought; the lines make its total (net, VAT half up per line), are
replaced on edit ([] removes them) and the total still can't drop below what was paid. Files kept
with an expense: POST/GET/DELETE /api/expenses/{id}/documents[/{doc}], PDF / JPG / PNG / WebP /
HEIC by their bytes, at most 15 MB, under MEDIA_DIR/expenses/<id>/ (removed with the expense).
Migration 0039.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:57:58 +02:00
bonaminandClaude Opus 5.5 5915177c82 feat(manager): UI review pass 2 (first part): QR codes print alone, staff and permissions, tabs, schedule, prep zones, sessions
- Tables -> QR codes: Print all codes prints only the codes, as cards to cut out (PrintArea).
- Staff: coloured row actions (edit accent, zones blue, block orange / unblock green, delete red);
  permissions drawer wider, help tips right after the text, section titles quiet and ruled, more
  room between sections.
- Tabs: an open tab's charged / paid / owed larger, charges and payments further apart.
- Schedule: the header on PageHeader, the person / hour switch a Segmented as tall as the buttons.
- Prep zones: the dialog wider, the name explained (the internal name; staff see the one below).
- Management -> Sessions (was 'Signed in now') moved last.
- Map labels: Fit width / Whole map.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:48:59 +02:00
bonaminandClaude Opus 5.5 87cd90c8f5 feat(manager): the live map fits the width or the whole plan and remembers the view
FloorView: minus · Fit width · Whole map · plus; the zoom steps from the scale on screen; the
plan, zoom and scroll position are kept per plan on the device (localStorage) and restored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:48:51 +02:00
bonaminandClaude Opus 5.5 b77bb8bb40 feat(ui): IconButton tones, Switch info slot, wide right sheet, PrintArea / PrintSheet
- IconButton tone=danger|warning|info|success|special|accent: a pastel button (soft background,
  ink icon) for row actions that stand apart.
- Switch info: an element (InfoTip) right after the label instead of after the switch.
- Sheet size=wide: a 600 px drawer.
- PrintArea: content rendered into <body>, hidden on screen, the only thing printed while mounted;
  PrintSheet: cards to cut out (dashed cut lines, never split across pages).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:48:50 +02:00
bonaminandClaude Opus 5.5 618fef53ef perf(backend): index the lookup columns and load order lines in batches
Order lines had no index on their order, orders none on their day/customer/status, and each
line's product was loaded to tell a fee apart: with ~3000 orders Customers took ~2 s and
Reports -> Days ~15 s. Migration 0038 adds the indexes (models carry index=True), Order.items
loads with selectin, sales.lines looks the fee products up once, cancellations and prep-zones
load their orders with the lines. Days 15 s -> 0.2 s (a month), customers 2 s -> 0.1 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:42:09 +02:00
bonaminandClaude Opus 5.5 fd917797a7 docs(design): restart dev servers after a Tailwind preset change
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:28:02 +02:00
bonaminandClaude Opus 5.5 6f4ab23582 feat(manager): design pass 1 — every page on <Page>, shared toolbars, fees under Online orders, QR codes under Tables, day stats reworked
From the owner's page-by-page review (2026-11-20):
- every page root is <Page> (scrolls, fills 1080p, 16:9 centred on
  ultrawides); not yet: products, management/tables, stock (next pass)
- /dashboard: more padding in cards (p-card), quieter secondary text,
  11px uppercase labels everywhere (text-overline)
- day stats: xl dialog, "● Day running · Opened …" as text, the six
  figures in equal boxes, "On tabs" in the payments bar, shared Tabs
- /tables: Segmented List / Map / QR codes (?view=; /online/qr redirects),
  filter chips + zones multi-select at one height, the card itself opens
  the table (button removed), cards ~20% wider
- /online-orders: shared Tabs with Settings (= the old /online/fees page,
  which redirects to ?tab=settings); orders fill the width
- contacts, customers, expenses: PageHeader + Toolbar + SearchInput +
  multi-select Dropdowns (kinds; statuses, categories); table cells
  vertically centred; the Spent tip opens on hover
- filterCards / filterContacts / filterExpenses take several values
  (unit tests added)
- docs/DESIGN.md: the design language (CS-20 in the pack README)
- tests/e2e/manager_layout.mjs: the page rule at 1920x1080 and 3440x1440;
  manager.mjs and manager_look.mjs follow the moved pages

Verified: manager build + lint (0 errors), unit tests (manager 99, ui 24,
i18n 31, api 25, access 8), i18n guard, manager_layout.mjs all passed,
manager.mjs 228 checks all passed. Not checked: the waiter app and the
terminal by eye (they only get the muted ink-2 token).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:23:30 +02:00
bonaminandClaude Opus 5.5 26ba19cba5 feat(ui): the shared page frame and toolbar kit: Page, PageHeader, Toolbar, Dropdown (multi-select), SearchInput, FilterChip, Segmented, Tabs
Owner's UI review (2026-11-20): pages that don't scroll and sit on the left,
native selects in toolbars, controls of different heights, labels too loud.
Everything is global in @xenia/ui so no page rebuilds it:
- Page: scrolls on its own, fills the area up to a 16:9 screen's width
  (--x-page-max = max(1280px, 100vh*16/9)), centred beyond (ultrawides);
  width="form" for settings; top= keeps a tab strip above the scroll
- Dropdown: portal list, flips above, keyboard, search for long lists,
  multiple (array value, [] = all, allLabel), dots and hints; Input heights
- SearchInput, FilterChip (tone + count), Segmented, Tabs (sideways scroll
  only, no 1px up/down scroll), Toolbar/ToolbarSpacer
- InfoTip opens on hover too; Dialog size xl (920px)
- tokens: --x-text-overline (11px), --x-pad-card(-y), muted ink-2 (contrast
  test still passes in every look); preset: text-overline, p-card,
  max-w-page, the special tone
- component labels (search, clear, all, nothing found) in en/el

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:23:29 +02:00
222 changed files with 8024 additions and 2097 deletions
+94
View File
@@ -0,0 +1,94 @@
# 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 the width of a 16:9 screen (`--x-page-max` = `max(1280px, 100vh × 16/9)`). On a 1080p monitor the page fills the screen; on an ultrawide it stays 16:9 wide and is **centred**,
- **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=`).
- `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.
- `width="form"` for settings and forms (centred at `--x-page-form-max`, 880 px). Lists, tables and dashboards use the default (full).
- **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 |
| 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 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 |
| A switch in a row of fields | `Switch boxed` | framed and as tall as an input: text left, switch right |
| 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.
+4
View File
@@ -71,6 +71,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `package.json`, `package-lock.json`, `packages/` | **npm workspace** for the frontends (D-15): `waiter_pwa`, `manager_dashboard`, `terminal` and the shared `packages/{ui,i18n,api,access}` (imported from source, no build step). One lockfile at this root; the apps have none of their own. | | `package.json`, `package-lock.json`, `packages/` | **npm workspace** for the frontends (D-15): `waiter_pwa`, `manager_dashboard`, `terminal` and the shared `packages/{ui,i18n,api,access}` (imported from source, no build step). One lockfile at this root; the apps have none of their own. |
| `terminal/` | The terminal app (phase 3): `src/device/DeviceProvider.jsx` (the device's `/me`, who is signed in, the live connection with credentials in the first frame, offline; apps listen with `useLiveEvent`), `src/device/flow.js` (which screen shows when: pairing → sign-in → app / blocked; pure, unit-tested), `src/screens/` (pairing, sign-in per mode, blocked, app + bar), `src/apps/registry.js` (which apps a screen runs, lazy chunks), `src/device/storage.js` (device + session tokens), `src/api/client.js` (`X-Xenia-Device` on every request; 401 / unreachable listeners). The screen follows the device, not the URL. Lint covers all of `src` | | `terminal/` | The terminal app (phase 3): `src/device/DeviceProvider.jsx` (the device's `/me`, who is signed in, the live connection with credentials in the first frame, offline; apps listen with `useLiveEvent`), `src/device/flow.js` (which screen shows when: pairing → sign-in → app / blocked; pure, unit-tested), `src/screens/` (pairing, sign-in per mode, blocked, app + bar), `src/apps/registry.js` (which apps a screen runs, lazy chunks), `src/device/storage.js` (device + session tokens), `src/api/client.js` (`X-Xenia-Device` on every request; 401 / unreachable listeners). The screen follows the device, not the URL. Lint covers all of `src` |
| `packages/ui/` | Shared design tokens, Tailwind preset and base components (CS-16). Visual check: `npm run dev:manager` → `/ui-gallery` | | `packages/ui/` | Shared design tokens, Tailwind preset and base components (CS-16). Visual check: `npm run dev:manager` → `/ui-gallery` |
| `docs/DESIGN.md` | **The design language** (2026-11-20): the page rule (`<Page>`: own scroll, fills 1080p, 16:9 and centred on ultrawides), toolbars, the one `Dropdown` (multi-select), tabs, type/spacing tokens, tables. Read before any UI work (CS-20) |
| `packages/api/` | Shared HTTP client (`createApiClient`: session/device headers, `err.xenia` codes, the manager-approval retry) and the live WebSocket client with cursor replay (`createLiveClient`, used by the waiter's `useWebSocket`) (CS-18) | | `packages/api/` | Shared HTTP client (`createApiClient`: session/device headers, `err.xenia` codes, the manager-approval retry) and the live WebSocket client with cursor replay (`createLiveClient`, used by the waiter's `useWebSocket`) (CS-18) |
| `packages/signage/` | `@xenia/signage` (5.6a): signage slides as the TVs draw them (`SlideView`, `TextSlide`, `MenuSlide`, `Widgets`) and the player's pure logic (schedule pick, slide windows, menu pages; tests in `tests/`), shared by the terminal's player and the manager's previews. Sizes are container units (`cqmin`): a slide needs a parent with `container-type: size` (`frameStyle()`; the manager's `SlidePreview` lays it out at 1920 × 1080 and scales it down, so previews match a TV). Both apps' Tailwind `content` include it | | `packages/signage/` | `@xenia/signage` (5.6a): signage slides as the TVs draw them (`SlideView`, `TextSlide`, `MenuSlide`, `Widgets`) and the player's pure logic (schedule pick, slide windows, menu pages; tests in `tests/`), shared by the terminal's player and the manager's previews. Sizes are container units (`cqmin`): a slide needs a parent with `container-type: size` (`frameStyle()`; the manager's `SlidePreview` lays it out at 1920 × 1080 and scales it down, so previews match a TV). Both apps' Tailwind `content` include it |
| `packages/access/` | `<AccessProvider>` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, `<Can>`, `<RequireModule>` (CS-18); the fixed lists every app shares with the backend: sales points (`salesPoints.js` = `core/sales_points.py`) the 14 EU allergens (`allergens.js` = `core/allergens.py`, 6.3) and the menu's languages (`menuLanguages.js` = `core/menu_languages.py`, 6.4: el + en; a product's own name is its base text, translations in `products.translations` / `categories.translations` are for customer screens only; tests compare the lists), and `<Allergens>` (a product's allergens, the same in every app). Plain-JS subpaths `@xenia/access/salesPoints`, `/allergens` for Node tests | | `packages/access/` | `<AccessProvider>` (bootstrap → modules, permission keys, venue, language; mounts the approval dialog), `useCan`, `useModule`, `<Can>`, `<RequireModule>` (CS-18); the fixed lists every app shares with the backend: sales points (`salesPoints.js` = `core/sales_points.py`) the 14 EU allergens (`allergens.js` = `core/allergens.py`, 6.3) and the menu's languages (`menuLanguages.js` = `core/menu_languages.py`, 6.4: el + en; a product's own name is its base text, translations in `products.translations` / `categories.translations` are for customer screens only; tests compare the lists), and `<Allergens>` (a product's allergens, the same in every app). Plain-JS subpaths `@xenia/access/salesPoints`, `/allergens` for Node tests |
@@ -198,6 +199,9 @@ Manager override (D-10, `core/access/override.py`): mark a key `Perm(..., overri
**CS-16. Shared UI lives in `packages/ui` and never restyles an app** (branch `platform-v2`, D-15, §9). **CS-16. Shared UI lives in `packages/ui` and never restyles an app** (branch `platform-v2`, D-15, §9).
Design tokens are CSS variables prefixed `--x-` (`packages/ui/src/tokens.css`), components use `.x-*` classes (`src/components.css`); neither file has element selectors, resets or anything that applies outside `.x-*` (the waiter keeps its own `--bg`/`--text`…; the manager's Tailwind classes keep their meaning). The look comes from attributes on `<html>` set by `applyLook` (`packages/ui/src/theme.js`, 6.15): `data-theme` (always `light`/`dark`; "system" is resolved and followed in JS), `data-palette` (the colours: `default`, `nord`…) and `data-style` (the components' shape: `rounded`, `sharp`…), plus `data-venue-theme` (the venue's accent on the staff apps). **A new palette or style is a token block** in `tokens.css` (sections "Palettes" / "Styles") plus its name in `PALETTES` / `STYLES` and its label; components never hard-code a radius, border width or colour, so they follow it. Tailwind apps use `@xenia/ui/tailwind-preset` (adds `bg-surface`, `text-ink-2`, `rounded-control`… only). A colour change must pass `npm test -w @xenia/ui` (WCAG AA for every pair the components use, every venue theme, light and dark). Components take their visible text as props with English defaults until `@xenia/i18n` (2.4). New components get a section in `packages/ui/gallery/Gallery.jsx` (dev-only `/ui-gallery` in the manager) and checks in `tests/e2e/ui.mjs`. **Board screens** (the kitchen display, and any later screen in the same style) use the board design language: `--x-board-*` tokens in the same file (Tailwind `bg-board-bg`, `text-board-ink-2`…; always dark, contrast-tested too) for the board itself, and the normal components in `data-theme="dark"` for their dialogs, toasts and forms (the terminal sets an app's theme from `apps/registry.js` `APP_THEMES`). No hard-coded colours in app code: a colour that isn't a token yet becomes one (values the user stores, like a KDS screen's age colours, are data, not styling). Design tokens are CSS variables prefixed `--x-` (`packages/ui/src/tokens.css`), components use `.x-*` classes (`src/components.css`); neither file has element selectors, resets or anything that applies outside `.x-*` (the waiter keeps its own `--bg`/`--text`…; the manager's Tailwind classes keep their meaning). The look comes from attributes on `<html>` set by `applyLook` (`packages/ui/src/theme.js`, 6.15): `data-theme` (always `light`/`dark`; "system" is resolved and followed in JS), `data-palette` (the colours: `default`, `nord`…) and `data-style` (the components' shape: `rounded`, `sharp`…), plus `data-venue-theme` (the venue's accent on the staff apps). **A new palette or style is a token block** in `tokens.css` (sections "Palettes" / "Styles") plus its name in `PALETTES` / `STYLES` and its label; components never hard-code a radius, border width or colour, so they follow it. Tailwind apps use `@xenia/ui/tailwind-preset` (adds `bg-surface`, `text-ink-2`, `rounded-control`… only). A colour change must pass `npm test -w @xenia/ui` (WCAG AA for every pair the components use, every venue theme, light and dark). Components take their visible text as props with English defaults until `@xenia/i18n` (2.4). New components get a section in `packages/ui/gallery/Gallery.jsx` (dev-only `/ui-gallery` in the manager) and checks in `tests/e2e/ui.mjs`. **Board screens** (the kitchen display, and any later screen in the same style) use the board design language: `--x-board-*` tokens in the same file (Tailwind `bg-board-bg`, `text-board-ink-2`…; always dark, contrast-tested too) for the board itself, and the normal components in `data-theme="dark"` for their dialogs, toasts and forms (the terminal sets an app's theme from `apps/registry.js` `APP_THEMES`). No hard-coded colours in app code: a colour that isn't a token yet becomes one (values the user stores, like a KDS screen's age colours, are data, not styling).
**CS-20. Every screen follows [DESIGN.md](DESIGN.md)** (2026-11-20).
Pages are `<Page>` (never their own padding / width / scrolling), filters sit in a `<Toolbar>` with one control height, choices are `Dropdown` (never a native select in a toolbar), sections are `Tabs`. Anything a second page needs goes into `@xenia/ui` first. `tests/e2e/manager_layout.mjs` checks the page rule at 1080p and ultrawide.
**CS-17. Frontend text is a key; dates are venue time** (branch `platform-v2`, D-11, D-12, §7.2, §8). **CS-17. Frontend text is a key; dates are venue time** (branch `platform-v2`, D-11, D-12, §7.2, §8).
New UI text goes into `packages/i18n/locales/en/<ns>.json` first, then `el` (same keys, same `{{placeholders}}`), and is shown with `t()` from `@xenia/i18n` (`useTranslation`, re-exported). Dates and times are shown only through `useFormat()` (`formatTime`, `formatDateTime`, `formatDate`, `formatRelative`), which use the venue zone from bootstrap; money with `formatMoney`, numbers with `formatNumber`; typed numbers are read with `parseNumber` (comma or dot). Business dates (`YYYY-MM-DD`) go to `formatDate` as they are. `npm test -w @xenia/i18n` runs `scripts/check-i18n.mjs`, which fails on keys missing in English, placeholder mismatches, and `toLocale…String()` / `new Intl.DateTimeFormat(` without `timeZone` in new code (`packages/*`, `terminal/`); it warns for missing Greek. Module names, their limits and **every permission key** have texts in `modules.json` (`modules:<module>.name`, `.limits.<key>`, `.permissions.<rest of the key, nested by its dots>`); `tests/test_module_texts.py` fails for a new module or key without them in both languages. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `<UiLabelsProvider labels={useUiLabels()}>` at the app root. New UI text goes into `packages/i18n/locales/en/<ns>.json` first, then `el` (same keys, same `{{placeholders}}`), and is shown with `t()` from `@xenia/i18n` (`useTranslation`, re-exported). Dates and times are shown only through `useFormat()` (`formatTime`, `formatDateTime`, `formatDate`, `formatRelative`), which use the venue zone from bootstrap; money with `formatMoney`, numbers with `formatNumber`; typed numbers are read with `parseNumber` (comma or dot). Business dates (`YYYY-MM-DD`) go to `formatDate` as they are. `npm test -w @xenia/i18n` runs `scripts/check-i18n.mjs`, which fails on keys missing in English, placeholder mismatches, and `toLocale…String()` / `new Intl.DateTimeFormat(` without `timeZone` in new code (`packages/*`, `terminal/`); it warns for missing Greek. Module names, their limits and **every permission key** have texts in `modules.json` (`modules:<module>.name`, `.limits.<key>`, `.permissions.<rest of the key, nested by its dots>`); `tests/test_module_texts.py` fails for a new module or key without them in both languages. The v1 apps' Greek strings convert in phases 4 and 6. The `@xenia/ui` components get their texts from `<UiLabelsProvider labels={useUiLabels()}>` at the app root.
+53
View File
@@ -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)
+9
View File
@@ -198,6 +198,15 @@ CODES: dict[str, tuple[int, str]] = {
"expense.not_found": (404, "Expense not found."), "expense.not_found": (404, "Expense not found."),
"expense.over_due": (400, "That's more than what is still due ({due})."), "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.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.not_found": (404, "Mark not found."),
"flag.in_use": (409, "This mark is on {count} table(s). Remove it there first."), "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."), "flag.invalid_ids": (400, "Some of these marks don't exist."),
+48 -3
View File
@@ -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 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 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} return {lang: (translations.get(lang) or {}).get(field) or base for lang in MENU_LANGUAGES}
def quick_texts(base: str, translations: dict) -> dict: def quick_texts(base: str, translations: dict, own: dict | None = None) -> dict:
return {lang: ((translations.get(lang) or {}).get("quick") or {}).get(base) or base for lang in MENU_LANGUAGES} """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: 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 name = (product.digital_name if customer else None) or product.name
desc = (product.digital_description if customer else None) or product.description desc = (product.digital_description if customer else None) or product.description
return {"names": texts(name, tr, "name"), "descriptions": texts(desc or None, tr, "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}
+3 -3
View File
@@ -55,13 +55,13 @@ def _ref_exists(source: str, value: int, db) -> bool:
if source == "signage_playlists": if source == "signage_playlists":
from models.signage import SignagePlaylist from models.signage import SignagePlaylist
return db.get(SignagePlaylist, value) is not None 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": if source == "tables":
from models.table import Table from models.table import Table
t = db.get(Table, value) t = db.get(Table, value)
return t is not None and bool(t.is_active) 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": if source == "display_looks":
from models.display_look import DisplayLook from models.display_look import DisplayLook
return db.get(DisplayLook, value) is not None 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')
+2 -1
View File
@@ -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.refund # noqa: F401 Refund, RefundItem (step 3.3e)
import models.media # noqa: F401 Media (media library, step 5.1) 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.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.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) import models.floor_plan # noqa: F401 FloorPlan, FloorItem (the table map, step 6.8)
+3 -3
View File
@@ -32,8 +32,8 @@ class ConversationParticipant(Base):
__tablename__ = "conversation_participants" __tablename__ = "conversation_participants"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False) conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False) user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
joined_at = Column(UTCDateTime, default=utcnow) joined_at = Column(UTCDateTime, default=utcnow)
last_read_at = Column(UTCDateTime, nullable=True) last_read_at = Column(UTCDateTime, nullable=True)
@@ -45,7 +45,7 @@ class ChatMessage(Base):
__tablename__ = "chat_messages" __tablename__ = "chat_messages"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False) conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False, index=True)
sender_id = Column(Integer, ForeignKey("users.id"), nullable=False) sender_id = Column(Integer, ForeignKey("users.id"), nullable=False)
body = Column(Text, nullable=False) body = Column(Text, nullable=False)
sent_at = Column(UTCDateTime, default=utcnow) sent_at = Column(UTCDateTime, default=utcnow)
+42 -3
View File
@@ -28,11 +28,11 @@ class Expense(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
description = Column(String, nullable=False) description = Column(String, nullable=False)
category = Column(String, nullable=False) # supplier|utilities|rent|maintenance|staff|equipment|other category = Column(String, nullable=False) # supplier|utilities|rent|maintenance|staff|equipment|other
contact_id = Column(Integer, ForeignKey("contacts.id"), nullable=True) contact_id = Column(Integer, ForeignKey("contacts.id"), nullable=True, index=True)
total_amount = Column(Float, nullable=False) total_amount = Column(Float, nullable=False)
paid_amount = Column(Float, default=0.0, nullable=False) paid_amount = Column(Float, default=0.0, nullable=False)
due_date = Column(UTCDateTime, nullable=True) due_date = Column(UTCDateTime, nullable=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True) business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
created_at = Column(UTCDateTime, default=utcnow) created_at = Column(UTCDateTime, default=utcnow)
notes = Column(Text, nullable=True) notes = Column(Text, nullable=True)
@@ -40,13 +40,18 @@ class Expense(Base):
contact = relationship("Contact", back_populates="expenses") contact = relationship("Contact", back_populates="expenses")
created_by = relationship("User", foreign_keys=[created_by_id]) created_by = relationship("User", foreign_keys=[created_by_id])
payments = relationship("ExpensePayment", back_populates="expense", cascade="all, delete-orphan") payments = relationship("ExpensePayment", back_populates="expense", cascade="all, delete-orphan")
# what was bought (2026-11-20): when an expense has lines, its total is theirs
lines = relationship("ExpenseLine", back_populates="expense", cascade="all, delete-orphan",
order_by="ExpenseLine.position")
documents = relationship("ExpenseDocument", back_populates="expense", cascade="all, delete-orphan",
order_by="ExpenseDocument.id")
class ExpensePayment(Base): class ExpensePayment(Base):
__tablename__ = "expense_payments" __tablename__ = "expense_payments"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False) expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False, index=True)
amount = Column(Float, nullable=False) amount = Column(Float, nullable=False)
paid_at = Column(UTCDateTime, default=utcnow) paid_at = Column(UTCDateTime, default=utcnow)
paid_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) paid_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
@@ -54,3 +59,37 @@ class ExpensePayment(Base):
expense = relationship("Expense", back_populates="payments") expense = relationship("Expense", back_populates="payments")
paid_by = relationship("User", foreign_keys=[paid_by_id]) paid_by = relationship("User", foreign_keys=[paid_by_id])
class ExpenseLine(Base):
"""A line of an expense (2026-11-20): what was bought, how many, the price of one before VAT
and its VAT rate. Line total = quantity × unit price × (1 + VAT %)."""
__tablename__ = "expense_lines"
id = Column(Integer, primary_key=True, index=True)
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False, index=True)
position = Column(Integer, default=0, nullable=False)
description = Column(String, nullable=False)
quantity = Column(Float, default=1.0, nullable=False)
unit_price = Column(Float, nullable=False) # one, before VAT
vat_rate = Column(Float, default=0.0, nullable=False) # %, e.g. 24
expense = relationship("Expense", back_populates="lines")
class ExpenseDocument(Base):
"""A file kept with an expense (2026-11-20): the invoice as a PDF or a photo of the receipt.
Stored under MEDIA_DIR/expenses/<expense id>/ (services/expense_docs.py)."""
__tablename__ = "expense_documents"
id = Column(Integer, primary_key=True, index=True)
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False, index=True)
filename = Column(String, nullable=False) # as uploaded
stored_name = Column(String, nullable=False) # on disk
content_type = Column(String, nullable=False)
size = Column(Integer, nullable=False)
uploaded_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
uploaded_at = Column(UTCDateTime, default=utcnow)
expense = relationship("Expense", back_populates="documents")
uploaded_by = relationship("User", foreign_keys=[uploaded_by_id])
+1
View File
@@ -54,5 +54,6 @@ class FloorItem(Base):
height = Column(Float, nullable=False) height = Column(Float, nullable=False)
rotation = Column(Float, nullable=False, default=0.0) rotation = Column(Float, nullable=False, default=0.0)
text = Column(String, nullable=True) 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") plan = relationship("FloorPlan", back_populates="items")
+1 -1
View File
@@ -42,7 +42,7 @@ class StaffMessageAck(Base):
__tablename__ = "staff_message_acks" __tablename__ = "staff_message_acks"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
message_id = Column(Integer, ForeignKey("staff_messages.id"), nullable=False) message_id = Column(Integer, ForeignKey("staff_messages.id"), nullable=False, index=True)
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False) waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
acked_at = Column(UTCDateTime, default=utcnow) acked_at = Column(UTCDateTime, default=utcnow)
+21 -17
View File
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Text from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Index, Text
from core.timeutil import UTCDateTime, utcnow from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
from database import Base from database import Base
@@ -8,16 +8,18 @@ from database import Base
class Order(Base): class Order(Base):
__tablename__ = "orders" __tablename__ = "orders"
# who opened what when (a shift's orders: migration 0038)
__table_args__ = (Index("ix_orders_opened_by_opened_at", "opened_by", "opened_at"),)
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True) # nullable for online orders table_id = Column(Integer, ForeignKey("tables.id"), nullable=True, index=True) # nullable for online orders
opened_by = Column(Integer, ForeignKey("users.id"), nullable=False) opened_by = Column(Integer, ForeignKey("users.id"), nullable=False)
opened_at = Column(UTCDateTime, default=utcnow) opened_at = Column(UTCDateTime, default=utcnow, index=True)
status = Column(String, default="open", nullable=False) # open|partially_paid|paid|closed|cancelled status = Column(String, default="open", nullable=False, index=True) # open|partially_paid|paid|closed|cancelled
closed_at = Column(UTCDateTime, nullable=True) closed_at = Column(UTCDateTime, nullable=True)
closed_by = Column(Integer, ForeignKey("users.id"), nullable=True) closed_by = Column(Integer, ForeignKey("users.id"), nullable=True)
notes = Column(Text, nullable=True) notes = Column(Text, nullable=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True) business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
# KDS # KDS
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done
kds_status_changed_at = Column(UTCDateTime, nullable=True) kds_status_changed_at = Column(UTCDateTime, nullable=True)
@@ -41,7 +43,7 @@ class Order(Base):
# when the customer wants it (S.5); NULL = as soon as possible # when the customer wants it (S.5); NULL = as soon as possible
requested_for = Column(UTCDateTime, nullable=True) requested_for = Column(UTCDateTime, nullable=True)
# Phase 2F — customer CRM # Phase 2F — customer CRM
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=True) customer_id = Column(Integer, ForeignKey("customers.id"), nullable=True, index=True)
# Number of customers at the table for this order # Number of customers at the table for this order
customer_count = Column(Integer, nullable=True) customer_count = Column(Integer, nullable=True)
@@ -53,7 +55,7 @@ class Order(Base):
opener = relationship("User", foreign_keys=[opened_by], back_populates="orders_opened") opener = relationship("User", foreign_keys=[opened_by], back_populates="orders_opened")
closer = relationship("User", foreign_keys=[closed_by], back_populates="orders_closed") closer = relationship("User", foreign_keys=[closed_by], back_populates="orders_closed")
customer = relationship("Customer", back_populates="orders", foreign_keys=[customer_id]) customer = relationship("Customer", back_populates="orders", foreign_keys=[customer_id])
items = relationship("OrderItem", back_populates="order", cascade="all, delete-orphan") items = relationship("OrderItem", back_populates="order", cascade="all, delete-orphan", lazy="selectin")
waiters = relationship("OrderWaiter", back_populates="order", cascade="all, delete-orphan") waiters = relationship("OrderWaiter", back_populates="order", cascade="all, delete-orphan")
print_logs = relationship("PrintLog", back_populates="order", cascade="all, delete-orphan") print_logs = relationship("PrintLog", back_populates="order", cascade="all, delete-orphan")
print_jobs = relationship("PrintJob", back_populates="order", cascade="all, delete-orphan") print_jobs = relationship("PrintJob", back_populates="order", cascade="all, delete-orphan")
@@ -65,8 +67,8 @@ class OrderWaiter(Base):
__tablename__ = "order_waiters" __tablename__ = "order_waiters"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False) waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
assigned_at = Column(UTCDateTime, default=utcnow) assigned_at = Column(UTCDateTime, default=utcnow)
order = relationship("Order", back_populates="waiters") order = relationship("Order", back_populates="waiters")
@@ -75,10 +77,12 @@ class OrderWaiter(Base):
class OrderItem(Base): class OrderItem(Base):
__tablename__ = "order_items" __tablename__ = "order_items"
# what someone added when (a shift's lines, cancellations: migration 0038)
__table_args__ = (Index("ix_order_items_added_by_added_at", "added_by", "added_at"),)
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
added_by = Column(Integer, ForeignKey("users.id"), nullable=False) added_by = Column(Integer, ForeignKey("users.id"), nullable=False)
quantity = Column(Float, nullable=False) quantity = Column(Float, nullable=False)
unit_price = Column(Float, nullable=False) # price snapshot at time of order unit_price = Column(Float, nullable=False) # price snapshot at time of order
@@ -92,7 +96,7 @@ class OrderItem(Base):
selected_options = Column(Text, nullable=True) # JSON array of option ids selected_options = Column(Text, nullable=True) # JSON array of option ids
removed_ingredients = Column(Text, nullable=True) # JSON array of ingredient ids removed_ingredients = Column(Text, nullable=True) # JSON array of ingredient ids
notes = Column(Text, nullable=True) notes = Column(Text, nullable=True)
status = Column(String, default="active", nullable=False) # active|paid|cancelled status = Column(String, default="active", nullable=False, index=True) # active|paid|cancelled
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done|served|declined kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done|served|declined
added_at = Column(UTCDateTime, default=utcnow) added_at = Column(UTCDateTime, default=utcnow)
printed = Column(Boolean, default=False, nullable=False) printed = Column(Boolean, default=False, nullable=False)
@@ -101,7 +105,7 @@ class OrderItem(Base):
paid_by = Column(Integer, ForeignKey("users.id"), nullable=True) paid_by = Column(Integer, ForeignKey("users.id"), nullable=True)
paid_at = Column(UTCDateTime, nullable=True) paid_at = Column(UTCDateTime, nullable=True)
payment_method = Column(String, nullable=True) # 'cash'|'card'|'other' — future use payment_method = Column(String, nullable=True) # 'cash'|'card'|'other' — future use
paid_in_shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True) paid_in_shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True, index=True)
# Phase 2A — cost snapshot (copied from product at time of order, never updated) # Phase 2A — cost snapshot (copied from product at time of order, never updated)
unit_cost = Column(Float, nullable=True) unit_cost = Column(Float, nullable=True)
@@ -150,7 +154,7 @@ class PrintLog(Base):
__tablename__ = "print_log" __tablename__ = "print_log"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False) printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False)
printed_at = Column(UTCDateTime, default=utcnow) printed_at = Column(UTCDateTime, default=utcnow)
item_ids = Column(Text, nullable=False) # JSON array of order_item ids item_ids = Column(Text, nullable=False) # JSON array of order_item ids
@@ -169,7 +173,7 @@ class PrintJob(Base):
__tablename__ = "print_jobs" __tablename__ = "print_jobs"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False) printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False)
zone_id = Column(Integer, nullable=True) # prep zone id, NULL for legacy zone_id = Column(Integer, nullable=True) # prep zone id, NULL for legacy
item_ids = Column(Text, nullable=False) # JSON array of order_item ids item_ids = Column(Text, nullable=False) # JSON array of order_item ids
@@ -194,7 +198,7 @@ class OrderAuditLog(Base):
__tablename__ = "order_audit_log" __tablename__ = "order_audit_log"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
event_type = Column(String, nullable=False) event_type = Column(String, nullable=False)
# ORDER_OPENED | ITEMS_ADDED | PAYMENT | PAYMENT_OFFLINE | ORDER_CLOSED | ORDER_CANCELLED | ITEM_CANCELLED # ORDER_OPENED | ITEMS_ADDED | PAYMENT | PAYMENT_OFFLINE | ORDER_CLOSED | ORDER_CANCELLED | ITEM_CANCELLED
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=True) waiter_id = Column(Integer, ForeignKey("users.id"), nullable=True)
@@ -221,7 +225,7 @@ class OrderDiscount(Base):
__tablename__ = "order_discounts" __tablename__ = "order_discounts"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) # NULL = whole-order discount item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) # NULL = whole-order discount
discount_type = Column(String, nullable=False) # 'percent' | 'fixed' discount_type = Column(String, nullable=False) # 'percent' | 'fixed'
discount_value = Column(Float, nullable=False) # e.g. 10.0 = 10% or €10.00 discount_value = Column(Float, nullable=False) # e.g. 10.0 = 10% or €10.00
+1 -1
View File
@@ -12,4 +12,4 @@ class PhoneCall(Base):
at = Column(UTCDateTime, default=utcnow, nullable=False, index=True) at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
number = Column(String, nullable=False) # as the phone system sent it number = Column(String, nullable=False) # as the phone system sent it
ext = Column(String, nullable=True) # the extension that was dialled 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)
+25 -4
View File
@@ -91,6 +91,7 @@ class PriceModifierCondition(Base):
min_order_value {"min": 0.00} (cart total before modifiers) min_order_value {"min": 0.00} (cart total before modifiers)
order_channel {"channels": [sales point, ...]} (core/sales_points.py; phase 3S) order_channel {"channels": [sales point, ...]} (core/sales_points.py; phase 3S)
price_group_active {"price_group_id": N} price_group_active {"price_group_id": N}
scene_active {"scene_id": N} (a scene is on: services/scenes.py, 2026-11-21)
user_tier {"tiers": ["bronze","silver","gold"]} (placeholder, needs user accounts) user_tier {"tiers": ["bronze","silver","gold"]} (placeholder, needs user accounts)
low_stock {"threshold": N} (placeholder, needs inventory) low_stock {"threshold": N} (placeholder, needs inventory)
""" """
@@ -98,7 +99,7 @@ class PriceModifierCondition(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"), modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"),
nullable=False) nullable=False, index=True)
condition_type = Column(String, nullable=False) condition_type = Column(String, nullable=False)
params = Column(Text, nullable=False, default="{}") # JSON params = Column(Text, nullable=False, default="{}") # JSON
@@ -120,7 +121,7 @@ class PriceModifierTarget(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"), modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"),
nullable=False) nullable=False, index=True)
target_type = Column(String, nullable=False) # 'all'|'item'|'category'|'prep_zone'|'tag' target_type = Column(String, nullable=False) # 'all'|'item'|'category'|'prep_zone'|'tag'
target_id = Column(Integer, nullable=True) # legacy single value target_id = Column(Integer, nullable=True) # legacy single value
target_tag = Column(String, nullable=True) # legacy single value target_tag = Column(String, nullable=True) # legacy single value
@@ -180,7 +181,7 @@ class DealCondition(Base):
__tablename__ = "deal_conditions" __tablename__ = "deal_conditions"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False) deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False, index=True)
condition_type = Column(String, nullable=False) condition_type = Column(String, nullable=False)
params = Column(Text, nullable=False, default="{}") # JSON params = Column(Text, nullable=False, default="{}") # JSON
@@ -195,7 +196,7 @@ class DealTarget(Base):
__tablename__ = "deal_targets" __tablename__ = "deal_targets"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False) deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False, index=True)
target_type = Column(String, nullable=False) # 'item'|'category'|'tag'|'any' target_type = Column(String, nullable=False) # 'item'|'category'|'tag'|'any'
target_id = Column(Integer, nullable=True) # legacy single value target_id = Column(Integer, nullable=True) # legacy single value
target_tag = Column(String, nullable=True) # legacy single value target_tag = Column(String, nullable=True) # legacy single value
@@ -280,3 +281,23 @@ class WaiterDiscountSettings(Base):
max_items_per_order = Column(Integer, nullable=True) max_items_per_order = Column(Integer, nullable=True)
user = relationship("User", foreign_keys=[user_id]) user = relationship("User", foreign_keys=[user_id])
class ChannelPrice(Base):
"""A price at one or more sales points (2026-11-20, services/channel_prices.py): for listed
products, the products of listed categories, or (neither) everything sold there. The most
precise rule wins: product > category > channel."""
__tablename__ = "channel_prices"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=True)
sales_points = Column(Text, nullable=False, default="[]") # JSON ["online_delivery", …]
product_ids = Column(Text, nullable=False, default="[]") # JSON [int]
category_ids = Column(Text, nullable=False, default="[]") # JSON [int]
action_type = Column(String, nullable=False) # 'set' | 'add_amount' | 'add_percent'
value = Column(Float, nullable=False)
round_to = Column(String, nullable=True) # as PriceModifier.round_to
is_active = Column(Boolean, nullable=False, default=True)
created_at = Column(UTCDateTime, default=utcnow)
updated_at = Column(UTCDateTime, nullable=True)
updated_by = Column(Integer, ForeignKey("users.id"), nullable=True)
+18 -6
View File
@@ -135,11 +135,13 @@ class ProductModifierGroup(Base):
__tablename__ = "product_modifier_groups" __tablename__ = "product_modifier_groups"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
# "option" | "ingredient" | "preference" # "option" | "ingredient" | "preference"
modifier_type = Column(String, nullable=False) modifier_type = Column(String, nullable=False)
name = Column(String, nullable=False) name = Column(String, nullable=False)
sort_order = Column(Integer, default=0, nullable=False) sort_order = Column(Integer, default=0, nullable=False)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
product = relationship("Product", back_populates="modifier_groups") product = relationship("Product", back_populates="modifier_groups")
@@ -148,7 +150,7 @@ class ProductOption(Base):
__tablename__ = "product_options" __tablename__ = "product_options"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
extra_cost = Column(Float, default=0.0) extra_cost = Column(Float, default=0.0)
allow_multiple = Column(Boolean, default=False, nullable=False) allow_multiple = Column(Boolean, default=False, nullable=False)
@@ -162,6 +164,8 @@ class ProductOption(Base):
is_compact = Column(Boolean, default=False, nullable=False) is_compact = Column(Boolean, default=False, nullable=False)
# Optional group/folder this option belongs to # Optional group/folder this option belongs to
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True) group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
product = relationship("Product", back_populates="options") product = relationship("Product", back_populates="options")
@@ -170,7 +174,7 @@ class ProductQuickOption(Base):
__tablename__ = "product_quick_options" __tablename__ = "product_quick_options"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
price = Column(Float, default=0.0, nullable=False) price = Column(Float, default=0.0, nullable=False)
allow_multiple = Column(Boolean, default=False, nullable=False) allow_multiple = Column(Boolean, default=False, nullable=False)
@@ -178,6 +182,8 @@ class ProductQuickOption(Base):
is_favorite = Column(Boolean, default=False, nullable=False) is_favorite = Column(Boolean, default=False, nullable=False)
favorite_sort_order = Column(Integer, default=0, nullable=False) favorite_sort_order = Column(Integer, default=0, nullable=False)
is_compact = Column(Boolean, default=False, nullable=False) is_compact = Column(Boolean, default=False, nullable=False)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
product = relationship("Product", back_populates="quick_options") product = relationship("Product", back_populates="quick_options")
@@ -186,7 +192,7 @@ class ProductIngredient(Base):
__tablename__ = "product_ingredients" __tablename__ = "product_ingredients"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
extra_cost = Column(Float, default=0.0) extra_cost = Column(Float, default=0.0)
is_favorite = Column(Boolean, default=False, nullable=False) is_favorite = Column(Boolean, default=False, nullable=False)
@@ -195,6 +201,8 @@ class ProductIngredient(Base):
is_compact = Column(Boolean, default=False, nullable=False) is_compact = Column(Boolean, default=False, nullable=False)
# Optional group/folder this ingredient belongs to # Optional group/folder this ingredient belongs to
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True) group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
product = relationship("Product", back_populates="ingredients") product = relationship("Product", back_populates="ingredients")
@@ -203,7 +211,7 @@ class ProductPreferenceSet(Base):
__tablename__ = "product_preference_sets" __tablename__ = "product_preference_sets"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
default_choice_id = Column(Integer, nullable=True) default_choice_id = Column(Integer, nullable=True)
# JSON: {name, default_choice_index, choices:[{name,extra_cost,is_default}]} # JSON: {name, default_choice_index, choices:[{name,extra_cost,is_default}]}
@@ -217,6 +225,8 @@ class ProductPreferenceSet(Base):
allow_multi_select = Column(Boolean, default=False, nullable=False) allow_multi_select = Column(Boolean, default=False, nullable=False)
# When True, each selected choice can have a quantity (x2, x3, …) # When True, each selected choice can have a quantity (x2, x3, …)
allow_choice_quantity = Column(Boolean, default=False, nullable=False) allow_choice_quantity = Column(Boolean, default=False, nullable=False)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
product = relationship("Product", back_populates="preference_sets") product = relationship("Product", back_populates="preference_sets")
choices = relationship("ProductPreferenceChoice", back_populates="set", cascade="all, delete-orphan") choices = relationship("ProductPreferenceChoice", back_populates="set", cascade="all, delete-orphan")
@@ -226,7 +236,7 @@ class ProductPreferenceChoice(Base):
__tablename__ = "product_preference_choices" __tablename__ = "product_preference_choices"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
set_id = Column(Integer, ForeignKey("product_preference_sets.id"), nullable=False) set_id = Column(Integer, ForeignKey("product_preference_sets.id"), nullable=False, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
extra_cost = Column(Float, default=0.0) extra_cost = Column(Float, default=0.0)
# JSON array of sub-choice objects: [{name, extra_cost, is_default, is_compact}] # JSON array of sub-choice objects: [{name, extra_cost, is_default, is_compact}]
@@ -236,6 +246,8 @@ class ProductPreferenceChoice(Base):
disables_subset = Column(Boolean, default=False, nullable=False) disables_subset = Column(Boolean, default=False, nullable=False)
# When True renders as half-width card on the PWA # When True renders as half-width card on the PWA
is_compact = Column(Boolean, default=False, nullable=False) is_compact = Column(Boolean, default=False, nullable=False)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
set = relationship("ProductPreferenceSet", back_populates="choices") set = relationship("ProductPreferenceSet", back_populates="choices")
+2 -2
View File
@@ -20,7 +20,7 @@ class Reservation(Base):
reserved_for = Column(UTCDateTime, nullable=False) reserved_for = Column(UTCDateTime, nullable=False)
# Optional table assignment (assignable/editable later) # Optional table assignment (assignable/editable later)
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True) table_id = Column(Integer, ForeignKey("tables.id"), nullable=True, index=True)
# Lifecycle: pending (confirmed, upcoming) | arrived | cancelled | no_show; # Lifecycle: pending (confirmed, upcoming) | arrived | cancelled | no_show;
# online requests (phase 3S, S.6) start as requested → pending (confirmed) | declined # online requests (phase 3S, S.6) start as requested → pending (confirmed) | declined
@@ -43,7 +43,7 @@ class Reservation(Base):
total = Column(Float, nullable=True) total = Column(Float, nullable=True)
online_price_diff = Column(Text, nullable=True) # services/online_check.py; NULL = matched 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) 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) response_note = Column(Text, nullable=True) # why it was declined / cancelled (the customer sees it)
created_at = Column(UTCDateTime, default=utcnow) created_at = Column(UTCDateTime, default=utcnow)
+23
View File
@@ -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)
+1 -1
View File
@@ -10,7 +10,7 @@ class ScheduledShift(Base):
__tablename__ = "scheduled_shifts" __tablename__ = "scheduled_shifts"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False) user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
scheduled_date = Column(Date, nullable=False) scheduled_date = Column(Date, nullable=False)
start_time = Column(String, nullable=False) # "HH:MM" stored as string (SQLite has no Time type) start_time = Column(String, nullable=False) # "HH:MM" stored as string (SQLite has no Time type)
end_time = Column(String, nullable=False) end_time = Column(String, nullable=False)
+3 -3
View File
@@ -10,8 +10,8 @@ class WaiterShift(Base):
__tablename__ = "waiter_shifts" __tablename__ = "waiter_shifts"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False) waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=False) business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=False, index=True)
started_at = Column(UTCDateTime, default=utcnow, nullable=False) started_at = Column(UTCDateTime, default=utcnow, nullable=False)
ended_at = Column(UTCDateTime, nullable=True) ended_at = Column(UTCDateTime, nullable=True)
starting_cash = Column(Float, nullable=True) starting_cash = Column(Float, nullable=True)
@@ -32,7 +32,7 @@ class ShiftBreak(Base):
__tablename__ = "shift_breaks" __tablename__ = "shift_breaks"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=False) shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=False, index=True)
started_at = Column(UTCDateTime, default=utcnow, nullable=False) started_at = Column(UTCDateTime, default=utcnow, nullable=False)
ended_at = Column(UTCDateTime, nullable=True) ended_at = Column(UTCDateTime, nullable=True)
+48 -9
View File
@@ -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 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). 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 A paired signage screen plays its default playlist (device config `playlist`) in its own
orientation and rotation (modules/signage/manifest.py). 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 import JSON, Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
@@ -53,15 +54,53 @@ class SignageSlide(Base):
playlist = relationship("SignagePlaylist", back_populates="slides") playlist = relationship("SignagePlaylist", back_populates="slides")
class SignageSchedule(Base): class SignageScheduleItem(Base):
"""Which playlist plays when (5.4d): entries matched in venue time (services/signage_schedule.py), """A schedule line (owner 2026-11-21, was named schedules of 5.4d): a playlist on some screens
the fallback when none matches. A screen with a schedule plays it instead of a single playlist.""" (none picked = every screen), on some days / hours / dates / smart days (core/calendar_days.py),
__tablename__ = "signage_schedules" 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) id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
fallback_playlist_id = Column(Integer, ForeignKey("signage_playlists.id", ondelete="SET NULL"), nullable=True) description = Column(String, nullable=True)
# [{playlist_id, days, time_from, time_to, date_from, date_to, priority}] orientation = Column(String, nullable=False, default="landscape") # landscape | portrait
entries = Column(JSON, nullable=False, default=list) 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) created_at = Column(UTCDateTime, default=utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False) updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
+1 -1
View File
@@ -22,7 +22,7 @@ class Table(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
number = Column(Integer, nullable=False) number = Column(Integer, nullable=False)
label = Column(String, nullable=True) label = Column(String, nullable=True)
group_id = Column(Integer, ForeignKey("table_groups.id"), nullable=True) group_id = Column(Integer, ForeignKey("table_groups.id"), nullable=True, index=True)
is_active = Column(Boolean, default=True, nullable=False) is_active = Column(Boolean, default=True, nullable=False)
seat_count = Column(Integer, nullable=True) seat_count = Column(Integer, nullable=True)
# its place on a floor plan (6.8, D-31; models/floor_plan.py): floor_x / floor_y = its centre # its place on a floor plan (6.8, D-31; models/floor_plan.py): floor_x / floor_y = its centre
+1 -1
View File
@@ -23,7 +23,7 @@ class TabletOrder(Base):
note = Column(Text, nullable=True) note = Column(Text, nullable=True)
total = Column(Float, nullable=False, default=0.0) total = Column(Float, nullable=False, default=0.0)
status = Column(String, nullable=False, default="waiting", index=True) 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) reason = Column(String, nullable=True)
decided_by_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True) decided_by_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
decided_at = Column(UTCDateTime, nullable=True) decided_at = Column(UTCDateTime, nullable=True)
+5 -5
View File
@@ -10,7 +10,7 @@ class Tab(Base):
__tablename__ = "tabs" __tablename__ = "tabs"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=False) customer_id = Column(Integer, ForeignKey("customers.id"), nullable=False, index=True)
status = Column(String, default="open", nullable=False) # open | closed | forgiven status = Column(String, default="open", nullable=False) # open | closed | forgiven
opened_at = Column(UTCDateTime, default=utcnow) opened_at = Column(UTCDateTime, default=utcnow)
closed_at = Column(UTCDateTime, nullable=True) closed_at = Column(UTCDateTime, nullable=True)
@@ -28,9 +28,9 @@ class TabEntry(Base):
__tablename__ = "tab_entries" __tablename__ = "tab_entries"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False) tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=True) order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True)
amount = Column(Float, nullable=False) # snapshot at time of tab entry amount = Column(Float, nullable=False) # snapshot at time of tab entry
description = Column(Text, nullable=True) # auto-generated summary description = Column(Text, nullable=True) # auto-generated summary
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
@@ -48,7 +48,7 @@ class TabPayment(Base):
__tablename__ = "tab_payments" __tablename__ = "tab_payments"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False) tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False, index=True)
amount = Column(Float, nullable=False) amount = Column(Float, nullable=False)
payment_method = Column(String, nullable=True) # cash | card | other payment_method = Column(String, nullable=True) # cash | card | other
received_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) received_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
+2 -2
View File
@@ -10,14 +10,14 @@ class WasteLog(Base):
__tablename__ = "waste_log" __tablename__ = "waste_log"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
quantity = Column(Float, nullable=False) # supports decimals quantity = Column(Float, nullable=False) # supports decimals
unit_cost_snapshot = Column(Float, nullable=True) # product's effective cost at log time unit_cost_snapshot = Column(Float, nullable=True) # product's effective cost at log time
total_cost = Column(Float, nullable=True) # unit_cost_snapshot * quantity total_cost = Column(Float, nullable=True) # unit_cost_snapshot * quantity
reason = Column(String, nullable=False) # kitchen_error|dropped|expired|other reason = Column(String, nullable=False) # kitchen_error|dropped|expired|other
reason_notes = Column(Text, nullable=True) reason_notes = Column(Text, nullable=True)
logged_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) logged_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True) business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
logged_at = Column(UTCDateTime, default=utcnow) logged_at = Column(UTCDateTime, default=utcnow)
product = relationship("Product", foreign_keys=[product_id]) product = relationship("Product", foreign_keys=[product_id])
+2
View File
@@ -12,6 +12,7 @@ MODULE = Module(
Perm('core.settings.manage', 'Change venue settings', roles=('owner',)), Perm('core.settings.manage', 'Change venue settings', roles=('owner',)),
Perm('core.modules.manage', 'Turn apps, features and integrations on or off', roles=('owner',)), Perm('core.modules.manage', 'Turn apps, features and integrations on or off', roles=('owner',)),
Perm('core.devices.manage', 'Pair, rename, reassign and remove devices', roles=('owner', 'store_manager')), Perm('core.devices.manage', 'Pair, rename, reassign and remove devices', roles=('owner', 'store_manager')),
Perm('core.scenes.manage', 'Make scenes and turn them on or off', roles=('owner', 'store_manager')),
Perm('core.system.admin', 'Support-only maintenance (superadmin)', roles=()), Perm('core.system.admin', 'Support-only maintenance (superadmin)', roles=()),
), ),
settings=( settings=(
@@ -48,6 +49,7 @@ MODULE = Module(
Mount('routers.media', '/api/media'), Mount('routers.media', '/api/media'),
Mount('routers.access', '/api/access'), Mount('routers.access', '/api/access'),
Mount('routers.notifications', '/api/platform/notifications'), Mount('routers.notifications', '/api/platform/notifications'),
Mount('routers.scenes', '/api/scenes'),
Mount('core.modules.api', '/api/platform'), Mount('core.modules.api', '/api/platform'),
), ),
) )
+2 -2
View File
@@ -27,8 +27,8 @@ MODULE = Module(
device_app=DeviceApp(login_modes=('none',), scope=(), config=( 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 # 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'), ConfigField('playlist', 'ref', default=None, choices_from='signage_playlists'),
# or a schedule: which playlist plays when (5.4d); it wins over the single playlist # ... or a library slide shown alone (owner 2026-11-21; a playlist wins when both are set)
ConfigField('schedule', 'ref', default=None, choices_from='signage_schedules'), ConfigField('slide', 'ref', default=None, choices_from='signage_slides'),
ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')), ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')),
ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)), ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)),
)), )),
+23 -9
View File
@@ -22,11 +22,17 @@ EXPORT_VERSION = 1 # tables bundle
CATALOG_EXPORT_VERSION = 2 # catalogue bundle: v2 = products listed in several categories (D-23) 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: def _serialize_product(p: Product) -> dict:
quick_options = [ quick_options = [
{"name": qo.name, "price": qo.price, "allow_multiple": qo.allow_multiple, {"name": qo.name, "price": qo.price, "allow_multiple": qo.allow_multiple,
"sort_order": qo.sort_order, "is_favorite": qo.is_favorite, "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 for qo in p.quick_options
] ]
options = [] options = []
@@ -34,10 +40,12 @@ def _serialize_product(p: Product) -> dict:
sub = json.loads(opt.sub_choices) if opt.sub_choices else [] sub = json.loads(opt.sub_choices) if opt.sub_choices else []
options.append({"name": opt.name, "extra_cost": opt.extra_cost, options.append({"name": opt.name, "extra_cost": opt.extra_cost,
"allow_multiple": opt.allow_multiple, "sub_choices": sub, "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 = [ ingredients = [
{"name": ing.name, "extra_cost": ing.extra_cost, {"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 for ing in p.ingredients
] ]
preference_sets = [] preference_sets = []
@@ -50,11 +58,13 @@ def _serialize_product(p: Product) -> dict:
default_index = i default_index = i
sub = json.loads(ch.sub_choices) if ch.sub_choices else [] sub = json.loads(ch.sub_choices) if ch.sub_choices else []
choices.append({"name": ch.name, "extra_cost": ch.extra_cost, 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({ preference_sets.append({
"name": ps.name, "choices": choices, "name": ps.name, "choices": choices,
"default_choice_index": default_index, "shared_subset": shared, "default_choice_index": default_index, "shared_subset": shared,
"is_favorite": ps.is_favorite, "favorite_sort_order": ps.favorite_sort_order, "is_favorite": ps.is_favorite, "favorite_sort_order": ps.favorite_sort_order,
"translations": menu_languages.names_of(ps),
}) })
return { return {
"name": p.name, "base_price": p.base_price, "is_available": p.is_available, "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() db.flush()
for qo in prod_data.get("quick_options", []): 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", []): for opt in prod_data.get("options", []):
sub_json = json.dumps(opt.get("sub_choices", [])) 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), 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, allow_multiple=opt.get("allow_multiple", False), sub_choices=sub_json,
is_favorite=opt.get("is_favorite", False), 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", []): 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", []): 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 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"], product_id=product.id, name=ps_data["name"],
shared_subset=shared_json, shared_subset=shared_json,
is_favorite=ps_data.get("is_favorite", False), 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.add(ps)
db.flush() 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", [])) sub_json = json.dumps(ch.get("sub_choices", []))
choice = ProductPreferenceChoice( choice = ProductPreferenceChoice(
set_id=ps.id, name=ch["name"], extra_cost=ch.get("extra_cost", 0.0), 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.add(choice)
db.flush() db.flush()
+104 -2
View File
@@ -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. be more than what is still due, and the total can't drop below what was already paid.
""" """
from datetime import date 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 sqlalchemy.orm import Session
from typing import List, Optional from typing import List, Optional
from database import get_db 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 models.user import User
from schemas.expenses import ( from schemas.expenses import (
ContactCreate, ContactUpdate, ContactOut, ContactCreate, ContactUpdate, ContactOut,
@@ -22,6 +24,7 @@ from schemas.expenses import (
from core.access.deps import require, require_any from core.access.deps import require, require_any
from core.errors import XeniaError from core.errors import XeniaError
from core.timeutil import venue_day_window from core.timeutil import venue_day_window
from services import expense_docs
from services.ws_bus import broadcast_sync from services.ws_bus import broadcast_sync
contacts_router = APIRouter() contacts_router = APIRouter()
@@ -43,6 +46,45 @@ def _check_contact(fields: dict):
raise XeniaError("validation.missing", field="name") 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): def _check_expense(db: Session, fields: dict, paid: float = 0.0):
if "description" in fields and not (fields["description"] or "").strip(): if "description" in fields and not (fields["description"] or "").strip():
raise XeniaError("validation.missing", field="description") raise XeniaError("validation.missing", field="description")
@@ -103,6 +145,11 @@ def _expense_out(e: Expense) -> dict:
"created_at": e.created_at, "created_at": e.created_at,
"notes": e.notes, "notes": e.notes,
"payments": payments_out, "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) @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): def create_expense(body: ExpenseCreate, db: Session = Depends(get_db), user: User = MANAGE):
fields = body.model_dump() 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) _check_expense(db, fields)
fields["description"] = fields["description"].strip() fields["description"] = fields["description"].strip()
expense = Expense(**fields, created_by_id=user.id) expense = Expense(**fields, created_by_id=user.id)
_set_lines(expense, lines)
db.add(expense) db.add(expense)
db.commit() db.commit()
db.refresh(expense) db.refresh(expense)
@@ -237,12 +288,16 @@ def update_expense(expense_id: int, body: ExpenseUpdate, db: Session = Depends(g
raise XeniaError("expense.not_found") raise XeniaError("expense.not_found")
# Fields sent as null are cleared (supplier, due date, notes); the rest only change when given # Fields sent as null are cleared (supplier, due date, notes); the rest only change when given
fields = body.model_dump(exclude_unset=True) 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"): for k in ("description", "category", "total_amount"):
if fields.get(k) is None: if fields.get(k) is None:
fields.pop(k, None) fields.pop(k, None)
_check_expense(db, fields, paid=expense.paid_amount) _check_expense(db, fields, paid=expense.paid_amount)
for field, value in fields.items(): for field, value in fields.items():
setattr(expense, field, value.strip() if field == "description" else value) setattr(expense, field, value.strip() if field == "description" else value)
_set_lines(expense, lines)
db.commit() db.commit()
db.refresh(expense) db.refresh(expense)
_changed() _changed()
@@ -256,6 +311,7 @@ def delete_expense(expense_id: int, db: Session = Depends(get_db), user: User =
raise XeniaError("expense.not_found") raise XeniaError("expense.not_found")
db.delete(expense) db.delete(expense)
db.commit() db.commit()
expense_docs.remove_all(expense_id)
_changed() _changed()
@@ -289,3 +345,49 @@ def record_payment(
db.refresh(expense) db.refresh(expense)
_changed() _changed()
return _expense_out(expense) 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)
+4 -2
View File
@@ -88,6 +88,7 @@ class PlacedItem(BaseModel):
height: float = Field(gt=0, le=6000) height: float = Field(gt=0, le=6000)
rotation: float = 0.0 rotation: float = 0.0
text: Optional[str] = Field(None, max_length=60) 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): 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, "media_id": p.media_id, "background": media_store.image_of(p.media) if p.media_id else None,
"background_opacity": p.background_opacity, "background_opacity": p.background_opacity,
"items": [{"id": i.id, "kind": i.kind, "x": i.x, "y": i.y, "width": i.width, "height": i.height, "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() db.flush()
for it in body.items: 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), 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.commit()
db.refresh(p) db.refresh(p)
_changed() _changed()
+4
View File
@@ -630,6 +630,8 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
# Build pricing context once for the whole batch # Build pricing context once for the whole batch
now = utcnow() now = utcnow()
active_pg_ids = build_active_price_group_ids(db, now) 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 # 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 from core.sales_points import is_sold_at, of_order
order_channel = of_order(order) order_channel = of_order(order)
@@ -670,6 +672,7 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
} }
], ],
active_price_group_ids=active_pg_ids, active_price_group_ids=active_pg_ids,
active_scene_ids=active_scenes,
) )
# Resolve final unit_price through pricing engine # Resolve final unit_price through pricing engine
@@ -804,6 +807,7 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
now=now, now=now,
cart_items=final_cart, cart_items=final_cart,
active_price_group_ids=active_pg_ids, active_price_group_ids=active_pg_ids,
active_scene_ids=active_scenes,
) )
deal_offers = evaluate_deals(order_id, deal_ctx, already_fired, db) deal_offers = evaluate_deals(order_id, deal_ctx, already_fired, db)
+135
View File
@@ -718,6 +718,8 @@ def _condition_ok(ctype: str, p: dict) -> bool:
return bool(p.get("channels")) return bool(p.get("channels"))
if ctype == "price_group_active": if ctype == "price_group_active":
return isinstance(p.get("price_group_id"), int) 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 return ctype in ("user_tier", "low_stock") # old placeholders: kept, never added
@@ -763,3 +765,136 @@ def _sync_deal_targets(deal, targets_in, db: Session):
target_ids=json.dumps(t.target_ids) if t.target_ids else None, 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, 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)}
+48 -7
View File
@@ -26,6 +26,35 @@ from core.errors import XeniaError
router = APIRouter() 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(): def _broadcast_products_changed():
broadcast_sync("products_changed", {}) broadcast_sync("products_changed", {})
@@ -43,6 +72,7 @@ def _replace_modifier_groups(db, product, groups):
modifier_type=g.modifier_type, modifier_type=g.modifier_type,
name=g.name, name=g.name,
sort_order=i, sort_order=i,
translations=menu_languages.dump(menu_languages.normalize_names(g.translations)),
) )
db.add(new_g) db.add(new_g)
db.flush() db.flush()
@@ -64,6 +94,7 @@ def _replace_quick_options(db, product, quick_options):
is_favorite=qo.is_favorite, is_favorite=qo.is_favorite,
favorite_sort_order=qo.favorite_sort_order, favorite_sort_order=qo.favorite_sort_order,
is_compact=qo.is_compact, 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.delete(opt)
db.flush() db.flush()
for opt in options: 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 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( db.add(ProductOption(
product_id=product.id, 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, favorite_sort_order=opt.favorite_sort_order,
is_compact=opt.is_compact, is_compact=opt.is_compact,
group_id=resolved_group, 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() db.flush()
for ing in ingredients: 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 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): 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.delete(ps)
db.flush() db.flush()
for ps in sets: 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 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( new_set = ProductPreferenceSet(
product_id=product.id, product_id=product.id,
@@ -113,12 +146,13 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
group_id=resolved_group, group_id=resolved_group,
allow_multi_select=ps.allow_multi_select, allow_multi_select=ps.allow_multi_select,
allow_choice_quantity=ps.allow_choice_quantity, allow_choice_quantity=ps.allow_choice_quantity,
translations=menu_languages.dump(menu_languages.normalize_names(ps.translations)),
) )
db.add(new_set) db.add(new_set)
db.flush() db.flush()
created_choices = [] created_choices = []
for ch in ps.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( choice = ProductPreferenceChoice(
set_id=new_set.id, set_id=new_set.id,
name=ch.name, name=ch.name,
@@ -126,6 +160,7 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
sub_choices=sub_json, sub_choices=sub_json,
disables_subset=ch.disables_subset, disables_subset=ch.disables_subset,
is_compact=ch.is_compact, is_compact=ch.is_compact,
translations=menu_languages.dump(menu_languages.normalize_names(ch.translations)),
) )
db.add(choice) db.add(choice)
db.flush() 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) @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)): 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", 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"}) "category_id", "primary_category_id", "category_ids", "allergens", "translations"})
if data.get("sort_order") == 0: 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, is_favorite=qo.is_favorite,
favorite_sort_order=qo.favorite_sort_order, favorite_sort_order=qo.favorite_sort_order,
is_compact=qo.is_compact, 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) created_groups = _replace_modifier_groups(db, product, body.modifier_groups)
group_id_map = [g.id for g in created_groups] group_id_map = [g.id for g in created_groups]
for opt in body.options: 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 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( db.add(ProductOption(
product_id=product.id, 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, favorite_sort_order=opt.favorite_sort_order,
is_compact=opt.is_compact, is_compact=opt.is_compact,
group_id=resolved_group, group_id=resolved_group,
translations=menu_languages.dump(menu_languages.normalize_names(opt.translations)),
)) ))
for ing in body.ingredients: 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 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) _replace_preference_sets(db, product, body.preference_sets, group_id_map)
db.commit() db.commit()
db.refresh(product) 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() product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
if not product: if not product:
raise XeniaError("product.not_found") raise XeniaError("product.not_found")
_check_names(body)
scalar_fields = body.model_dump( scalar_fields = body.model_dump(
exclude_none=True, exclude_none=True,
exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups", 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() product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
if not product: if not product:
raise XeniaError("product.not_found") 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.add(g)
db.commit() db.commit()
db.refresh(g) db.refresh(g)
+4 -11
View File
@@ -10,7 +10,7 @@ import json
from fastapi import APIRouter, Depends, Query, BackgroundTasks, Request from fastapi import APIRouter, Depends, Query, BackgroundTasks, Request
from fastapi.responses import StreamingResponse from fastapi.responses import StreamingResponse
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session, contains_eager, selectinload
from sqlalchemy import func from sqlalchemy import func
from datetime import date, datetime, timedelta, timezone from datetime import date, datetime, timedelta, timezone
from typing import Optional, List from typing import Optional, List
@@ -1386,7 +1386,7 @@ def cancellations_log(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_reports), 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 # 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) 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() items = q.order_by(OrderItem.added_at.desc()).all()
waiters_db = {u.id: u for u in db.query(User).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()} 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 = [] result = []
for item in items: 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 "—" table_name = tables_db.get(order.table_id, f"#{order.table_id}") if order else "—"
waiter = waiters_db.get(item.added_by) waiter = waiters_db.get(item.added_by)
waiter_name = (waiter.full_name or waiter.username) if waiter else f"#{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) product_zone_map[product.id].append(zone.id)
# Query order items in the requested range # 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') _since = history_since(from_dt, 'reports')
if _since: if _since:
q = q.filter(Order.opened_at >= _since) q = q.filter(Order.opened_at >= _since)
+90
View File
@@ -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)
+348 -116
View File
@@ -12,8 +12,14 @@ Manager side (signage.manage):
PUT /api/signage/slides/{id} change it PUT /api/signage/slides/{id} change it
DELETE /api/signage/slides/{id} DELETE /api/signage/slides/{id}
POST /api/signage/slides/{id}/duplicate a copy right after it POST /api/signage/slides/{id}/duplicate a copy right after it
GET /api/signage/screens the paired screens: playlist, orientation, rotation GET /api/signage/library the Slides library (2026-11-21): kept slides
PUT /api/signage/screens/{id} {playlist_id, orientation, rotation} POST /api/signage/library {name, description, orientation, kind, …slide fields}
GET /api/signage/library/{id} one (a menu board resolved for its preview)
PUT /api/signage/library/{id} change it (a screen showing it is told)
DELETE /api/signage/library/{id} screens that had it as their default show nothing
POST /api/signage/library/{id}/duplicate a copy
GET /api/signage/screens the paired screens: playlist or slide, orientation, rotation
PUT /api/signage/screens/{id} {playlist_id | slide_id, orientation, rotation}
The screen (a paired device running `signage`, no sign-in): The screen (a paired device running `signage`, no sign-in):
GET /api/signage/screen its playlist resolved for playing GET /api/signage/screen its playlist resolved for playing
@@ -29,13 +35,13 @@ import json
from typing import Dict, List, Literal, Optional from typing import Dict, List, Literal, Optional
from fastapi import APIRouter, Depends, Response from fastapi import APIRouter, Depends, Response
from pydantic import BaseModel, ConfigDict, Field, field_validator from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from core.access.deps import require, require_device from core.access.deps import require, require_device
from core.errors import XeniaError from core.errors import XeniaError
from database import get_db from database import get_db
from models.signage import SignagePlaylist, SignageSchedule, SignageSlide from models.signage import SignagePlaylist, SignageSavedSlide, SignageScheduleItem, SignageSlide
from services import media as media_store from services import media as media_store
from services import video as video_store from services import video as video_store
from services.ws_bus import broadcast_sync from services.ws_bus import broadcast_sync
@@ -66,14 +72,34 @@ class Background(_Strict):
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather"] WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather"]
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar"] Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"]
class Box(_Strict):
"""Where a widget moved by hand sits (2026-11-21): % of the slide's width / height."""
x: float = Field(ge=0, le=100)
y: float = Field(ge=0, le=100)
w: float = Field(ge=2, le=100)
h: float = Field(ge=2, le=100)
@model_validator(mode="after")
def _inside(self):
# kept on the slide: a box never runs past its right or bottom edge
self.w = round(min(self.w, 100), 2)
self.h = round(min(self.h, 100), 2)
self.x = round(min(self.x, 100 - self.w), 2)
self.y = round(min(self.y, 100 - self.h), 2)
return self
class Widget(_Strict): class Widget(_Strict):
"""Something small on a menu or text slide (5.4c), in a corner or a bar.""" """Something small on a menu, text or blank slide (5.4c), in a corner or a bar, or (moved and
sized by hand on the editor's preview, 2026-11-21) in its own box: position and size "custom"."""
kind: WidgetKind kind: WidgetKind
position: Position = "top-right" position: Position = "top-right"
size: Literal["small", "medium", "large"] = "medium" size: Literal["small", "medium", "large", "custom"] = "medium"
box: Optional[Box] = None # position "custom"
align: Literal["auto", "left", "center", "right"] = "auto" # inside its place; auto: by its corner / box
media_id: Optional[int] = None # logo: a picture media_id: Optional[int] = None # logo: a picture
text: Optional[str] = Field(default=None, max_length=200) # message: this text instead of the venue's text: Optional[str] = Field(default=None, max_length=200) # message: this text instead of the venue's
date_style: Literal["short", "long"] = "long" date_style: Literal["short", "long"] = "long"
@@ -83,6 +109,18 @@ class Widget(_Strict):
qr_caption: Optional[str] = Field(default=None, max_length=80) qr_caption: Optional[str] = Field(default=None, max_length=80)
weather_days: int = Field(default=1, ge=1, le=3) # today, or today + the next days weather_days: int = Field(default=1, ge=1, le=3) # today, or today + the next days
@model_validator(mode="after")
def _place(self):
if self.position == "custom":
if self.box is None:
raise ValueError("a widget placed by hand needs its box")
self.size = "custom"
else:
self.box = None
if self.size == "custom":
self.size = "medium"
return self
@field_validator("qr_url") @field_validator("qr_url")
@classmethod @classmethod
def _url(cls, v): def _url(cls, v):
@@ -118,6 +156,12 @@ class TextContent(_Strict):
widgets: List[Widget] = Field(default_factory=list, max_length=10) widgets: List[Widget] = Field(default_factory=list, max_length=10)
class BlankContent(_Strict):
"""A blank slide (2026-11-21): only its background and its widgets."""
background: Background = Field(default_factory=Background)
widgets: List[Widget] = Field(default_factory=list, max_length=10)
Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"] Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"]
@@ -143,6 +187,8 @@ class MenuContent(_Strict):
language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed
# how it's laid out (the player pages through what doesn't fit, 5.5b) # how it's laid out (the player pages through what doesn't fit, 5.5b)
columns: int = Field(default=2, ge=1, le=3) columns: int = Field(default=2, ge=1, le=3)
board_width: int = Field(default=100, ge=40, le=100) # % of the screen the list takes (2026-11-21)
board_align: Literal["left", "center", "right"] = "left" # where a narrower list sits, and its title
page_size: Optional[int] = Field(default=None, ge=3, le=60) # items per page; None = as many as fit page_size: Optional[int] = Field(default=None, ge=3, le=60) # items per page; None = as many as fit
page_seconds: int = Field(default=10, ge=3, le=120) page_seconds: int = Field(default=10, ge=3, le=120)
font: Font = "sans" font: Font = "sans"
@@ -168,8 +214,8 @@ class MenuContent(_Strict):
return v return v
CONTENT = {"image": ImageContent, "video": VideoContent, "text": TextContent, "menu": MenuContent} CONTENT = {"image": ImageContent, "video": VideoContent, "text": TextContent, "menu": MenuContent, "blank": BlankContent}
Kind = Literal["menu", "image", "video", "text"] Kind = Literal["menu", "image", "video", "text", "blank"]
# ── requests ─────────────────────────────────────────────────────────────────── # ── requests ───────────────────────────────────────────────────────────────────
@@ -218,14 +264,21 @@ class OrderBody(BaseModel):
slide_ids: List[int] slide_ids: List[int]
class ScheduleEntry(BaseModel): class ScheduleLine(BaseModel):
"""A schedule line (owner 2026-11-21): a playlist on some screens ([] = every screen), when, with a priority."""
id: Optional[int] = None
name: Optional[str] = Field(default=None, max_length=80)
playlist_id: int playlist_id: int
screen_ids: List[int] = Field(default_factory=list)
priority: int = Field(default=0, ge=0, le=100)
enabled: bool = True
days: List[int] = Field(default_factory=list) # [0..6], Monday = 0; [] = every day days: List[int] = Field(default_factory=list) # [0..6], Monday = 0; [] = every day
month_days: List[str] = Field(default_factory=list) # core/calendar_days.MONTH_DAYS
time_from: Optional[str] = Field(default=None, pattern=TIME) time_from: Optional[str] = Field(default=None, pattern=TIME)
time_to: Optional[str] = Field(default=None, pattern=TIME) time_to: Optional[str] = Field(default=None, pattern=TIME)
date_from: Optional[str] = Field(default=None, pattern=DATE) date_from: Optional[str] = Field(default=None, pattern=DATE)
date_to: Optional[str] = Field(default=None, pattern=DATE) date_to: Optional[str] = Field(default=None, pattern=DATE)
priority: int = Field(default=0, ge=0, le=100) scene_id: Optional[int] = None
@field_validator("days") @field_validator("days")
@classmethod @classmethod
@@ -234,16 +287,29 @@ class ScheduleEntry(BaseModel):
raise ValueError("days are 0 (Monday) to 6 (Sunday)") raise ValueError("days are 0 (Monday) to 6 (Sunday)")
return sorted(set(v)) return sorted(set(v))
@field_validator("month_days")
@classmethod
def _month_days(cls, v):
from core.calendar_days import MONTH_DAYS
if any(d not in MONTH_DAYS for d in v):
raise ValueError(f"smart days are {', '.join(MONTH_DAYS)}")
return [d for d in MONTH_DAYS if d in v]
class ScheduleBody(BaseModel):
name: str = Field(min_length=1, max_length=80) class SchedulesBody(BaseModel):
fallback_playlist_id: Optional[int] = None lines: List[ScheduleLine] = Field(default_factory=list, max_length=200)
entries: List[ScheduleEntry] = Field(default_factory=list, max_length=100)
class SavedSlideBody(SlideFields):
"""A library slide: its name and description, the shape it is built for, its kind (new ones)."""
kind: Optional[Kind] = None
description: Optional[str] = Field(default=None, max_length=300)
orientation: Optional[Orientation] = None
class ScreenBody(BaseModel): class ScreenBody(BaseModel):
playlist_id: Optional[int] = None playlist_id: Optional[int] = None # its default playlist
schedule_id: Optional[int] = None slide_id: Optional[int] = None # … or a library slide (one or the other)
orientation: Optional[Orientation] = None orientation: Optional[Orientation] = None
rotation: Optional[Literal[0, 90, 180, 270]] = None rotation: Optional[Literal[0, 90, 180, 270]] = None
@@ -355,24 +421,36 @@ def _screen_config(dev) -> dict:
return effective(for_app("signage"), dev.config) return effective(for_app("signage"), dev.config)
def slide_key(slide_id: int) -> str:
"""A library slide shown alone, where a playlist id goes (a screen's default, 2026-11-21)."""
return f"slide:{slide_id}"
def default_of(cfg: dict):
"""A screen's default: its playlist's id, else "slide:<id>" for its library slide, else None."""
if cfg.get("playlist"):
return cfg["playlist"]
if cfg.get("slide"):
return slide_key(cfg["slide"])
return None
def _screens_showing_slide(db, slide_id: int) -> list[int]:
return [d.id for d in _screens(db) if not _screen_config(d).get("playlist") and _screen_config(d).get("slide") == slide_id]
def _screen_playlists(db, d) -> set:
"""Every playlist a screen may play: its default and those of its schedule lines."""
from services.signage_schedule import lines_for
out = {i.playlist_id for i in lines_for(db, d.id)}
if _screen_config(d).get("playlist"):
out.add(_screen_config(d)["playlist"])
return out
def _screens_playing(db, playlist_id: int) -> list[int]: def _screens_playing(db, playlist_id: int) -> list[int]:
"""The screens that play it: as their playlist, or anywhere in their schedule.""" """The screens that may play it: as their default, or in one of their schedule lines."""
in_schedules = {s.id for s in db.query(SignageSchedule) if playlist_id in _schedule_playlists(s)} return [d.id for d in _screens(db) if playlist_id in _screen_playlists(db, d)]
out = []
for d in _screens(db):
cfg = _screen_config(d)
if cfg.get("schedule") in in_schedules or (not cfg.get("schedule") and cfg.get("playlist") == playlist_id):
out.append(d.id)
return out
def _schedule_playlists(s) -> set:
if s is None:
return set()
out = {e.get("playlist_id") for e in (s.entries or []) if e.get("playlist_id")}
if s.fallback_playlist_id:
out.add(s.fallback_playlist_id)
return out
def _tell(ids: list[int]) -> None: def _tell(ids: list[int]) -> None:
@@ -434,6 +512,14 @@ def _uses(db, media_id: int) -> list:
media_store.register_usage("signage_slide", _uses) media_store.register_usage("signage_slide", _uses)
def _saved_uses(db, media_id: int) -> list:
return [{"id": s.id, "name": s.name} for s in db.query(SignageSavedSlide).order_by(SignageSavedSlide.name)
if media_id in media_ids(s.content or {})]
media_store.register_usage("signage_saved_slide", _saved_uses)
def _video_done(db, media_id: int) -> None: def _video_done(db, media_id: int) -> None:
"""A video's playable version is ready (services/video.py): the screens playing it switch to it.""" """A video's playable version is ready (services/video.py): the screens playing it switch to it."""
playlists = {s.playlist_id for s in db.query(SignageSlide).filter(SignageSlide.kind == "video") playlists = {s.playlist_id for s in db.query(SignageSlide).filter(SignageSlide.kind == "video")
@@ -452,10 +538,11 @@ def tell_all_screens(db) -> None:
def menu_changed(db) -> None: def menu_changed(db) -> None:
"""Products, categories or prices changed (main.py, the same requests that push the online menu): """Products, categories or prices changed (main.py, the same requests that push the online menu):
the screens with a menu board on their playlist read it again.""" the screens with a menu board on their playlist (or as their default slide) read it again."""
playlists = {pid for (pid,) in db.query(SignageSlide.playlist_id).filter(SignageSlide.kind == "menu")} playlists = {pid for (pid,) in db.query(SignageSlide.playlist_id).filter(SignageSlide.kind == "menu")}
if playlists: boards = {slide_key(sid) for (sid,) in db.query(SignageSavedSlide.id).filter(SignageSavedSlide.kind == "menu")}
_tell([d.id for d in _screens(db) if _screen_config(d).get("playlist") in playlists]) if playlists or boards:
_tell([d.id for d in _screens(db) if _screen_playlists(db, d) & playlists or default_of(_screen_config(d)) in boards])
# ── playlists ────────────────────────────────────────────────────────────────── # ── playlists ──────────────────────────────────────────────────────────────────
@@ -500,12 +587,8 @@ def delete_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depend
for d in _screens(db): for d in _screens(db):
if (d.config or {}).get("playlist") == p.id: if (d.config or {}).get("playlist") == p.id:
d.config = {**(d.config or {}), "playlist": None} d.config = {**(d.config or {}), "playlist": None}
for sch in db.query(SignageSchedule): for item in db.query(SignageScheduleItem).filter(SignageScheduleItem.playlist_id == p.id):
kept = [e for e in (sch.entries or []) if e.get("playlist_id") != p.id] db.delete(item) # its schedule lines go with it
if kept != (sch.entries or []):
sch.entries = kept
if sch.fallback_playlist_id == p.id:
sch.fallback_playlist_id = None
db.delete(p) db.delete(p)
db.commit() db.commit()
_tell(stopped) _tell(stopped)
@@ -605,20 +688,133 @@ def duplicate_slide(slide_id: int, db: Session = Depends(get_db), user=Depends(r
return _slide_out(copy) return _slide_out(copy)
# ── the Slides library (owner 2026-11-21) ──────────────────────────────────────
def _saved(db, sid: int) -> SignageSavedSlide:
s = db.get(SignageSavedSlide, sid)
if s is None:
raise XeniaError("signage.slide_unknown", slide_id=sid)
return s
def _saved_out(s: SignageSavedSlide, db=None) -> dict:
out = {"id": s.id, "name": s.name, "description": s.description, "orientation": s.orientation, "kind": s.kind,
"duration_s": s.duration_s, "transition": s.transition, "video_to_end": bool(s.video_to_end), "enabled": bool(s.enabled),
"days": s.days or [], "time_from": s.time_from, "time_to": s.time_to, "date_from": s.date_from, "date_to": s.date_to,
"content": s.content or {}}
if db is not None:
if s.kind == "menu":
from services.signage_menu import resolve
out["menu"] = resolve(db, out["content"])
showing = set(_screens_showing_slide(db, s.id))
out["screens"] = [{"id": d.id, "name": d.name} for d in _screens(db) if d.id in showing]
return out
def _saved_name(body) -> str:
name = (body.name or "").strip()
if not name:
raise XeniaError("signage.content_invalid", field="name", reason="required")
return name
@router.get("/library")
def list_saved(db: Session = Depends(get_db), user=Depends(require(KEY))):
"""Every kept slide, with its menu resolved (the gallery's previews) and the media they show."""
rows = db.query(SignageSavedSlide).order_by(SignageSavedSlide.name, SignageSavedSlide.id).all()
return {"slides": [_saved_out(s, db) for s in rows],
"media": _media_map(db, [i for s in rows for i in media_ids(s.content or {})])}
@router.post("/library", status_code=201)
def create_saved(body: SavedSlideBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
if body.kind is None:
raise XeniaError("signage.content_invalid", field="kind", reason="required")
name = _saved_name(body)
s = SignageSavedSlide(name=name, kind=body.kind, orientation=body.orientation or "landscape", duration_s=10, enabled=True,
video_to_end=body.kind == "video", content=_content(db, body.kind, None))
_apply(db, s, body)
s.name = name
s.description = (body.description or "").strip() or None
db.add(s)
db.commit()
db.refresh(s)
return _saved_out(s, db)
@router.get("/library/{slide_id}")
def get_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id)
out = _saved_out(s, db)
out["media"] = _media_map(db, media_ids(s.content or {}))
return out
@router.put("/library/{slide_id}")
def update_saved(slide_id: int, body: SavedSlideBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id)
if body.kind is not None and body.kind != s.kind:
raise XeniaError("signage.content_invalid", field="kind", reason="a slide keeps its kind")
name = _saved_name(body) if "name" in body.model_fields_set else s.name
_apply(db, s, body)
s.name = name
if "description" in body.model_fields_set:
s.description = (body.description or "").strip() or None
if body.orientation is not None:
s.orientation = body.orientation
db.commit()
db.refresh(s)
_tell(_screens_showing_slide(db, s.id))
return _saved_out(s, db)
@router.delete("/library/{slide_id}", status_code=204)
def delete_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id)
showing = _screens_showing_slide(db, s.id)
for d in _screens(db):
if (d.config or {}).get("slide") == s.id:
d.config = {**(d.config or {}), "slide": None}
db.delete(s)
db.commit()
_tell(showing)
return Response(status_code=204)
@router.post("/library/{slide_id}/duplicate", status_code=201)
def duplicate_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id)
copy = SignageSavedSlide(name=f"{s.name} (2)"[:80], description=s.description, orientation=s.orientation, kind=s.kind,
duration_s=s.duration_s, transition=s.transition, video_to_end=s.video_to_end, enabled=s.enabled,
days=s.days, time_from=s.time_from, time_to=s.time_to, date_from=s.date_from, date_to=s.date_to,
content=json.loads(json.dumps(s.content or {})))
db.add(copy)
db.commit()
db.refresh(copy)
return _saved_out(copy, db)
# ── screens ──────────────────────────────────────────────────────────────────── # ── screens ────────────────────────────────────────────────────────────────────
def _screen_out(db, d) -> dict: def _screen_out(db, d) -> dict:
"""A screen: its default playlist, shape and turn, and what plays on it now (a schedule line wins)."""
from services.signage_schedule import now_for
cfg = _screen_config(d) cfg = _screen_config(d)
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None
sch = db.get(SignageSchedule, cfg["schedule"]) if cfg.get("schedule") else None sl = db.get(SignageSavedSlide, cfg["slide"]) if cfg.get("slide") and not p else None
if sch is not None: now_id, scheduled = now_for(db, d)
ids = _schedule_playlists(sch) if isinstance(now_id, str):
shapes = {x.orientation for x in db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids))} if ids else set() now = {"id": now_id, "name": sl.name, "scheduled": False, "slide": True} if sl else None
else: else:
shapes = {p.orientation} if p else set() now_p = db.get(SignagePlaylist, now_id) if now_id else None
now = {"id": now_p.id, "name": now_p.name, "scheduled": scheduled} if now_p else None
ids = _screen_playlists(db, d)
shapes = {x.orientation for x in db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids))} if ids else set()
if sl:
shapes.add(sl.orientation)
return {"id": d.id, "name": d.name, "playlist_id": p.id if p else None, "playlist_name": p.name if p else None, return {"id": d.id, "name": d.name, "playlist_id": p.id if p else None, "playlist_name": p.name if p else None,
"schedule_id": sch.id if sch else None, "schedule_name": sch.name if sch else None, "slide_id": sl.id if sl else None, "slide_name": sl.name if sl else None,
"orientation": cfg["orientation"], "rotation": cfg["rotation"], "orientation": cfg["orientation"], "rotation": cfg["rotation"], "now": now,
"orientation_mismatch": any(o != cfg["orientation"] for o in shapes)} "orientation_mismatch": any(o != cfg["orientation"] for o in shapes)}
@@ -636,7 +832,12 @@ def update_screen(device_id: int, body: ScreenBody, db: Session = Depends(get_db
raise XeniaError("signage.not_a_screen", device_id=device_id) raise XeniaError("signage.not_a_screen", device_id=device_id)
cfg = dict(d.config or {}) cfg = dict(d.config or {})
for key in body.model_fields_set: for key in body.model_fields_set:
cfg[{"playlist_id": "playlist", "schedule_id": "schedule"}.get(key, key)] = getattr(body, key) cfg[{"playlist_id": "playlist", "slide_id": "slide"}.get(key, key)] = getattr(body, key)
# the default is a playlist or a library slide, never both
if "playlist_id" in body.model_fields_set and body.playlist_id is not None:
cfg["slide"] = None
if "slide_id" in body.model_fields_set and body.slide_id is not None:
cfg["playlist"] = None
d.config = validate(for_app("signage"), cfg, db) d.config = validate(for_app("signage"), cfg, db)
db.commit() db.commit()
broadcast_sync("device.updated", {}, device_ids=[d.id]) broadcast_sync("device.updated", {}, device_ids=[d.id])
@@ -661,29 +862,59 @@ def _resolved(db, p: SignagePlaylist) -> dict:
"media": _media_map(db, [i for s in slides for i in media_ids(s["content"])])} "media": _media_map(db, [i for s in slides for i in media_ids(s["content"])])}
def _resolved_slide(db, s: SignageSavedSlide, orientation: str) -> dict:
"""A library slide shown alone as a screen's default: a playlist of that one slide."""
from services.signage_menu import resolve
one = _saved_out(s)
one["transition"] = one["transition"] or "fade"
if one["kind"] == "menu":
one["menu"] = resolve(db, one["content"])
for w in one["content"].get("widgets") or []:
if w["kind"] == "qr":
w["link"] = _qr_link(w)
slides = [one] if s.enabled else []
return {"id": slide_key(s.id), "name": s.name, "orientation": orientation, "transition": "fade", "slides": slides,
"media": _media_map(db, media_ids(one["content"]))}
def _default_resolved(db, cfg: dict):
d = default_of(cfg)
if isinstance(d, str):
s = db.get(SignageSavedSlide, cfg["slide"])
return d, (_resolved_slide(db, s, cfg["orientation"]) if s else None)
p = db.get(SignagePlaylist, d) if d else None
return d, (_resolved(db, p) if p else None)
@router.get("/screen") @router.get("/screen")
def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))): def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))):
"""What this screen plays: its settings and its playlist with every slide and media address. """What this screen plays: its settings and its playlist with every slide and media address.
Slides that are off are left out; time windows are the player's (it keeps playing offline). Slides that are off are left out; time windows are the player's (it keeps playing offline).
With a schedule (5.4d): the schedule and every playlist in it, so the screen switches by With schedule lines for it (5.4d, 2026-11-21): the lines, the scenes on now and every playlist
itself; `playlist` is the one playing now. `version` changes whenever anything here does.""" they name, so the screen switches by itself; `playlist` is the one playing now and the
schedule's `fallback_playlist_id` is the screen's default. `version` changes whenever anything
here does."""
from core.timeutil import venue_now, venue_tz from core.timeutil import venue_now, venue_tz
from services import weather from services import weather
from services.signage_schedule import pick from services.scenes import active_ids
from services.signage_schedule import entry_of, lines_for, pick
cfg = _screen_config(dev) cfg = _screen_config(dev)
sch = db.get(SignageSchedule, cfg["schedule"]) if cfg.get("schedule") else None lines = lines_for(db, dev.id)
schedule, playlists, playlist = None, None, None schedule, playlists, playlist = None, None, None
if sch is not None: default, fallback = _default_resolved(db, cfg)
ids = _schedule_playlists(sch) if lines:
ids = _screen_playlists(db, dev)
playlists = {str(p.id): _resolved(db, p) for p in playlists = {str(p.id): _resolved(db, p) for p in
(db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids)).all() if ids else [])} (db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids)).all() if ids else [])}
now_id = pick(sch.entries or [], sch.fallback_playlist_id, venue_now()) if isinstance(default, str) and fallback:
playlists[default] = fallback # its library slide, under "slide:<id>"
scenes = sorted(active_ids(db))
entries = [entry_of(i) for i in lines]
now_id = pick(entries, default, venue_now(), scenes)
playlist = playlists.get(str(now_id)) if now_id else None playlist = playlists.get(str(now_id)) if now_id else None
schedule = {"id": sch.id, "name": sch.name, "entries": sch.entries or [], "fallback_playlist_id": sch.fallback_playlist_id, schedule = {"entries": entries, "fallback_playlist_id": default, "scenes": scenes, "timezone": venue_tz().key}
"timezone": venue_tz().key}
else: else:
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None playlist = fallback
playlist = _resolved(db, p) if p is not None else None
out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]}, out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]},
"playlist": playlist, "schedule": schedule, "playlists": playlists, "playlist": playlist, "schedule": schedule, "playlists": playlists,
# for the widgets (5.4c): weather None = hide it (no internet, no place, too old) # for the widgets (5.4c): weather None = hide it (no internet, no place, too old)
@@ -693,73 +924,74 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))
return out return out
# ── schedules (5.4d) ─────────────────────────────────────────────────────────── # ── schedules (5.4d; lines with their screens and scenes, owner 2026-11-21) ─────
def _schedule(db, sid: int) -> SignageSchedule: def _line_out(i: SignageScheduleItem, now_ids: dict) -> dict:
s = db.get(SignageSchedule, sid) return {"id": i.id, "name": i.name, "playlist_id": i.playlist_id, "screen_ids": i.screen_ids or [], "priority": i.priority,
if s is None: "enabled": bool(i.enabled), "days": i.days or [], "month_days": i.month_days or [], "time_from": i.time_from,
raise XeniaError("signage.schedule_unknown", schedule_id=sid) "time_to": i.time_to, "date_from": i.date_from, "date_to": i.date_to, "scene_id": i.scene_id, "position": i.position,
return s # the screens where this line wins now
"playing_on": now_ids.get(i.id, [])}
def _schedule_out(db, s: SignageSchedule) -> dict: def _lines_out(db) -> list:
from core.timeutil import venue_now from core.timeutil import venue_now
from services.signage_schedule import pick from services.scenes import active_ids
names = {p.id: p.name for p in db.query(SignagePlaylist)} from services.signage_schedule import entry_of, lines_for, matches
now_id = pick(s.entries or [], s.fallback_playlist_id, venue_now()) local, scenes = venue_now(), active_ids(db)
return {"id": s.id, "name": s.name, "fallback_playlist_id": s.fallback_playlist_id, "entries": s.entries or [], winners: dict = {}
"playing_now": {"id": now_id, "name": names.get(now_id)} if now_id else None, for d in _screens(db):
"screens": [{"id": d.id, "name": d.name} for d in _screens(db) if _screen_config(d).get("schedule") == s.id]} best, key = None, None
for n, i in enumerate(lines_for(db, d.id)):
e = entry_of(i)
def _check_schedule(db, body: ScheduleBody) -> None: if not matches(e, local, scenes):
for pid in [body.fallback_playlist_id, *[e.playlist_id for e in body.entries]]: continue
if pid is not None: from services.signage_schedule import _specific
_playlist(db, pid) k = (i.priority or 0, _specific(e), n)
if key is None or k > key:
best, key = i.id, k
if best is not None:
winners.setdefault(best, []).append({"id": d.id, "name": d.name})
items = db.query(SignageScheduleItem).order_by(SignageScheduleItem.position, SignageScheduleItem.id).all()
return [_line_out(i, winners) for i in items]
@router.get("/schedules") @router.get("/schedules")
def list_schedules(db: Session = Depends(get_db), user=Depends(require(KEY))): def list_schedules(db: Session = Depends(get_db), user=Depends(require(KEY))):
return [_schedule_out(db, s) for s in db.query(SignageSchedule).order_by(SignageSchedule.name)] return _lines_out(db)
@router.post("/schedules", status_code=201) @router.put("/schedules")
def create_schedule(body: ScheduleBody, db: Session = Depends(get_db), user=Depends(require(KEY))): def save_schedules(body: SchedulesBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
_check_schedule(db, body) """Every schedule line at once (the tab saves them together); ids that aren't sent are deleted."""
s = SignageSchedule(name=body.name.strip(), fallback_playlist_id=body.fallback_playlist_id, from models.scene import Scene
entries=[e.model_dump() for e in body.entries]) screens = {d.id for d in _screens(db)}
db.add(s) for line in body.lines:
_playlist(db, line.playlist_id)
if line.scene_id is not None and db.get(Scene, line.scene_id) is None:
raise XeniaError("signage.scene_unknown", scene_id=line.scene_id)
for sid in line.screen_ids:
if sid not in screens:
raise XeniaError("signage.screen_unknown", device_id=sid)
keep = {line.id for line in body.lines if line.id}
for item in db.query(SignageScheduleItem):
if item.id not in keep:
db.delete(item)
db.flush()
for n, line in enumerate(body.lines):
item = db.get(SignageScheduleItem, line.id) if line.id else None
if item is None:
item = SignageScheduleItem()
db.add(item)
for k, v in line.model_dump(exclude={"id"}).items():
setattr(item, k, (v or "").strip() or None if k == "name" else v)
item.screen_ids = sorted(set(line.screen_ids))
item.position = n
db.commit() db.commit()
db.refresh(s) _tell([d.id for d in _screens(db)]) # their lines may have changed
return _schedule_out(db, s) return _lines_out(db)
@router.put("/schedules/{schedule_id}")
def update_schedule(schedule_id: int, body: ScheduleBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _schedule(db, schedule_id)
_check_schedule(db, body)
s.name = body.name.strip()
s.fallback_playlist_id = body.fallback_playlist_id
s.entries = [e.model_dump() for e in body.entries]
db.commit()
db.refresh(s)
_tell([d.id for d in _screens(db) if _screen_config(d).get("schedule") == s.id])
return _schedule_out(db, s)
@router.delete("/schedules/{schedule_id}", status_code=204)
def delete_schedule(schedule_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _schedule(db, schedule_id)
moved = []
for d in _screens(db):
if (d.config or {}).get("schedule") == s.id:
d.config = {**(d.config or {}), "schedule": None}
moved.append(d.id)
db.delete(s)
db.commit()
_tell(moved)
return Response(status_code=204)
# ── the message of the day and the weather (5.4c) ────────────────────────────── # ── the message of the day and the weather (5.4c) ──────────────────────────────
class MessageBody(BaseModel): class MessageBody(BaseModel):
+30 -1
View File
@@ -59,11 +59,35 @@ class ExpensePaymentOut(BaseModel):
model_config = {"from_attributes": True} 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): class ExpenseCreate(BaseModel):
description: str description: str
category: str category: str
contact_id: Optional[int] = None 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 due_date: Optional[datetime] = None
business_day_id: Optional[int] = None business_day_id: Optional[int] = None
notes: Optional[str] = None notes: Optional[str] = None
@@ -80,6 +104,7 @@ class ExpenseUpdate(BaseModel):
category: Optional[str] = None category: Optional[str] = None
contact_id: Optional[int] = None contact_id: Optional[int] = None
total_amount: Optional[float] = None total_amount: Optional[float] = None
lines: Optional[List[ExpenseLineIn]] = None # given: replaces the lines ([] = none)
due_date: Optional[datetime] = None due_date: Optional[datetime] = None
notes: Optional[str] = None notes: Optional[str] = None
@@ -107,5 +132,9 @@ class ExpenseOut(BaseModel):
created_at: datetime created_at: datetime
notes: Optional[str] = None notes: Optional[str] = None
payments: List[ExpensePaymentOut] = [] 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} model_config = {"from_attributes": True}
+33 -1
View File
@@ -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.sales_points import ALL as _SALES_POINTS, sold_at as _sold_at
from core.allergens import of as _allergens_of 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"] 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" modifier_type: str # "option" | "ingredient" | "preference"
name: str name: str
sort_order: int = 0 sort_order: int = 0
translations: Dict[str, str] = {} # its name per language (0042)
class ModifierGroupOut(BaseModel): class ModifierGroupOut(BaseModel):
@@ -84,9 +85,15 @@ class ModifierGroupOut(BaseModel):
modifier_type: str modifier_type: str
name: str name: str
sort_order: int = 0 sort_order: int = 0
translations: Dict[str, str] = {} # its name per language (0042)
model_config = {"from_attributes": True} 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 ───────────────────────────────────────────────────────────── # ── Quick Options ─────────────────────────────────────────────────────────────
@@ -98,6 +105,7 @@ class ProductQuickOptionCreate(BaseModel):
is_favorite: bool = False is_favorite: bool = False
favorite_sort_order: int = 0 favorite_sort_order: int = 0
is_compact: bool = False is_compact: bool = False
translations: Dict[str, str] = {} # its name per language (0042)
class ProductQuickOptionOut(BaseModel): class ProductQuickOptionOut(BaseModel):
@@ -110,9 +118,15 @@ class ProductQuickOptionOut(BaseModel):
is_favorite: bool = False is_favorite: bool = False
favorite_sort_order: int = 0 favorite_sort_order: int = 0
is_compact: bool = False is_compact: bool = False
translations: Dict[str, str] = {} # its name per language (0042)
model_config = {"from_attributes": True} 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 ────────────────────────────────────────────────────────────────── # ── Options ──────────────────────────────────────────────────────────────────
@@ -124,6 +138,7 @@ class OptionSubChoice(BaseModel):
allow_multiple: bool = False allow_multiple: bool = False
# When True renders as half-width card on the PWA # When True renders as half-width card on the PWA
is_compact: bool = False is_compact: bool = False
translations: Dict[str, str] = {} # its name per language (0042)
class ProductOptionBase(BaseModel): class ProductOptionBase(BaseModel):
@@ -137,6 +152,7 @@ class ProductOptionBase(BaseModel):
# When True renders the option itself as half-width card on the PWA # When True renders the option itself as half-width card on the PWA
is_compact: bool = False is_compact: bool = False
group_id: Optional[int] = None group_id: Optional[int] = None
translations: Dict[str, str] = {} # its name per language (0042)
class ProductOptionCreate(ProductOptionBase): class ProductOptionCreate(ProductOptionBase):
@@ -168,6 +184,7 @@ class ProductOptionOut(ProductOptionBase):
'favorite_sort_order': getattr(data, 'favorite_sort_order', 0) or 0, 'favorite_sort_order': getattr(data, 'favorite_sort_order', 0) or 0,
'is_compact': getattr(data, 'is_compact', False) or False, 'is_compact': getattr(data, 'is_compact', False) or False,
'group_id': getattr(data, 'group_id', None), 'group_id': getattr(data, 'group_id', None),
'translations': _choice_names(data),
} }
return data return data
@@ -182,6 +199,7 @@ class ProductIngredientBase(BaseModel):
# When True renders as half-width card on the PWA # When True renders as half-width card on the PWA
is_compact: bool = False is_compact: bool = False
group_id: Optional[int] = None group_id: Optional[int] = None
translations: Dict[str, str] = {} # its name per language (0042)
class ProductIngredientCreate(ProductIngredientBase): class ProductIngredientCreate(ProductIngredientBase):
@@ -194,6 +212,11 @@ class ProductIngredientOut(ProductIngredientBase):
model_config = {"from_attributes": True} 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) ──────────────────────────── # ── Sub-choices (nested under a preference choice) ────────────────────────────
@@ -202,6 +225,7 @@ class SubChoice(BaseModel):
extra_cost: float = 0.0 extra_cost: float = 0.0
is_default: bool = False is_default: bool = False
is_compact: 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) ───────────── # ── Shared subset (set-level, shown for all non-disabling choices) ─────────────
@@ -211,10 +235,12 @@ class SharedSubsetChoice(BaseModel):
extra_cost: float = 0.0 extra_cost: float = 0.0
is_default: bool = False is_default: bool = False
is_compact: bool = False is_compact: bool = False
translations: Dict[str, str] = {} # its name per language (0042)
class SharedSubset(BaseModel): class SharedSubset(BaseModel):
name: str name: str
translations: Dict[str, str] = {} # its name per language (0042)
choices: List[SharedSubsetChoice] = [] choices: List[SharedSubsetChoice] = []
@@ -227,6 +253,7 @@ class PreferenceChoiceCreate(BaseModel):
disables_subset: bool = False disables_subset: bool = False
# When True renders as half-width card on the PWA # When True renders as half-width card on the PWA
is_compact: bool = False is_compact: bool = False
translations: Dict[str, str] = {} # its name per language (0042)
class PreferenceChoiceOut(BaseModel): class PreferenceChoiceOut(BaseModel):
@@ -237,6 +264,7 @@ class PreferenceChoiceOut(BaseModel):
sub_choices: List[SubChoice] = [] sub_choices: List[SubChoice] = []
disables_subset: bool = False disables_subset: bool = False
is_compact: bool = False is_compact: bool = False
translations: Dict[str, str] = {} # its name per language (0042)
model_config = {"from_attributes": True} model_config = {"from_attributes": True}
@@ -260,6 +288,7 @@ class PreferenceChoiceOut(BaseModel):
'sub_choices': parsed, 'sub_choices': parsed,
'disables_subset': data.disables_subset or False, 'disables_subset': data.disables_subset or False,
'is_compact': getattr(data, 'is_compact', False) or False, 'is_compact': getattr(data, 'is_compact', False) or False,
'translations': _choice_names(data),
} }
return data return data
@@ -274,6 +303,7 @@ class PreferenceSetCreate(BaseModel):
group_id: Optional[int] = None group_id: Optional[int] = None
allow_multi_select: bool = False allow_multi_select: bool = False
allow_choice_quantity: bool = False allow_choice_quantity: bool = False
translations: Dict[str, str] = {} # its name per language (0042)
class PreferenceSetOut(BaseModel): class PreferenceSetOut(BaseModel):
@@ -288,6 +318,7 @@ class PreferenceSetOut(BaseModel):
group_id: Optional[int] = None group_id: Optional[int] = None
allow_multi_select: bool = False allow_multi_select: bool = False
allow_choice_quantity: bool = False allow_choice_quantity: bool = False
translations: Dict[str, str] = {} # its name per language (0042)
model_config = {"from_attributes": True} model_config = {"from_attributes": True}
@@ -315,6 +346,7 @@ class PreferenceSetOut(BaseModel):
'group_id': getattr(data, 'group_id', None), 'group_id': getattr(data, 'group_id', None),
'allow_multi_select': getattr(data, 'allow_multi_select', False) or False, 'allow_multi_select': getattr(data, 'allow_multi_select', False) or False,
'allow_choice_quantity': getattr(data, 'allow_choice_quantity', False) or False, 'allow_choice_quantity': getattr(data, 'allow_choice_quantity', False) or False,
'translations': _choice_names(data),
} }
return data return data
+137
View File
@@ -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
+2 -2
View File
@@ -289,7 +289,7 @@ def menu_snapshot(db) -> tuple[dict, list]:
"digital_image_url": p.digital_image_url, "digital_image_url": p.digital_image_url,
"image_url": p.image_url, "image_url": p.image_url,
"quick_options": [{"id": o.id, "name": o.name, "price": o.price, "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"} "allergens": allergens.of(p), # 6.3: {key: "contains" | "may_contain"}
**menu_languages.product_texts(p), # 6.4: names / descriptions {language: text} **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 # 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. # worker; edits in a row within MENU_SETTLE_SECONDS become one push.
MENU_SETTLE_SECONDS = 5 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 "/api/connect/qr", "/api/tables") # S.7: the tables' QR codes travel with the menu
_menu_wake: "asyncio.Event | None" = None _menu_wake: "asyncio.Event | None" = None
_menu_loop = None _menu_loop = None
+79
View File
@@ -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}
+6 -2
View File
@@ -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 from services.pricing import OrderContext, build_active_price_group_ids, resolve_price
now = utcnow() now = utcnow()
active = build_active_price_group_ids(db, now) 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) channel = point or point_for(order_type)
cart = list(existing_cart or []) cart = list(existing_cart or [])
out = [] 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") raise _bad(n, "not_sold_here")
here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids, 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} "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) unit, events = resolve_price(p, line.quantity, line.extra, ctx, db)
out.append((unit, events)) out.append((unit, events))
cart.append({**here, "unit_price": unit}) 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 from services.pricing import OrderContext, build_active_price_group_ids, resolve_price
now = now or utcnow() now = now or utcnow()
active = build_active_price_group_ids(db, now) active = build_active_price_group_ids(db, now)
from services.pricing import build_active_scene_ids
scenes = build_active_scene_ids(db, now)
out = [] out = []
for p in products: for p in products:
here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids, here = {"product_id": p.id, "category_id": p.primary_category_id, "category_ids": p.category_ids,
"quantity": 1, "unit_price": p.base_price} "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]) out.append(resolve_price(p, 1, 0.0, ctx, db)[0])
return out return out
+21 -1
View File
@@ -38,6 +38,7 @@ class OrderContext:
cart_items: list # list of {product_id, category_id (primary), category_ids, quantity, unit_price} 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 active_price_group_ids: set # set of PriceGroup.id that are currently active
user_tier: Optional[str] = None # 'bronze'|'silver'|'gold' — placeholder 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 @dataclass
@@ -144,6 +145,11 @@ def _eval_condition(ctype: str, params: dict, ctx: OrderContext,
passed = pgid in ctx.active_price_group_ids passed = pgid in ctx.active_price_group_ids
return passed, {"price_group_active": passed} 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": if ctype == "user_tier":
passed = ctx.user_tier in params.get("tiers", []) passed = ctx.user_tier in params.get("tiers", [])
return passed, {"user_tier": ctx.user_tier} 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) 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: def build_active_price_group_ids(db: Session, now: datetime) -> set:
"""Fetch all price groups once per request and return active IDs.""" """Fetch all price groups once per request and return active IDs."""
from models.pricing import PriceGroup 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. order_id must be set on the PriceEvents before writing them; the caller does this.
""" """
from models.pricing import PriceModifier from models.pricing import PriceModifier
from services import channel_prices
base = product.base_price + options_extra
events: list[PriceEvent] = [] 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 --- # --- Load modifiers ---
# Item-scoped modifiers for this product # Item-scoped modifiers for this product
+8 -1
View File
@@ -29,6 +29,12 @@ def is_fee(item) -> bool:
return getattr(item, "system_key", None) is not None 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 @dataclass
class Line: class Line:
item: object item: object
@@ -54,11 +60,12 @@ def lines(db, items) -> list[Line]:
from services.refunds import refunded_quantities from services.refunds import refunded_quantities
sold = [i for i in items if i.status in SOLD] 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"]) back = refunded_quantities(db, [i.id for i in sold if i.status == "paid"])
fees = _fee_products(db) if sold else set()
out = [] out = []
for i in sold: for i in sold:
r = min(back.get(i.id, 0.0), i.quantity) r = min(back.get(i.id, 0.0), i.quantity)
q = max(i.quantity - r, 0.0) 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 return out
+42
View File
@@ -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
+51 -21
View File
@@ -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, A screen's lines are the schedule lines (models/signage.py SignageScheduleItem) that are on and
priority} and a fallback playlist. At a moment (venue time) the entries that match are: name it (or no screen = every screen). At a moment (venue time) a line matches when:
- its days include today (empty = every day), - 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, - 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), 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 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 `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 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: def _date_ok(e: dict, day) -> bool:
from core.calendar_days import month_days_ok
d = day.isoformat() 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: def matches(e: dict, local: datetime, scenes=None) -> bool:
"""Does entry `e` cover this venue-local moment?""" """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 [] days = e.get("days") or []
start, end = _minutes(e.get("time_from")), _minutes(e.get("time_to")) start, end = _minutes(e.get("time_from")), _minutes(e.get("time_to"))
now = local.hour * 60 + local.minute now = local.hour * 60 + local.minute
@@ -55,15 +62,15 @@ def matches(e: dict, local: datetime) -> bool:
def _specific(e: dict) -> int: 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) (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).""" """The playlist id that plays at `local` (venue time)."""
best, best_key = None, None best, best_key = None, None
for i, e in enumerate(entries or []): 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 continue
key = (e.get("priority") or 0, _specific(e), i) key = (e.get("priority") or 0, _specific(e), i)
if best_key is None or key > best_key: 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 _playing: dict[int, int | None] = {} # screen id → the playlist it was told about
def due_changes(db, local: datetime | None = None) -> list[int]: ENTRY_KEYS = ("playlist_id", "days", "month_days", "time_from", "time_to", "date_from", "date_to", "priority", "scene_id")
"""The screens on a schedule whose pick is different from the last one seen (and remember it)."""
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 core.timeutil import venue_now
from models.signage import SignageSchedule from routers.signage import _screen_config, default_of
from routers.signage import _screen_config, _screens from services.scenes import active_ids
local = local or venue_now() 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 = [] changed = []
for d in _screens(db): for d in _screens(db):
sid = _screen_config(d).get("schedule") now = now_for(db, d, local, scenes)[0]
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
if d.id in _playing and _playing[d.id] != now: if d.id in _playing and _playing[d.id] != now:
changed.append(d.id) changed.append(d.id)
_playing[d.id] = now _playing[d.id] = now
@@ -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
+44
View File
@@ -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 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.get("/api/tabs/", headers=no).status_code == 403
assert client.post("/api/orders/1/items/1/tab", 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
+13
View File
@@ -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 assert len(client.get("/api/floor-plans/live", headers=owner_h).json()["tables"]) == 4
# only the tables' managers set plans up # only the tables' managers set plans up
assert client.post("/api/floor-plans", headers=h, json={"name": "x"}).status_code == 403 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
@@ -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") 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) 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) 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": "Ψητά"}}
+2 -1
View File
@@ -105,7 +105,8 @@ def test_message_in_the_readers_language(client, db, make_user, login):
def test_license_expiring_steps(client, db, people): def test_license_expiring_steps(client, db, people):
owner = people["owner"] 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) check_license_expiry(end, 20, True, db)
assert keys(client, owner[1]) == [] assert keys(client, owner[1]) == []
check_license_expiry(end, 12, True, db) check_license_expiry(end, 12, True, db)
+51
View File
@@ -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"
@@ -0,0 +1,96 @@
"""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}}]})
clock, date = s["content"]["widgets"]
assert clock["size"] == "custom" and clock["box"] == {"x": 80, "y": 5, "w": 20, "h": 10} and clock["align"] == "right" # kept on the slide
assert date["size"] == "medium" and date["box"] is None # a corner: no box, a real size
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"
+92 -43
View File
@@ -1,10 +1,12 @@
"""Signage schedules (plan step 5.4d): which playlist plays when (days, hours that may pass """Signage schedules (plan step 5.4d; lines with their screens, smart days and scenes, owner
midnight, dates, priority, a fallback); a screen on a schedule gets every playlist in it so it 2026-11-21): which playlist plays when (days, hours that may pass midnight, dates, smart days,
switches by itself, and the server tells it when the pick changes.""" priority, a scene); no line → the screen's default playlist. A screen with lines gets every
from datetime import datetime playlist they name so it switches by itself, and the server tells it when the pick changes."""
from datetime import date, datetime
import pytest import pytest
from core.calendar_days import is_holiday, month_days_ok, orthodox_easter
from services.signage_schedule import matches, pick from services.signage_schedule import matches, pick
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures) from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_signage import playlist, slide 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(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": 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 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(): def test_the_winner():
entries = [{"playlist_id": 10, "time_from": "12:00", "time_to": "15:00"}, entries = [{"playlist_id": 10, "time_from": "12:00", "time_to": "15:00"},
{"playlist_id": 20, "days": [5, 6]}, {"playlist_id": 20, "days": [5, 6]},
{"playlist_id": 30, "days": [5, 6], "time_from": "12:00", "time_to": "15:00"}, {"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}] {"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": 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, 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, 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, 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 @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")) lunch, weekend, normal = (playlist(client, owner_h, n) for n in ("Lunch", "Weekend", "Normal"))
for p in (lunch, weekend, normal): for p in (lunch, weekend, normal):
slide(client, owner_h, p["id"], "text", content={"title": p["name"]}) 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") token, dev = pair("signage", "TV")
client.put(f"/api/signage/screens/{dev.json()['id']}", headers=owner_h, json={"schedule_id": r.json()["id"]}) _, other = pair("signage", "Bar TV")
return {"h": {"X-Xenia-Device": token}, "id": dev.json()["id"], "schedule": r.json(), 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"]} "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) at(MON_10)
got = client.get("/api/signage/screen", headers=setup["h"]).json() 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 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"]["timezone"] == "Europe/Athens" and len(got["schedule"]["entries"]) == 2
assert got["schedule"]["fallback_playlist_id"] == setup["normal"]
at(MON_13) at(MON_13)
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Lunch" assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Lunch"
at(SAT_13) at(SAT_13)
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Weekend" assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Weekend"
s = client.get("/api/signage/schedules", headers=owner_h).json()[0] lines = client.get("/api/signage/schedules", headers=owner_h).json()
assert s["playing_now"]["name"] == "Weekend" and [x["name"] for x in s["screens"]] == ["TV"] assert sorted(x["name"] for x in lines[1]["playing_on"]) == ["Bar TV", "TV"] # the weekend line is for every screen
screen = client.get("/api/signage/screens", headers=owner_h).json()[0] screens = {s["name"]: s for s in client.get("/api/signage/screens", headers=owner_h).json()}
assert screen["schedule_name"] == "The week" and screen["orientation_mismatch"] is False 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): 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)) at(datetime(2026, 11, 16, 11, 59, 40))
assert ss.due_changes(db) == [] assert ss.due_changes(db) == []
at(datetime(2026, 11, 16, 12, 0)) 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) == [] assert ss.due_changes(db) == []
at(datetime(2026, 11, 16, 15, 0)) at(datetime(2026, 11, 16, 15, 0))
assert ss.due_changes(db) == [setup["id"]] # and ends 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): def test_changes_and_deletes(client, owner_h, setup, sent, at):
at(MON_10) at(MON_13)
sid = setup["schedule"]["id"] lines = client.get("/api/signage/schedules", headers=owner_h).json()
sent.clear() sent.clear()
client.put(f"/api/signage/schedules/{sid}", headers=owner_h, json={"name": "The week", "fallback_playlist_id": setup["lunch"], "entries": []}) 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 sent == [("signage.changed", [setup["id"]])] assert sorted(sent[0][1]) == sorted([setup["id"], setup["bar"]])
assert client.get("/api/signage/screen", headers=setup["h"]).json()["playlist"]["name"] == "Lunch" 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 the schedule reaches the screen # a slide changed in a playlist of its lines reaches the screen
lunch = client.get(f"/api/signage/playlists/{setup['lunch']}", headers=owner_h).json() wk = client.get(f"/api/signage/playlists/{setup['weekend']}", headers=owner_h).json()
sent.clear() sent.clear()
client.put(f"/api/signage/slides/{lunch['slides'][0]['id']}", headers=owner_h, json={"duration_s": 20}) client.put(f"/api/signage/slides/{wk['slides'][0]['id']}", headers=owner_h, json={"duration_s": 20})
assert sent == [("signage.changed", [setup["id"]])] assert sorted(sent[0][1]) == sorted([setup["id"], setup["bar"]])
# deleting a playlist takes it out of the schedule # deleting a playlist takes its lines with it
client.delete(f"/api/signage/playlists/{setup['lunch']}", headers=owner_h) client.delete(f"/api/signage/playlists/{setup['weekend']}", headers=owner_h)
assert client.get("/api/signage/schedules", headers=owner_h).json()[0]["fallback_playlist_id"] is None assert client.get("/api/signage/schedules", headers=owner_h).json() == []
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
got = client.get("/api/signage/screen", headers=setup["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): def test_schedules_are_checked(client, owner_h, setup):
body = {"name": "Bad", "entries": [{"playlist_id": 99999}]} put = lambda line: client.put("/api/signage/schedules", headers=owner_h, json={"lines": [line]}) # noqa: E731
assert err(client.post("/api/signage/schedules", headers=owner_h, json=body)) == "signage.playlist_unknown" assert err(put({"playlist_id": 99999})) == "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 err(put({"playlist_id": setup["lunch"], "screen_ids": [99999]})) == "signage.screen_unknown"
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(put({"playlist_id": setup["lunch"], "scene_id": 99999})) == "signage.scene_unknown"
assert err(client.put(f"/api/signage/screens/{setup['id']}", headers=owner_h, json={"schedule_id": 99999})) == "validation.device_config" assert put({"playlist_id": setup["lunch"], "days": [9]}).status_code == 422
assert err(client.get("/api/signage/schedules/99999", headers=owner_h)) in ("http.404", "http.405") 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"
+4 -4
View File
@@ -22,8 +22,6 @@ import OverviewPage from './pages/overview/OverviewPage'
import TablesPage from './pages/orders/TablesPage' import TablesPage from './pages/orders/TablesPage'
import OrderPage from './pages/orders/OrderPage' import OrderPage from './pages/orders/OrderPage'
import OnlineOrdersPage from './pages/online/OnlineOrdersPage' import OnlineOrdersPage from './pages/online/OnlineOrdersPage'
import FeesPage from './pages/online/FeesPage'
import QrCodesPage from './pages/online/QrCodesPage'
// CRM // CRM
import ContactsPage from './pages/finance/ContactsPage' import ContactsPage from './pages/finance/ContactsPage'
@@ -44,6 +42,7 @@ import ApprovalsPage from './pages/staff/ApprovalsPage'
import ManagementSchedulePage from './pages/schedule/SchedulePage' import ManagementSchedulePage from './pages/schedule/SchedulePage'
import PrepZonesConfigPage from './pages/printing/PrepZonesPage' import PrepZonesConfigPage from './pages/printing/PrepZonesPage'
import PricingPage from './pages/pricing/PricingPage' import PricingPage from './pages/pricing/PricingPage'
import ScenesPage from './pages/scenes/ScenesPage'
// Inventory // Inventory
import ThrowawaysPage from './pages/inventory/ThrowawaysPage' import ThrowawaysPage from './pages/inventory/ThrowawaysPage'
@@ -134,8 +133,8 @@ export default function App() {
<Route path="dashboard" element={<OverviewPage />} /> <Route path="dashboard" element={<OverviewPage />} />
<Route path="tables" element={<TablesPage />} /> <Route path="tables" element={<TablesPage />} />
<Route path="online-orders" element={<OnlineOrdersPage />} /> <Route path="online-orders" element={<OnlineOrdersPage />} />
<Route path="online/fees" element={<FeesPage />} /> <Route path="online/fees" element={<Navigate to="/online-orders?tab=settings" replace />} />
<Route path="online/qr" element={<QrCodesPage />} /> <Route path="online/qr" element={<Navigate to="/tables?view=qr" replace />} />
<Route path="orders/:orderId" element={<OrderPage />} /> <Route path="orders/:orderId" element={<OrderPage />} />
{/* ── CRM ── */} {/* ── CRM ── */}
@@ -157,6 +156,7 @@ export default function App() {
<Route path="management/schedule" element={<ManagementSchedulePage />} /> <Route path="management/schedule" element={<ManagementSchedulePage />} />
<Route path="management/prep-zones" element={<PrepZonesConfigPage />} /> <Route path="management/prep-zones" element={<PrepZonesConfigPage />} />
<Route path="management/pricing" element={<PricingPage />} /> <Route path="management/pricing" element={<PricingPage />} />
<Route path="management/scenes" element={<ScenesPage />} />
{/* ── Inventory ── */} {/* ── Inventory ── */}
<Route path="inventory/throwaways" element={<ThrowawaysPage />} /> <Route path="inventory/throwaways" element={<ThrowawaysPage />} />
@@ -75,7 +75,7 @@ export default function UserMenuButton({ displayName, onEditProfile, onSignOut }
</button> </button>
<div className="my-1 border-t border-line" /> <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" /> <Languages className="h-3.5 w-3.5" />
{t('profile.language')} {t('profile.language')}
</div> </div>
@@ -94,7 +94,7 @@ export default function UserMenuButton({ displayName, onEditProfile, onSignOut }
))} ))}
<div className="my-1 border-t border-line" /> <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" /> <Palette className="h-3.5 w-3.5" />
{t('profile.look')} {t('profile.look')}
</div> </div>
@@ -1,7 +1,9 @@
// Management → Tables: the tables and their zones (the list, for typing and bulk changes), and // 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). // the floor plans (plan step 6.8: where the tables stand, drawn on a map). On the page rule
import { useState } from 'react' // (2026-11-20): the tabs above, the tab in the address (?tab=).
import { useSearchParams } from 'react-router-dom'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Page, Tabs } from '@xenia/ui'
import FloorPlansTab from '../floor/FloorPlansTab' import FloorPlansTab from '../floor/FloorPlansTab'
import TablesListTab from '../tables/TablesListTab' import TablesListTab from '../tables/TablesListTab'
@@ -9,21 +11,14 @@ const TABS = ['list', 'floor']
export default function TablesConfigPage() { export default function TablesConfigPage() {
const { t } = useTranslation('manager') 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 ( return (
<div className="flex flex-col h-full min-h-0"> <Page testId="tables-config"
<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')}> top={<Tabs size="lg" value={tab} onChange={setTab} aria-label={t('floor.pageTabs')}
{TABS.map(k => ( tabs={TABS.map(k => ({ id: k, label: t(`floor.tabs.${k}`), testId: `tables-tab-${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 />} {tab === 'list' ? <TablesListTab /> : <FloorPlansTab />}
</div> </Page>
</div>
) )
} }
+3 -3
View File
@@ -5,7 +5,7 @@ import { useCallback, useEffect, useState } from 'react'
import { PhoneIncoming } from 'lucide-react' import { PhoneIncoming } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' 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 client from '../api/client'
import { useLiveEvent } from '../live/useLiveEvent' import { useLiveEvent } from '../live/useLiveEvent'
import usePhoneStore from '../store/phoneStore' 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}` const hook = `${window.location.protocol}//${window.location.hostname}/api/phone/call-event?caller=\${CALLERID}&ext=\${EXTEN}`
return ( 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"> <header className="grid gap-1">
<h1 className="text-heading font-semibold text-ink">{t('calls.title')}</h1> <h1 className="text-heading font-semibold text-ink">{t('calls.title')}</h1>
<p className="text-body text-ink-2">{t('calls.intro')}</p> <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> <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> <p className="text-caption text-ink-3">{t('calls.setupSecret')}</p>
</section> </section>
</div> </Page>
) )
} }
@@ -5,7 +5,7 @@
import { useSearchParams } from 'react-router-dom' import { useSearchParams } from 'react-router-dom'
import { useCan, useModule } from '@xenia/access' import { useCan, useModule } from '@xenia/access'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button } from '@xenia/ui' import { Page, Tabs } from '@xenia/ui'
import PrintingSettings from '../printing/PrintingSettings' import PrintingSettings from '../printing/PrintingSettings'
import CustomerDisplaySettings from './sections/CustomerDisplaySettings' import CustomerDisplaySettings from './sections/CustomerDisplaySettings'
import DevelopmentSettings from './sections/DevelopmentSettings' import DevelopmentSettings from './sections/DevelopmentSettings'
@@ -19,9 +19,9 @@ import VenueSettings from './sections/VenueSettings'
const TABS = { const TABS = {
'app-info': () => <SystemSettings />, 'app-info': () => <SystemSettings />,
venue: () => <div className="max-w-3xl"><VenueSettings /></div>, venue: () => <VenueSettings />,
'customer-display': () => <div className="max-w-4xl"><CustomerDisplaySettings /></div>, 'customer-display': () => <CustomerDisplaySettings />,
'menu-tablets': () => <div className="max-w-3xl"><MenuTabletSettings /></div>, 'menu-tablets': () => <MenuTabletSettings />,
security: () => <SecuritySettings />, security: () => <SecuritySettings />,
operation: () => <OperationSettings />, operation: () => <OperationSettings />,
colours: () => <TableColours />, colours: () => <TableColours />,
@@ -47,16 +47,11 @@ export default function SettingsPage() {
const active = tabs.includes(params.get('tab')) ? params.get('tab') : tabs[0] const active = tabs.includes(params.get('tab')) ? params.get('tab') : tabs[0]
const Tab = TABS[active] const Tab = TABS[active]
return ( return (
<div className="h-full flex flex-col min-h-0" data-testid="settings-page"> // settings are forms: the page's form width, centred (the page rule, 2026-11-20)
<div className="shrink-0 border-b border-line bg-surface px-4 lg:px-6 overflow-x-auto"> <Page testId="settings-page" width="form" aria-label={t('settings.title')}
<div className="flex gap-1 py-2" role="tablist" aria-label={t('settings.title')}> top={<Tabs size="lg" value={active} onChange={id => setParams({ tab: id }, { replace: true })}
{tabs.map(id => ( tabs={tabs.map(id => ({ id, label: t(`settings.tabs.${id}`), testId: `settings-tab-${id}` }))} />}>
<Button key={id} size="sm" variant={active === id ? 'primary' : 'ghost'} role="tab" aria-selected={active === id} <Tab />
onClick={() => setParams({ tab: id }, { replace: true })} data-testid={`settings-tab-${id}`}>{t(`settings.tabs.${id}`)}</Button> </Page>
))}
</div>
</div>
<div className="flex-1 overflow-y-auto p-4 lg:p-6"><Tab /></div>
</div>
) )
} }
@@ -11,7 +11,7 @@ export default function DevelopmentSettings() {
if (s.loading) return <div className="py-8 flex justify-center"><Spinner /></div> if (s.loading) return <div className="py-8 flex justify-center"><Spinner /></div>
const spoof = s.get('dev.spoof_printing', 'false') === 'true' const spoof = s.get('dev.spoof_printing', 'false') === 'true'
return ( return (
<div className="grid gap-5 max-w-3xl" data-testid="settings-development"> <div className="grid gap-5" 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> <p className="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')}> <SettingsCard title={t('settings.dev.title')}>
<SettingRow label={t('settings.dev.spoof')} hint={t('settings.dev.spoofHint')} warning={spoof ? t('settings.dev.spoofOn') : undefined}> <SettingRow label={t('settings.dev.spoof')} hint={t('settings.dev.spoofHint')} warning={spoof ? t('settings.dev.spoofOn') : undefined}>
@@ -21,7 +21,7 @@ export default function FiscalSettings() {
if (s.loading) return <div className="py-8 flex justify-center"><Spinner /></div> if (s.loading) return <div className="py-8 flex justify-center"><Spinner /></div>
const on = s.get('fiscal.enabled', 'false') === 'true' const on = s.get('fiscal.enabled', 'false') === 'true'
return ( return (
<div className="grid gap-5 max-w-3xl" data-testid="settings-fiscal"> <div className="grid gap-5" data-testid="settings-fiscal">
<SettingsCard title={t('settings.fiscal.title')} description={t('settings.fiscal.intro')}> <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')}
warning={on ? t('settings.fiscal.onWarning') : undefined}> warning={on ? t('settings.fiscal.onWarning') : undefined}>
@@ -26,7 +26,7 @@ export default function OperationSettings() {
const chat = useModule('chat') const chat = useModule('chat')
const qrMenu = useModule('connect_menu') const qrMenu = useModule('connect_menu')
return ( return (
<div className="grid gap-5 max-w-3xl" data-testid="settings-operation"> <div className="grid gap-5" data-testid="settings-operation">
<RolePermissions /> <RolePermissions />
{ordering && <OrderingSettings />} {ordering && <OrderingSettings />}
{ordering && <TableFlags />} {ordering && <TableFlags />}
@@ -19,7 +19,7 @@ import { useSettings } from './useSettings'
export default function SecuritySettings() { export default function SecuritySettings() {
return ( return (
<div className="grid gap-5 max-w-3xl" data-testid="settings-security"> <div className="grid gap-5" data-testid="settings-security">
<SignInSettings /> <SignInSettings />
<IdleSettings /> <IdleSettings />
<RecoveryCodes /> <RecoveryCodes />
@@ -43,7 +43,7 @@ export default function SystemSettings() {
const counts = ['categories', 'products', 'tables', 'table_groups', 'managers', 'waiters'] const counts = ['categories', 'products', 'tables', 'table_groups', 'managers', 'waiters']
return ( return (
<div className="grid gap-5 max-w-3xl" data-testid="settings-system"> <div className="grid gap-5" data-testid="settings-system">
<SettingsCard title={t('settings.system.title')}> <SettingsCard title={t('settings.system.title')}>
<SettingRow label={t('settings.system.version')}> <SettingRow label={t('settings.system.version')}>
<span className="flex flex-wrap items-center gap-2 text-body font-semibold text-ink" data-testid="system-version"> <span className="flex flex-wrap items-center gap-2 text-body font-semibold text-ink" data-testid="system-version">
@@ -79,7 +79,7 @@ export default function SystemSettings() {
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 p-5"> <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 p-5">
{counts.map(k => ( {counts.map(k => (
<div key={k} className="rounded-card bg-surface-2 p-3 grid"> <div key={k} className="rounded-card bg-surface-2 p-3 grid">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t(`settings.system.counts.${k}`)}</span> <span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t(`settings.system.counts.${k}`)}</span>
<span className="text-title font-semibold tabular-nums text-ink">{stats?.[k] ?? '—'}</span> <span className="text-title font-semibold tabular-nums text-ink">{stats?.[k] ?? '—'}</span>
</div> </div>
))} ))}
@@ -36,7 +36,7 @@ export default function CustomerCard({ customer: c, onClose, onEdit }) {
<div className="grid grid-cols-3 gap-2"> <div className="grid grid-cols-3 gap-2">
{[['visits', fmt.formatNumber(c.visit_count)], ['spent', fmt.formatMoney(c.total_spent)], ['perVisit', avg != null ? fmt.formatMoney(avg) : '—']].map(([k, v]) => ( {[['visits', fmt.formatNumber(c.visit_count)], ['spent', fmt.formatMoney(c.total_spent)], ['perVisit', avg != null ? fmt.formatMoney(avg) : '—']].map(([k, v]) => (
<div key={k} className="rounded-card bg-surface-2 p-3 grid gap-0.5 text-center"> <div key={k} className="rounded-card bg-surface-2 p-3 grid gap-0.5 text-center">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t(`customers.${k}`)}</span> <span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t(`customers.${k}`)}</span>
<span className="text-body font-semibold tabular-nums text-ink">{v}</span> <span className="text-body font-semibold tabular-nums text-ink">{v}</span>
</div> </div>
))} ))}
@@ -58,7 +58,7 @@ export default function CustomerCard({ customer: c, onClose, onEdit }) {
)} )}
{c.notes && <p className="rounded-card bg-warning-soft text-warning-ink p-3 text-label whitespace-pre-wrap">{c.notes}</p>} {c.notes && <p className="rounded-card bg-warning-soft text-warning-ink p-3 text-label whitespace-pre-wrap">{c.notes}</p>}
<section> <section>
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('customers.history')}</h3> <h3 className="text-overline font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('customers.history')}</h3>
{isPending ? <Spinner /> : !data?.length ? <p className="text-label text-ink-3">{t('customers.noVisits')}</p> : ( {isPending ? <Spinner /> : !data?.length ? <p className="text-label text-ink-3">{t('customers.noVisits')}</p> : (
<ul className="divide-y divide-line"> <ul className="divide-y divide-line">
{data.map(o => ( {data.map(o => (
@@ -6,10 +6,10 @@
import { useDeferredValue, useState } from 'react' import { useDeferredValue, useState } from 'react'
import { useMutation } from '@tanstack/react-query' import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { Pencil, Plus, Search, Trash2, Users } from 'lucide-react' import { Pencil, Plus, Trash2, Users } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Input, Spinner } from '@xenia/ui' import { Button, Dialog, EmptyState, IconButton, Page, PageHeader, SearchInput, Spinner, Toolbar } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import { Avatar } from '../overview/parts' import { Avatar } from '../overview/parts'
@@ -59,19 +59,12 @@ export default function CustomersPage() {
] ]
return ( return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="customers-page"> <Page testId="customers-page">
<div className="max-w-6xl mx-auto grid gap-4"> <PageHeader title={t('customers.title')} subtitle={t('customers.subtitle')}
<header className="flex flex-wrap items-center gap-3"> actions={<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'new' })} data-testid="customer-new">{t('customers.new')}</Button>} />
<div className="flex-1 min-w-0"> <Toolbar>
<h1 className="text-title font-semibold text-ink">{t('customers.title')}</h1> <SearchInput value={q} onChange={setQ} placeholder={t('customers.search')} data-testid="customer-search" />
<p className="text-label text-ink-2">{t('customers.subtitle')}</p> </Toolbar>
</div>
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'new' })} data-testid="customer-new">{t('customers.new')}</Button>
</header>
<div className="relative">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('customers.search')} aria-label={t('customers.search')} className="pl-9" data-testid="customer-search" />
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div> {isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !rows.length && !search ? <EmptyState icon={<Users size={28} />} title={t('customers.none')} description={t('customers.noneHint')} /> : !rows.length && !search ? <EmptyState icon={<Users size={28} />} title={t('customers.none')} description={t('customers.noneHint')} />
: ( : (
@@ -80,7 +73,6 @@ export default function CustomersPage() {
empty={t('customers.noMatch')} initialSort={{ key: 'name', dir: 'asc' }} /> empty={t('customers.noMatch')} initialSort={{ key: 'name', dir: 'asc' }} />
</Panel> </Panel>
)} )}
</div>
{(dialog?.kind === 'new' || dialog?.kind === 'edit') && <CustomerDialog customer={dialog.customer} onClose={close} onSaved={saved} />} {(dialog?.kind === 'new' || dialog?.kind === 'edit') && <CustomerDialog customer={dialog.customer} onClose={close} onSaved={saved} />}
{dialog?.kind === 'card' && <CustomerCard customer={dialog.customer} onClose={close} onEdit={() => setDialog({ kind: 'edit', customer: dialog.customer })} />} {dialog?.kind === 'card' && <CustomerCard customer={dialog.customer} onClose={close} onEdit={() => setDialog({ kind: 'edit', customer: dialog.customer })} />}
{dialog?.kind === 'remove' && ( {dialog?.kind === 'remove' && (
@@ -90,6 +82,6 @@ export default function CustomersPage() {
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.customer)}>{t('customers.removeYes')}</Button> <Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.customer)}>{t('customers.removeYes')}</Button>
</>} /> </>} />
)} )}
</div> </Page>
) )
} }
@@ -5,10 +5,10 @@
import { useState } from 'react' import { useState } from 'react'
import { useMutation } from '@tanstack/react-query' import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { BookUser, Pencil, Plus, Search, Trash2 } from 'lucide-react' import { BookUser, Pencil, Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Input, Select, Spinner } from '@xenia/ui' import { Button, Dialog, Dropdown, EmptyState, IconButton, Page, PageHeader, SearchInput, Spinner, Toolbar } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts' import { Pill } from '../overview/parts'
@@ -21,7 +21,7 @@ const TYPE_TONE = { supplier: 'accent', staff: 'success', utility: 'warning', ot
export default function ContactsPage() { export default function ContactsPage() {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const fmt = useFormat() const fmt = useFormat()
const [filter, setFilter] = useState({ type: '', q: '' }) const [filter, setFilter] = useState({ type: [], q: '' })
const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'remove', contact } const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'remove', contact }
const { data, isPending, refetch } = useLiveQuery({ queryKey: ['contacts'], queryFn: () => client.get('/api/contacts/').then(r => r.data), events: ['expenses.changed'] }) const { data, isPending, refetch } = useLiveQuery({ queryKey: ['contacts'], queryFn: () => client.get('/api/contacts/').then(r => r.data), events: ['expenses.changed'] })
const { data: expenses = [] } = useLiveQuery({ queryKey: ['expenses'], queryFn: () => client.get('/api/expenses/').then(r => r.data), events: ['expenses.changed'] }) const { data: expenses = [] } = useLiveQuery({ queryKey: ['expenses'], queryFn: () => client.get('/api/expenses/').then(r => r.data), events: ['expenses.changed'] })
@@ -57,23 +57,14 @@ export default function ContactsPage() {
] ]
return ( return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="contacts-page"> <Page testId="contacts-page">
<div className="max-w-6xl mx-auto grid gap-4"> <PageHeader title={t('finance.contacts.title')} subtitle={t('finance.contacts.subtitle', { count: all.length })}
<header className="flex flex-wrap items-center gap-3"> actions={<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'new' })} data-testid="contact-new">{t('finance.contacts.new')}</Button>} />
<div className="flex-1 min-w-0"> <Toolbar>
<h1 className="text-title font-semibold text-ink">{t('finance.contacts.title')}</h1> <SearchInput value={filter.q} onChange={v => set('q', v)} placeholder={t('finance.contacts.search')} />
<p className="text-label text-ink-2">{t('finance.contacts.subtitle', { count: all.length })}</p> <Dropdown multiple value={filter.type} onChange={v => set('type', v)} aria-label={t('finance.contacts.type')} allLabel={t('finance.contacts.allTypes')}
</div> options={CONTACT_TYPES.map(k => ({ value: k, label: t(`finance.contacts.types.${k}`) }))} />
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'new' })} data-testid="contact-new">{t('finance.contacts.new')}</Button> </Toolbar>
</header>
<div className="flex flex-wrap items-center gap-2">
<div className="relative flex-1 min-w-56">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={filter.q} onChange={e => set('q', e.target.value)} placeholder={t('finance.contacts.search')} aria-label={t('finance.contacts.search')} className="pl-9" />
</div>
<Select size="sm" value={filter.type} onChange={e => set('type', e.target.value)} aria-label={t('finance.contacts.type')}
options={[{ value: '', label: t('finance.contacts.allTypes') }, ...CONTACT_TYPES.map(k => ({ value: k, label: t(`finance.contacts.types.${k}`) }))]} />
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div> {isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !all.length ? <EmptyState icon={<BookUser size={28} />} title={t('finance.contacts.none')} description={t('finance.contacts.noneHint')} /> : !all.length ? <EmptyState icon={<BookUser size={28} />} title={t('finance.contacts.none')} description={t('finance.contacts.noneHint')} />
: ( : (
@@ -82,7 +73,6 @@ export default function ContactsPage() {
empty={t('finance.contacts.noMatch')} initialSort={{ key: 'name', dir: 'asc' }} /> empty={t('finance.contacts.noMatch')} initialSort={{ key: 'name', dir: 'asc' }} />
</Panel> </Panel>
)} )}
</div>
{(dialog?.kind === 'new' || dialog?.kind === 'edit') && <ContactDialog contact={dialog.contact} onClose={close} onSaved={saved} />} {(dialog?.kind === 'new' || dialog?.kind === 'edit') && <ContactDialog contact={dialog.contact} onClose={close} onSaved={saved} />}
{dialog?.kind === 'remove' && ( {dialog?.kind === 'remove' && (
<Dialog open size="sm" onClose={close} title={t('finance.contacts.removeTitle', { name: dialog.contact.name })} description={t('finance.contacts.removeBody')} <Dialog open size="sm" onClose={close} title={t('finance.contacts.removeTitle', { name: dialog.contact.name })} description={t('finance.contacts.removeBody')}
@@ -91,6 +81,6 @@ export default function ContactsPage() {
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.contact)}>{t('finance.contacts.removeYes')}</Button> <Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.contact)}>{t('finance.contacts.removeYes')}</Button>
</>} /> </>} />
)} )}
</div> </Page>
) )
} }
@@ -1,67 +1,197 @@
// A new expense or an existing one (plan step 6.13a): what it is, its category, the supplier // A new expense or an existing one (plan step 6.13a): what it is, its category, the supplier
// (from the supplier book; a new one can be added from here), the amount (comma or dot), the date // (from the supplier book; a new one can be added from here), the amount (comma or dot), the date
// it is due by and notes. The total can't be less than what was paid already. // it is due by and notes. The total can't be less than what was paid already.
import { useState } from 'react' // 2026-11-20: what it bought, line by line (quantity, price before VAT, VAT %; the lines make the
// total), and the documents kept with it (the invoice as a PDF, a photo of the receipt). Files
// picked for a new expense are uploaded once it is saved.
import { useRef, useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query' import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { FileText, Image as ImageIcon, Paperclip, Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Select, Textarea } from '@xenia/ui' import { Button, Dialog, Dropdown, Field, IconButton, Input, Select, Textarea, cx } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import ContactDialog from './ContactDialog' import ContactDialog from './ContactDialog'
import { CATEGORIES, expenseBody, expenseForm, expenseProblems } from './financeLogic' import { CATEGORIES, VAT_RATES, emptyLine, expenseBody, expenseForm, expenseProblems, lineMoney, linesTotal } from './financeLogic'
export default function ExpenseDialog({ expense, onClose, onSaved }) { const ACCEPT = 'application/pdf,image/jpeg,image/png,image/webp,image/heic,.heic'
export default function ExpenseDialog({ expense: initial, onClose, onSaved }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const fmt = useFormat() const fmt = useFormat()
const qc = useQueryClient() const qc = useQueryClient()
const [expense, setExpense] = useState(initial) // documents change it in place
const isNew = !expense const isNew = !expense
const [form, setForm] = useState(() => expenseForm(expense, fmt.venueDateKey)) const [form, setForm] = useState(() => expenseForm(initial, fmt.venueDateKey))
const [tried, setTried] = useState(false) const [tried, setTried] = useState(false)
const [addContact, setAddContact] = useState(false) const [addContact, setAddContact] = useState(false)
const [pending, setPending] = useState([]) // files picked for a new expense
const [uploading, setUploading] = useState(false)
const fileInput = useRef(null)
const { data: contacts = [] } = useLiveQuery({ queryKey: ['contacts'], queryFn: () => client.get('/api/contacts/').then(r => r.data), events: ['expenses.changed'] }) const { data: contacts = [] } = useLiveQuery({ queryKey: ['contacts'], queryFn: () => client.get('/api/contacts/').then(r => r.data), events: ['expenses.changed'] })
const set = (k, v) => setForm(f => ({ ...f, [k]: v })) const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const setLine = (i, k, v) => setForm(f => ({ ...f, lines: f.lines.map((l, j) => (j === i ? { ...l, [k]: v } : l)) }))
const paid = expense?.paid_amount ?? 0 const paid = expense?.paid_amount ?? 0
const wrong = expenseProblems(form, paid) const wrong = expenseProblems(form, paid)
const err = k => (tried && wrong.includes(k) ? t(`finance.exp.wrong.${k}`, { paid: fmt.formatMoney(paid) }) : undefined) const err = k => (tried && wrong.includes(k) ? t(`finance.exp.wrong.${k}`, { paid: fmt.formatMoney(paid) }) : undefined)
const hasLines = form.lines.length > 0
const sum = linesTotal(form.lines)
const upload = async (id, files) => {
let last = null
for (const f of files) {
const body = new FormData()
body.append('file', f)
try { last = (await client.post(`/api/expenses/${id}/documents`, body)).data } catch (e) { toast.error(`${f.name}: ${errorMessage(e, t)}`) }
}
return last
}
const save = useMutation({ const save = useMutation({
mutationFn: body => (isNew ? client.post('/api/expenses/', body) : client.put(`/api/expenses/${expense.id}`, body)), mutationFn: body => (isNew ? client.post('/api/expenses/', body) : client.put(`/api/expenses/${expense.id}`, body)),
onSuccess: () => { toast.success(t(isNew ? 'finance.exp.added' : 'finance.exp.saved', { what: form.description.trim() })); onSaved() }, onSuccess: async r => {
if (isNew && pending.length) await upload(r.data.id, pending)
toast.success(t(isNew ? 'finance.exp.added' : 'finance.exp.saved', { what: form.description.trim() }))
onSaved()
},
onError: e => toast.error(errorMessage(e, t)), onError: e => toast.error(errorMessage(e, t)),
}) })
const submit = () => { setTried(true); if (!wrong.length) save.mutate(expenseBody(form)) } const submit = () => { setTried(true); if (!wrong.length) save.mutate(expenseBody(form)) }
const pick = async files => {
const list = [...files]
if (!list.length) return
if (isNew) { setPending(p => [...p, ...list]); return }
setUploading(true)
const next = await upload(expense.id, list)
if (next) { setExpense(next); qc.invalidateQueries({ queryKey: ['expenses'] }) }
setUploading(false)
}
const removeDoc = async doc => {
try { setExpense((await client.delete(`/api/expenses/${expense.id}/documents/${doc.id}`)).data); qc.invalidateQueries({ queryKey: ['expenses'] }) } catch (e) { toast.error(errorMessage(e, t)) }
}
const openDoc = async doc => {
// fetched with the session (the address alone isn't enough), shown in a new tab
const tab = window.open('', '_blank')
try {
const blob = (await client.get(`/api/expenses/${expense.id}/documents/${doc.id}`, { responseType: 'blob' })).data
const url = URL.createObjectURL(blob)
if (tab) tab.location.href = url
setTimeout(() => URL.revokeObjectURL(url), 60_000)
} catch (e) { tab?.close(); toast.error(errorMessage(e, t)) }
}
// A supplier no longer in the book still shows on its expense // A supplier no longer in the book still shows on its expense
const options = [{ value: '', label: t('finance.exp.noSupplier') }, const options = [{ value: '', label: t('finance.exp.noSupplier') },
...contacts.map(c => ({ value: String(c.id), label: c.name })), ...contacts.map(c => ({ value: String(c.id), label: c.name })),
...(expense?.contact_id && !contacts.some(c => c.id === expense.contact_id) ? [{ value: String(expense.contact_id), label: expense.contact_name ?? '' }] : [])] ...(expense?.contact_id && !contacts.some(c => c.id === expense.contact_id) ? [{ value: String(expense.contact_id), label: expense.contact_name ?? '' }] : [])]
const docs = [...(expense?.documents ?? []).map(d => ({ ...d, saved: true })), ...pending.map((f, i) => ({ id: `p${i}`, filename: f.name, content_type: f.type, size: f.size, file: f }))]
return ( return (
<Dialog open size="lg" onClose={onClose} title={isNew ? t('finance.exp.newTitle') : expense.description} <Dialog open size="xl" onClose={onClose} title={isNew ? t('finance.exp.newTitle') : expense.description}
footer={<> footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button> <Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="expense-save">{isNew ? t('finance.exp.add') : t('finance.save')}</Button> <Button loading={save.isPending} onClick={submit} data-testid="expense-save">{isNew ? t('finance.exp.add') : t('finance.save')}</Button>
</>}> </>}>
<div className="grid gap-3" data-testid="expense-dialog"> <div className="grid gap-5" data-testid="expense-dialog">
<Field label={t('finance.exp.what')} required error={err('description')}> <Field label={t('finance.exp.what')} required error={err('description')}>
<Input value={form.description} autoFocus onChange={e => set('description', e.target.value)} placeholder={t('finance.exp.whatHint')} data-testid="expense-description" /> <Input value={form.description} autoFocus onChange={e => set('description', e.target.value)} placeholder={t('finance.exp.whatHint')} data-testid="expense-description" />
</Field> </Field>
<div className="grid gap-3 sm:grid-cols-2"> <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<Field label={t('finance.exp.category')}> <Field label={t('finance.exp.category')}>
<Select value={form.category} onChange={e => set('category', e.target.value)} data-testid="expense-category" <Select value={form.category} onChange={e => set('category', e.target.value)} data-testid="expense-category"
options={CATEGORIES.map(c => ({ value: c, label: t(`finance.categories.${c}`) }))} /> options={CATEGORIES.map(c => ({ value: c, label: t(`finance.categories.${c}`) }))} />
</Field> </Field>
<Field label={t('finance.exp.amount')} required error={err('total_amount') ?? err('below_paid')}>
<Input inputMode="decimal" value={form.total_amount} onChange={e => set('total_amount', e.target.value)} placeholder="0,00" data-testid="expense-amount" />
</Field>
<Field label={t('finance.exp.supplier')} hint={<button type="button" className="text-accent-ink hover:underline" onClick={() => setAddContact(true)}>{t('finance.exp.newSupplier')}</button>}> <Field label={t('finance.exp.supplier')} hint={<button type="button" className="text-accent-ink hover:underline" onClick={() => setAddContact(true)}>{t('finance.exp.newSupplier')}</button>}>
<Select value={form.contact_id} onChange={e => set('contact_id', e.target.value)} data-testid="expense-supplier" options={options} /> <Select value={form.contact_id} onChange={e => set('contact_id', e.target.value)} data-testid="expense-supplier" options={options} />
</Field> </Field>
<Field label={t('finance.exp.dueBy')} hint={t('finance.exp.dueByHint')}> <Field label={t('finance.exp.dueBy')} hint={t('finance.exp.dueByHint')}>
<Input type="date" value={form.due_date} onChange={e => set('due_date', e.target.value)} data-testid="expense-due-date" /> <Input type="date" value={form.due_date} onChange={e => set('due_date', e.target.value)} data-testid="expense-due-date" />
</Field> </Field>
<Field label={t('finance.exp.amount')} required hint={hasLines ? t('finance.exp.amountFromLines') : undefined} error={err('total_amount') ?? err('below_paid')}>
{hasLines
? <Input value={fmt.formatMoney(sum.total)} readOnly tabIndex={-1} data-testid="expense-amount" />
: <Input inputMode="decimal" value={form.total_amount} onChange={e => set('total_amount', e.target.value)} placeholder="0,00" data-testid="expense-amount" />}
</Field>
</div> </div>
{/* what it bought */}
<section className="grid gap-2" data-testid="expense-lines">
<div className="flex items-center gap-3">
<h3 className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('finance.exp.lines')}</h3>
<span className="flex-1 border-t border-line" aria-hidden="true" />
<Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => set('lines', [...form.lines, emptyLine()])} data-testid="expense-line-add">{t('finance.exp.addLine')}</Button>
</div>
{!hasLines ? <p className="text-label text-ink-3">{t('finance.exp.noLines')}</p> : (
<div className="rounded-card border border-line overflow-x-auto">
<table className="w-full text-label">
<thead className="bg-surface-2 text-ink-3">
<tr className="text-overline font-semibold uppercase tracking-wide">
<th className="px-3 py-2 text-left">{t('finance.exp.lineWhat')}</th>
<th className="px-2 py-2 text-right w-24">{t('finance.exp.lineQty')}</th>
<th className="px-2 py-2 text-right w-32">{t('finance.exp.linePrice')}</th>
<th className="px-2 py-2 text-right w-28">{t('finance.exp.lineVat')}</th>
<th className="px-3 py-2 text-right w-28">{t('finance.exp.lineTotal')}</th>
<th className="w-12" />
</tr>
</thead>
<tbody className="divide-y divide-line">
{form.lines.map((l, i) => {
const m = lineMoney(l)
const bad = tried && wrong.includes(`line.${i}`)
return (
<tr key={i} className={cx('align-middle', bad && 'bg-danger-soft')} data-testid="expense-line">
<td className="px-2 py-1.5"><Input size="sm" value={l.description} onChange={e => setLine(i, 'description', e.target.value)} aria-label={t('finance.exp.lineWhat')} data-testid="expense-line-what" /></td>
<td className="px-1 py-1.5"><Input size="sm" inputMode="decimal" className="text-right" value={l.quantity} onChange={e => setLine(i, 'quantity', e.target.value)} aria-label={t('finance.exp.lineQty')} data-testid="expense-line-qty" /></td>
<td className="px-1 py-1.5"><Input size="sm" inputMode="decimal" className="text-right" value={l.unit_price} placeholder="0,00" onChange={e => setLine(i, 'unit_price', e.target.value)} aria-label={t('finance.exp.linePrice')} data-testid="expense-line-price" /></td>
<td className="px-1 py-1.5">
<Dropdown size="sm" value={l.vat_rate} onChange={v => setLine(i, 'vat_rate', v)} aria-label={t('finance.exp.lineVat')} data-testid="expense-line-vat"
options={[...new Set([...VAT_RATES.map(String), l.vat_rate])].map(v => ({ value: v, label: `${v} %` }))} />
</td>
<td className="px-3 py-1.5 text-right tabular-nums font-medium text-ink">{fmt.formatMoney(m.total)}</td>
<td className="px-1 py-1.5 text-right">
<IconButton size="sm" variant="ghost" tone="danger" label={t('finance.exp.removeLine')} onClick={() => set('lines', form.lines.filter((_, j) => j !== i))}><Trash2 size={14} /></IconButton>
</td>
</tr>
)
})}
</tbody>
<tfoot className="bg-surface-2 text-ink-2">
<tr><td colSpan={4} className="px-3 py-1.5 text-right">{t('finance.exp.net')}</td><td className="px-3 py-1.5 text-right tabular-nums">{fmt.formatMoney(sum.net)}</td><td /></tr>
<tr><td colSpan={4} className="px-3 py-1.5 text-right">{t('finance.exp.vat')}</td><td className="px-3 py-1.5 text-right tabular-nums">{fmt.formatMoney(sum.vat)}</td><td /></tr>
<tr className="text-ink font-semibold"><td colSpan={4} className="px-3 py-2 text-right">{t('finance.exp.total')}</td><td className="px-3 py-2 text-right tabular-nums" data-testid="expense-lines-total">{fmt.formatMoney(sum.total)}</td><td /></tr>
</tfoot>
</table>
</div>
)}
</section>
{/* the invoice / receipt */}
<section className="grid gap-2" data-testid="expense-documents">
<div className="flex items-center gap-3">
<h3 className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('finance.exp.documents')}</h3>
<span className="flex-1 border-t border-line" aria-hidden="true" />
<Button size="sm" variant="secondary" icon={<Paperclip size={14} />} loading={uploading} onClick={() => fileInput.current?.click()} data-testid="expense-doc-add">{t('finance.exp.addDocument')}</Button>
<input ref={fileInput} type="file" accept={ACCEPT} multiple hidden onChange={e => { pick(e.target.files); e.target.value = '' }} data-testid="expense-doc-input" />
</div>
{docs.length === 0 ? <p className="text-label text-ink-3">{t('finance.exp.noDocuments')}</p> : (
<ul className="grid gap-2 sm:grid-cols-2">
{docs.map(d => (
<li key={d.id} className="flex items-center gap-3 px-3 py-2 rounded-card border border-line bg-surface" data-testid="expense-doc">
{d.content_type === 'application/pdf' ? <FileText size={18} className="text-danger-ink shrink-0" aria-hidden="true" /> : <ImageIcon size={18} className="text-info-ink shrink-0" aria-hidden="true" />}
<span className="flex-1 min-w-0 grid">
{d.saved
? <button type="button" className="text-left text-label font-medium text-accent-ink hover:underline truncate" onClick={() => openDoc(d)}>{d.filename}</button>
: <span className="text-label font-medium text-ink truncate">{d.filename}</span>}
<span className="text-caption text-ink-3">{d.saved ? `${fmt.formatDateTime(d.uploaded_at, 'datetimeShort')} · ` : `${t('finance.exp.uploadOnSave')} · `}{Math.max(1, Math.round(d.size / 1024))} KB</span>
</span>
<IconButton size="sm" variant="ghost" tone="danger" label={t('finance.exp.removeDocument', { name: d.filename })}
onClick={() => (d.saved ? removeDoc(d) : setPending(p => p.filter(f => f !== d.file)))}><Trash2 size={14} /></IconButton>
</li>
))}
</ul>
)}
</section>
<Field label={t('finance.notes')}> <Field label={t('finance.notes')}>
<Textarea rows={2} value={form.notes} onChange={e => set('notes', e.target.value)} /> <Textarea rows={2} value={form.notes} onChange={e => set('notes', e.target.value)} />
</Field> </Field>
@@ -5,10 +5,10 @@
import { useState } from 'react' import { useState } from 'react'
import { useMutation } from '@tanstack/react-query' import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { Banknote, Pencil, Plus, Receipt, Search, Trash2 } from 'lucide-react' import { Banknote, Pencil, Plus, Receipt, Trash2, Paperclip } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Input, Select, Spinner } from '@xenia/ui' import { Button, Dialog, Dropdown, EmptyState, IconButton, Page, PageHeader, SearchInput, Spinner, Toolbar } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts' import { Pill } from '../overview/parts'
@@ -20,7 +20,8 @@ import { CATEGORIES, STATUS_TONE, expenseTotals, filterExpenses, isLate } from '
export default function ExpensesPage() { export default function ExpensesPage() {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const fmt = useFormat() const fmt = useFormat()
const [filter, setFilter] = useState({ status: 'unpaid', category: '', q: '' }) // what's still to pay first: due + partly paid (= v1's "unpaid")
const [filter, setFilter] = useState({ status: ['due', 'partial'], category: [], q: '' })
const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'pay' | 'view' | 'delete', expense } const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'pay' | 'view' | 'delete', expense }
const { data, isPending, refetch } = useLiveQuery({ queryKey: ['expenses'], queryFn: () => client.get('/api/expenses/').then(r => r.data), events: ['expenses.changed'] }) const { data, isPending, refetch } = useLiveQuery({ queryKey: ['expenses'], queryFn: () => client.get('/api/expenses/').then(r => r.data), events: ['expenses.changed'] })
const all = data ?? [] const all = data ?? []
@@ -43,7 +44,8 @@ export default function ExpensesPage() {
const columns = [ const columns = [
{ key: 'description', label: t('finance.exp.what'), render: e => ( { key: 'description', label: t('finance.exp.what'), render: e => (
<span className="grid"> <span className="grid">
<span className="font-semibold text-ink">{e.description}</span> <span className="font-semibold text-ink flex items-center gap-1.5">{e.description}
{e.documents?.length > 0 && <Paperclip size={13} className="text-ink-3" aria-label={t('finance.exp.documents')} />}</span>
{e.contact_name && <span className="text-caption text-ink-2">{e.contact_name}</span>} {e.contact_name && <span className="text-caption text-ink-2">{e.contact_name}</span>}
</span>) }, </span>) },
{ key: 'category', label: t('finance.exp.category'), sort: e => cat(e.category), render: e => cat(e.category) }, { key: 'category', label: t('finance.exp.category'), sort: e => cat(e.category), render: e => cat(e.category) },
@@ -66,15 +68,9 @@ export default function ExpensesPage() {
] ]
return ( return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="expenses-page"> <Page testId="expenses-page">
<div className="max-w-6xl mx-auto grid gap-4"> <PageHeader title={t('finance.exp.title')} subtitle={t('finance.exp.subtitle')}
<header className="flex flex-wrap items-center gap-3"> actions={<Button icon={<Plus size={16} />} onClick={() => open('new')} data-testid="expense-new">{t('finance.exp.new')}</Button>} />
<div className="flex-1 min-w-0">
<h1 className="text-title font-semibold text-ink">{t('finance.exp.title')}</h1>
<p className="text-label text-ink-2">{t('finance.exp.subtitle')}</p>
</div>
<Button icon={<Plus size={16} />} onClick={() => open('new')} data-testid="expense-new">{t('finance.exp.new')}</Button>
</header>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]"> <div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('finance.exp.owed')} tone={owed.due ? 'danger' : 'success'} value={fmt.formatMoney(owed.due)} <Stat label={t('finance.exp.owed')} tone={owed.due ? 'danger' : 'success'} value={fmt.formatMoney(owed.due)}
@@ -84,17 +80,13 @@ export default function ExpensesPage() {
sub={t('finance.exp.shownSub', { paid: fmt.formatMoney(shown.paid), count: rows.length })} /> sub={t('finance.exp.shownSub', { paid: fmt.formatMoney(shown.paid), count: rows.length })} />
</div> </div>
<div className="flex flex-wrap items-center gap-2"> <Toolbar>
<div className="relative flex-1 min-w-56"> <SearchInput value={filter.q} onChange={v => set('q', v)} placeholder={t('finance.exp.search')} />
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" /> <Dropdown multiple value={filter.status} onChange={v => set('status', v)} aria-label={t('finance.exp.status')} data-testid="expenses-status" allLabel={t('finance.exp.all')}
<Input value={filter.q} onChange={e => set('q', e.target.value)} placeholder={t('finance.exp.search')} aria-label={t('finance.exp.search')} className="pl-9" /> options={['due', 'partial', 'paid'].map(s => ({ value: s, label: t(`finance.status.${s}`) }))} />
</div> <Dropdown multiple value={filter.category} onChange={v => set('category', v)} aria-label={t('finance.exp.category')} allLabel={t('finance.exp.allCategories')}
<Select size="sm" value={filter.status} onChange={e => set('status', e.target.value)} aria-label={t('finance.exp.status')} data-testid="expenses-status" options={CATEGORIES.map(c => ({ value: c, label: cat(c) }))} />
options={[{ value: '', label: t('finance.exp.all') }, { value: 'unpaid', label: t('finance.exp.unpaidOnly') }, </Toolbar>
...['due', 'partial', 'paid'].map(s => ({ value: s, label: t(`finance.status.${s}`) }))]} />
<Select size="sm" value={filter.category} onChange={e => set('category', e.target.value)} aria-label={t('finance.exp.category')}
options={[{ value: '', label: t('finance.exp.allCategories') }, ...CATEGORIES.map(c => ({ value: c, label: cat(c) }))]} />
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div> {isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !all.length ? <EmptyState icon={<Receipt size={28} />} title={t('finance.exp.none')} description={t('finance.exp.noneHint')} /> : !all.length ? <EmptyState icon={<Receipt size={28} />} title={t('finance.exp.none')} description={t('finance.exp.noneHint')} />
@@ -104,7 +96,6 @@ export default function ExpensesPage() {
initialSort={{ key: 'created_at', dir: 'desc' }} /> initialSort={{ key: 'created_at', dir: 'desc' }} />
</Panel> </Panel>
)} )}
</div>
{(dialog?.kind === 'new' || dialog?.kind === 'edit') && <ExpenseDialog expense={dialog.expense} onClose={close} onSaved={saved} />} {(dialog?.kind === 'new' || dialog?.kind === 'edit') && <ExpenseDialog expense={dialog.expense} onClose={close} onSaved={saved} />}
{dialog?.kind === 'pay' && <ExpensePayDialog expense={dialog.expense} onClose={close} onSaved={saved} />} {dialog?.kind === 'pay' && <ExpensePayDialog expense={dialog.expense} onClose={close} onSaved={saved} />}
@@ -120,7 +111,7 @@ export default function ExpensesPage() {
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.expense)} data-testid="expense-delete-confirm">{t('finance.exp.deleteYes')}</Button> <Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.expense)} data-testid="expense-delete-confirm">{t('finance.exp.deleteYes')}</Button>
</>} /> </>} />
)} )}
</div> </Page>
) )
} }
@@ -144,7 +135,7 @@ function ExpenseView({ expense: e, cat, onClose, onPay, onEdit }) {
</div> </div>
{e.due_date && <p className="text-label text-ink-2">{t('finance.exp.dueOn', { date: fmt.formatDate(e.due_date) })}</p>} {e.due_date && <p className="text-label text-ink-2">{t('finance.exp.dueOn', { date: fmt.formatDate(e.due_date) })}</p>}
{e.notes && <p className="text-label text-ink-2 whitespace-pre-wrap">{e.notes}</p>} {e.notes && <p className="text-label text-ink-2 whitespace-pre-wrap">{e.notes}</p>}
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('finance.exp.payments')}</h3> <h3 className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('finance.exp.payments')}</h3>
{e.payments?.length ? ( {e.payments?.length ? (
<ul className="divide-y divide-line"> <ul className="divide-y divide-line">
{e.payments.map(p => ( {e.payments.map(p => (
@@ -163,7 +154,7 @@ function ExpenseView({ expense: e, cat, onClose, onPay, onEdit }) {
function Figure({ label, value, tone }) { function Figure({ label, value, tone }) {
return ( return (
<div className="rounded-card bg-surface-2 p-3 grid gap-0.5 text-center"> <div className="rounded-card bg-surface-2 p-3 grid gap-0.5 text-center">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{label}</span> <span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{label}</span>
<span className={`text-body font-semibold tabular-nums ${tone ?? 'text-ink'}`}>{value}</span> <span className={`text-body font-semibold tabular-nums ${tone ?? 'text-ink'}`}>{value}</span>
</div> </div>
) )
@@ -9,7 +9,7 @@ import toast from 'react-hot-toast'
import { Banknote, CheckCircle2, ChevronDown, CreditCard, HandHeart, Search } from 'lucide-react' import { Banknote, CheckCircle2, ChevronDown, CreditCard, HandHeart, Search } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, Input, Spinner, cx } from '@xenia/ui' import { Button, EmptyState, Input, Page, Spinner, cx } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts' import { Pill } from '../overview/parts'
@@ -40,8 +40,7 @@ export default function TabsPage() {
}) })
return ( return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="tabs-page"> <Page testId="tabs-page">
<div className="max-w-4xl mx-auto grid gap-4">
<header> <header>
<h1 className="text-title font-semibold text-ink">{t('finance.tabs.title')}</h1> <h1 className="text-title font-semibold text-ink">{t('finance.tabs.title')}</h1>
<p className="text-label text-ink-2">{t('finance.tabs.subtitle')}</p> <p className="text-label text-ink-2">{t('finance.tabs.subtitle')}</p>
@@ -75,9 +74,8 @@ export default function TabsPage() {
))} ))}
</ul> </ul>
)} )}
</div>
<TabDialogs dialog={tabNow && !openQ.isFetching ? { kind: dialog.kind, tab: tabNow } : null} onClose={() => setDialog(null)} onSaved={() => { setDialog(null); refresh() }} /> <TabDialogs dialog={tabNow && !openQ.isFetching ? { kind: dialog.kind, tab: tabNow } : null} onClose={() => setDialog(null)} onSaved={() => { setDialog(null); refresh() }} />
</div> </Page>
) )
} }
@@ -109,15 +107,15 @@ function TabCard({ tab, open, onToggle, onPay, onForgive, onClose, closing }) {
<div className="border-t border-line"> <div className="border-t border-line">
<div className="grid grid-cols-3 divide-x divide-line bg-surface-2 text-center"> <div className="grid grid-cols-3 divide-x divide-line bg-surface-2 text-center">
{[['charged', tab.total_charged, 'text-ink'], ['paid', tab.total_paid, 'text-success-ink'], ['balance', tab.balance, tab.balance > 0.005 ? 'text-danger-ink' : 'text-ink']].map(([k, v, tone]) => ( {[['charged', tab.total_charged, 'text-ink'], ['paid', tab.total_paid, 'text-success-ink'], ['balance', tab.balance, tab.balance > 0.005 ? 'text-danger-ink' : 'text-ink']].map(([k, v, tone]) => (
<span key={k} className="p-2 grid"> <span key={k} className="px-card py-card-y grid gap-1">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t(`finance.tabs.${k}`)}</span> <span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t(`finance.tabs.${k}`)}</span>
<span className={cx('text-body font-semibold tabular-nums', tone)}>{fmt.formatMoney(v)}</span> <span className={cx('text-heading font-semibold tabular-nums', tone)}>{fmt.formatMoney(v)}</span>
</span> </span>
))} ))}
</div> </div>
<div className="grid gap-3 p-4 sm:grid-cols-2"> <div className="grid gap-x-10 gap-y-6 p-card sm:grid-cols-2">
<section> <section>
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('finance.tabs.charges')}</h3> <h3 className="text-overline font-semibold uppercase tracking-wide text-ink-3 mb-2">{t('finance.tabs.charges')}</h3>
{tab.entries.length ? ( {tab.entries.length ? (
<ul className="divide-y divide-line text-label"> <ul className="divide-y divide-line text-label">
{tab.entries.map(e => ( {tab.entries.map(e => (
@@ -133,7 +131,7 @@ function TabCard({ tab, open, onToggle, onPay, onForgive, onClose, closing }) {
) : <p className="text-label text-ink-3">{t('finance.tabs.noCharges')}</p>} ) : <p className="text-label text-ink-3">{t('finance.tabs.noCharges')}</p>}
</section> </section>
<section> <section>
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('finance.tabs.payments')}</h3> <h3 className="text-overline font-semibold uppercase tracking-wide text-ink-3 mb-2">{t('finance.tabs.payments')}</h3>
{tab.payments.length ? ( {tab.payments.length ? (
<ul className="divide-y divide-line text-label"> <ul className="divide-y divide-line text-label">
{tab.payments.map(p => ( {tab.payments.map(p => (
@@ -149,7 +147,7 @@ function TabCard({ tab, open, onToggle, onPay, onForgive, onClose, closing }) {
) : <p className="text-label text-ink-3">{t('finance.tabs.noPayments')}</p>} ) : <p className="text-label text-ink-3">{t('finance.tabs.noPayments')}</p>}
</section> </section>
</div> </div>
{tab.status !== 'open' && tab.notes && <p className="px-4 pb-3 text-label text-ink-2">{tab.notes}</p>} {tab.status !== 'open' && tab.notes && <p className="px-card pb-card-y text-label text-ink-2">{tab.notes}</p>}
{(can.pay || can.close || can.forgive) && ( {(can.pay || can.close || can.forgive) && (
<div className="flex flex-wrap gap-2 px-4 pb-4"> <div className="flex flex-wrap gap-2 px-4 pb-4">
{can.pay && <Button icon={<Banknote size={15} />} onClick={onPay} data-testid="tab-pay">{t('finance.tabs.pay')}</Button>} {can.pay && <Button icon={<Banknote size={15} />} onClick={onPay} data-testid="tab-pay">{t('finance.tabs.pay')}</Button>}
@@ -22,25 +22,60 @@ export function expenseForm(e, dateKey = d => d) {
description: e?.description ?? '', category: e?.category ?? 'supplier', description: e?.description ?? '', category: e?.category ?? 'supplier',
contact_id: e?.contact_id ? String(e.contact_id) : '', total_amount: e ? String(e.total_amount) : '', contact_id: e?.contact_id ? String(e.contact_id) : '', total_amount: e ? String(e.total_amount) : '',
due_date: e?.due_date ? dateKey(e.due_date) : '', notes: e?.notes ?? '', due_date: e?.due_date ? dateKey(e.due_date) : '', notes: e?.notes ?? '',
lines: (e?.lines ?? []).map(l => ({ description: l.description, quantity: String(l.quantity), unit_price: String(l.unit_price), vat_rate: String(l.vat_rate) })),
} }
} }
/** Which fields are wrong: description, total_amount (none, zero, or less than what was paid). */ // ── An expense's lines (2026-11-20): what it bought; the lines make its total ──
/** Greek VAT rates offered for a line (another one can be typed). */
export const VAT_RATES = [24, 13, 6, 0]
/** An empty line (VAT 24 %, the usual rate). */
export const emptyLine = () => ({ description: '', quantity: '1', unit_price: '', vat_rate: '24' })
const qty = text => parseNumber(String(text ?? ''), { decimals: 3, allowNegative: false })
const halfUp = v => Math.round((v + Number.EPSILON) * 100) / 100
/** A line's money as the backend counts it (routers/expenses.py): net = quantity × price before
* VAT, VAT = net × rate (each rounded half up to the cent), total = net + VAT. */
export function lineMoney(line) {
const net = halfUp((qty(line.quantity) || 0) * (money(line.unit_price) || 0))
const vat = halfUp(net * (qty(line.vat_rate) || 0) / 100)
return { net, vat, total: halfUp(net + vat) }
}
/** The lines added up: { net, vat, total }. */
export function linesTotal(lines = []) {
return lines.map(lineMoney).reduce((a, m) => ({ net: halfUp(a.net + m.net), vat: halfUp(a.vat + m.vat), total: halfUp(a.total + m.total) }),
{ net: 0, vat: 0, total: 0 })
}
/** Which fields are wrong: description, total_amount (none, zero, or less than what was paid);
* with lines: line.<i> (no description, no quantity, no price) and the total is the lines'. */
export function expenseProblems(form, paid = 0) { export function expenseProblems(form, paid = 0) {
const out = [] const out = []
if (!form.description.trim()) out.push('description') if (!form.description.trim()) out.push('description')
const total = money(form.total_amount) const lines = form.lines ?? []
lines.forEach((l, i) => {
if (!l.description.trim() || !(qty(l.quantity) > 0) || money(l.unit_price) == null) out.push(`line.${i}`)
})
const total = lines.length ? linesTotal(lines).total : money(form.total_amount)
if (!(total > 0)) out.push('total_amount') if (!(total > 0)) out.push('total_amount')
else if (cents(total) < cents(paid)) out.push('below_paid') else if (cents(total) < cents(paid)) out.push('below_paid')
return out return out
} }
/** What the API takes. `due_date` is the venue date picked ('' clears it). */ /** What the API takes. `due_date` is the venue date picked ('' clears it). With lines, the
* backend makes the total from them; `lines: []` removes them (the typed total counts). */
export function expenseBody(form) { export function expenseBody(form) {
const lines = (form.lines ?? []).map(l => ({ description: l.description.trim(), quantity: qty(l.quantity),
unit_price: money(l.unit_price), vat_rate: qty(l.vat_rate) || 0 }))
return { return {
description: form.description.trim(), category: form.category, description: form.description.trim(), category: form.category,
contact_id: form.contact_id ? Number(form.contact_id) : null, contact_id: form.contact_id ? Number(form.contact_id) : null,
total_amount: money(form.total_amount), total_amount: lines.length ? null : money(form.total_amount),
lines,
due_date: form.due_date || null, notes: form.notes.trim() || null, due_date: form.due_date || null, notes: form.notes.trim() || null,
} }
} }
@@ -57,10 +92,15 @@ export function isLate(expense, today, dateKey) {
} }
/** The page's list after its filters: status ('' | 'unpaid' | due | partial | paid), category, text. */ /** The page's list after its filters: status ('' | 'unpaid' | due | partial | paid), category, text. */
/** A filter's chosen values: a list (the toolbars' multi-selects, 2026-11-20), one value, or none = all. */
const picked = v => (Array.isArray(v) ? v : v ? [v] : [])
export function filterExpenses(list, { status = '', category = '', q = '' } = {}) { export function filterExpenses(list, { status = '', category = '', q = '' } = {}) {
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean) const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean)
return list.filter(e => (!status || (status === 'unpaid' ? e.status !== 'paid' : e.status === status)) const statuses = picked(status)
&& (!category || e.category === category) const categories = picked(category)
return list.filter(e => (!statuses.length || statuses.some(s => (s === 'unpaid' ? e.status !== 'paid' : e.status === s)))
&& (!categories.length || categories.includes(e.category))
&& words.every(w => `${e.description} ${e.contact_name ?? ''} ${e.notes ?? ''}`.toLowerCase().includes(w))) && words.every(w => `${e.description} ${e.contact_name ?? ''} ${e.notes ?? ''}`.toLowerCase().includes(w)))
} }
@@ -107,7 +147,8 @@ export function contactBody(form) {
export function filterContacts(list, { type = '', q = '' } = {}) { export function filterContacts(list, { type = '', q = '' } = {}) {
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean) const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean)
return list.filter(c => (!type || c.type === type) const types = picked(type)
return list.filter(c => (!types.length || types.includes(c.type))
&& words.every(w => `${c.name} ${c.phone ?? ''} ${c.email ?? ''} ${c.notes ?? ''}`.toLowerCase().includes(w))) && words.every(w => `${c.name} ${c.phone ?? ''} ${c.email ?? ''} ${c.notes ?? ''}`.toLowerCase().includes(w)))
} }
+214 -51
View File
@@ -1,45 +1,88 @@
// One floor plan's editor (plan step 6.8, D-31). Drag tables and things on the floor; the panel // One floor plan's editor (plan step 6.8, D-31). Drag tables and things on the floor; the panel
// on the right edits what's selected (shape, seats, size, rotation, text), adds the tables that // on the right edits what's selected (shape, seats, size, rotation, text), adds the tables that
// aren't on the plan and walls / the bar / labels / areas, and holds the plan's settings: name, // aren't on the plan and walls / the bar / labels / areas, and holds the plan's settings: name,
// zone, size, the grid (snap on / off and its size), the floor's shape (drag its corners; add or // zone, size, a background picture. The toolbar over both: the grid (on / off and its resolution),
// remove corners) and a background picture from the media library. Arrow keys move the selected // "Edit the floor's shape", fit the width or the whole plan, undo, save.
// thing (a grid cell, or 5; Shift: 1), Delete takes it off, Escape lets go. Nothing is saved // The floor's shape (2026-11-20): drag a corner; on an edge a "+" shows where a click adds a
// until "Save"; then every app's map changes at once. // corner; resting on a corner shows a bubble to remove it (a floor keeps at least 3). An area
import { useMemo, useRef, useState } from 'react' // (2026-11-20) is resized by the handles on its sides and corners, and has a colour (pastel, see-
// through); when tables cover its name, the name shows in its corner too.
// 2026-11-21: the "+" on an edge hides near a corner (there the corner's bubble removes it);
// minus / fit width / whole plan / plus; "Edit the floor's shape" is a button that turns into
// "Save shape" (saves the shape and the floor's size at once, nothing else); every unrotated table
// or thing has resize handles, and sizes are in grid cells (half cells), so they follow the grid
// resolution picked; a wall's thickness in steps.
// Arrow keys move the selected thing (a grid cell, or 5; Shift: 1), Delete takes it off, Escape
// lets go. Nothing is saved until "Save"; then every app's map changes at once.
import { useLayoutEffect, useMemo, useRef, useState } from 'react'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { RotateCcw, RotateCw, Save, Trash2, Undo2 } from 'lucide-react' import { Check, Minus, PenTool, Plus, RotateCcw, RotateCw, Save, Trash2, Undo2 } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { import {
Floor, GRID_SIZES, ITEM_KINDS, Item, SHAPES, TableShape, addCorner, defaultSize, moveCorner, moveTo, outlineOf, removeCorner, toPlan, AREA_COLOURS, Floor, GRID_LEVELS, ITEM_KINDS, Item, SHAPES, TableShape, addCornerAt, coveredAreas, defaultSize, moveCorner, moveTo,
nearestEdge, outlineOf, removeCorner, resizeBox, toPlan,
} from '@xenia/floorplan' } from '@xenia/floorplan'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, Input, Select, Switch, cx } from '@xenia/ui' import { Button, Dialog, Dropdown, Field, IconButton, Input, Segmented, Stepper, Switch, cx } from '@xenia/ui'
import MediaField from '../media/MediaField' import MediaField from '../media/MediaField'
import * as api from './floorApi' import * as api from './floorApi'
import { addItem, addable, find, fitOutline, layoutBody, layoutOf, nudge, placeTable, planBody, remove, resize, rotate, sameLayout, update } from './editorLogic' import { WALL_THICKNESS, addItem, addable, cellOf, find, fitOutline, layoutBody, layoutOf, nudge, placeTable, planBody, remove, resizeCells, rotate, sameLayout, toCells, update } from './editorLogic'
const PAD = 30 // room around the floor for the corner handles const PAD = 30 // room around the floor for the corner handles
const HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']
const CURSOR = { n: 'ns-resize', s: 'ns-resize', e: 'ew-resize', w: 'ew-resize', nw: 'nwse-resize', se: 'nwse-resize', ne: 'nesw-resize', sw: 'nesw-resize' }
/** The size of an element, kept up to date. */
function useSize(ref) {
const [size, setSize] = useState({ width: 0, height: 0 })
useLayoutEffect(() => {
const el = ref.current
if (!el) return undefined
const ro = new ResizeObserver(([e]) => setSize({ width: e.contentRect.width, height: e.contentRect.height }))
ro.observe(el)
return () => ro.disconnect()
}, [ref])
return size
}
export default function FloorEditor({ plan: saved, data, groups, onSaved, onDeleted }) { export default function FloorEditor({ plan: saved, data, groups, onSaved, onDeleted }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const initial = useMemo(() => layoutOf(data, saved.id), [data, saved.id]) const initial = useMemo(() => layoutOf(data, saved.id), [data, saved.id])
const [layout, setLayout] = useState(initial) const [layout, setLayout] = useState(initial)
const [base, setBase] = useState(saved) // the plan as saved (a saved shape updates it)
const [form, setForm] = useState(() => ({ ...saved })) const [form, setForm] = useState(() => ({ ...saved }))
const [sel, setSel] = useState(null) // {type: 'table'|'item', id} | {type: 'corner', index} const [sel, setSel] = useState(null) // {type: 'table'|'item', id} | {type: 'corner', index}
const [shapeMode, setShapeMode] = useState(false) const [shapeMode, setShapeMode] = useState(false)
const [newShape, setNewShape] = useState('square') const [newShape, setNewShape] = useState('square')
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [deleting, setDeleting] = useState(false) const [deleting, setDeleting] = useState(false)
const [fit, setFit] = useState('width') // 'width' | 'all'
const [zoom, setZoom] = useState(null) // a scale picked with − / + (null: the fit)
const [shapeBusy, setShapeBusy] = useState(false)
const [edgeHover, setEdgeHover] = useState(null) // where a click on the edge adds a corner
const [cornerTip, setCornerTip] = useState(null) // the corner showing its "remove" bubble
const tipTimer = useRef(null)
const svg = useRef(null) const svg = useRef(null)
const box = useRef(null)
const drag = useRef(null) const drag = useRef(null)
const size = useSize(box)
const plan = form // the preview follows the unsaved settings const plan = form // the preview follows the unsaved settings
const dirtySettings = JSON.stringify(planBody(form)) !== JSON.stringify(planBody(saved)) const dirtySettings = JSON.stringify(planBody(form)) !== JSON.stringify(planBody(base))
const dirty = dirtySettings || !sameLayout(layout, initial) const dirty = dirtySettings || !sameLayout(layout, initial)
const selected = sel && sel.type !== 'corner' ? find(layout, sel) : null const selected = sel && sel.type !== 'corner' ? find(layout, sel) : null
const corners = outlineOf(plan) const corners = outlineOf(plan)
const setF = (k, v) => setForm(f => ({ ...f, [k]: v })) const setF = (k, v) => setForm(f => ({ ...f, [k]: v }))
const { own, other } = addable(data, plan, layout) const { own, other } = addable(data, plan, layout)
const covered = coveredAreas(layout.items, layout.tables)
// the scale: the plan (and its margin) fitted to the width, or whole in the box
const vbW = plan.width + 2 * PAD
const vbH = plan.height + 2 * PAD
const fitScale = size.width ? (fit === 'all' && size.height ? Math.min(size.width / vbW, size.height / vbH) : size.width / vbW) : 1
const scale = zoom ?? fitScale
const zoomBy = f => setZoom(Math.min(4, Math.max(0.1, scale * f)))
const r = Math.max(8, 9 / scale) // a handle's size on screen ≈ 18 px
const point = e => toPlan(svg.current, e.clientX, e.clientY) const point = e => toPlan(svg.current, e.clientX, e.clientY)
const start = (e, target) => { const start = (e, target) => {
@@ -49,6 +92,8 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
if (target.type === 'corner') { if (target.type === 'corner') {
setSel(target) setSel(target)
drag.current = { target } drag.current = { target }
} else if (target.handle) {
drag.current = { target }
} else { } else {
const thing = find(layout, target) const thing = find(layout, target)
setSel(target) setSel(target)
@@ -58,12 +103,24 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
} }
const move = e => { const move = e => {
const d = drag.current const d = drag.current
if (!d) return
const [px, py] = point(e) const [px, py] = point(e)
if (!d) {
if (shapeMode) {
// near a corner there is no "+": that corner's bubble removes it
const nearCorner = corners.some(([x, y]) => Math.hypot(x - px, y - py) < r * 3)
const n = nearCorner ? null : nearestEdge(corners, [px, py])
setEdgeHover(n && n.d < 14 / scale ? n : null)
}
return
}
if (d.target.type === 'corner') { if (d.target.type === 'corner') {
setForm(f => ({ ...f, outline: moveCorner(outlineOf(f), d.target.index, px, py, f) })) setForm(f => ({ ...f, outline: moveCorner(outlineOf(f), d.target.index, px, py, f) }))
return return
} }
if (d.target.handle) {
setLayout(l => update(l, d.target, resizeBox(find(l, d.target), d.target.handle, px, py, plan, cellOf(plan) / 2)))
return
}
setLayout(l => { setLayout(l => {
const thing = find(l, d.target) const thing = find(l, d.target)
if (!thing) return l if (!thing) return l
@@ -72,6 +129,17 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
}) })
} }
const end = () => { drag.current = null } const end = () => { drag.current = null }
const down = e => {
if (shapeMode && edgeHover) {
// a click on an edge adds a corner there and starts dragging it
const index = edgeHover.index + 1
setForm(f => ({ ...f, outline: addCornerAt(outlineOf(f), edgeHover.index, edgeHover.x, edgeHover.y, f) }))
setEdgeHover(null)
start(e, { type: 'corner', index })
return
}
setSel(null)
}
const keys = e => { const keys = e => {
if (!sel || sel.type === 'corner') return if (!sel || sel.type === 'corner') return
const dirs = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] } const dirs = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
@@ -79,6 +147,9 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
else if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); setLayout(l => remove(l, sel)); setSel(null) } else if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); setLayout(l => remove(l, sel)); setSel(null) }
else if (e.key === 'Escape') setSel(null) else if (e.key === 'Escape') setSel(null)
} }
const showTip = i => { clearTimeout(tipTimer.current); tipTimer.current = setTimeout(() => setCornerTip(i), 600) }
const hideTip = () => { clearTimeout(tipTimer.current); tipTimer.current = setTimeout(() => setCornerTip(null), 500) }
const keepTip = () => clearTimeout(tipTimer.current)
const save = async () => { const save = async () => {
setBusy(true) setBusy(true)
@@ -89,34 +160,68 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
onSaved() onSaved()
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) } } catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
} }
const enterShape = () => { setShapeMode(true); setSel(null); setEdgeHover(null); setCornerTip(null) }
const leaveShape = () => { setShapeMode(false); setEdgeHover(null); setCornerTip(null); setSel(null) }
// "Save shape": the floor's shape and size are saved at once; the rest waits for "Save"
const saveShape = async () => {
const shape = { outline: form.outline ?? null, width: form.width, height: form.height }
if (JSON.stringify(planBody({ ...base, ...shape })) !== JSON.stringify(planBody(base))) {
setShapeBusy(true)
try {
await api.savePlan(saved.id, planBody({ ...base, ...shape }))
setBase(b => ({ ...b, ...shape }))
toast.success(t('floor.shapeSaved'))
} catch (err) { toast.error(errorMessage(err, t)); setShapeBusy(false); return }
setShapeBusy(false)
}
leaveShape()
}
const zoneName = id => groups.find(g => g.id === id)?.name ?? t('floor.noZone') const zoneName = id => groups.find(g => g.id === id)?.name ?? t('floor.noZone')
const gridOptions = [...GRID_LEVELS.map(([k, v]) => ({ value: v, label: t(`floor.gridLevels.${k}`), hint: t('floor.gridCell', { size: v }) })),
...(GRID_LEVELS.some(([, v]) => v === form.grid_size) ? [] : [{ value: form.grid_size, label: t('floor.gridCell', { size: form.grid_size }) }])]
const resizable = selected && !shapeMode && Math.round(selected.rotation || 0) % 180 === 0
const handles = resizable && selected.kind === 'wall' ? ['e', 'w'] : HANDLES
return ( return (
<div className="grid gap-4 lg:grid-cols-[1fr_18rem] items-start" data-testid="floor-editor" data-plan={saved.id}> <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_19rem] items-start" data-testid="floor-editor" data-plan={saved.id}>
<div className="grid gap-3 content-start min-w-0"> {/* the toolbar, over the map and the panels */}
<div className="flex flex-wrap items-center gap-2"> <div className="lg:col-span-2 flex flex-wrap items-center gap-x-4 gap-y-2 px-card py-card-y rounded-card border border-line bg-surface shadow-raised">
<h2 className="text-body-lg font-semibold text-ink mr-auto">{form.name || saved.name}</h2> <h2 className="text-body-lg font-semibold text-ink">{form.name || saved.name}</h2>
{dirty && <span className="px-2 py-0.5 rounded-full bg-warning-soft text-warning-ink text-caption font-medium" data-testid="floor-dirty">{t('floor.unsaved')}</span>} {dirty && <span className="px-2 py-0.5 rounded-full bg-warning-soft text-warning-ink text-caption font-medium" data-testid="floor-dirty">{t('floor.unsaved')}</span>}
<Button variant="secondary" size="sm" icon={<Undo2 size={16} />} disabled={!dirty || busy} <span className="flex-1" />
onClick={() => { setLayout(initial); setForm({ ...saved }); setSel(null) }}>{t('floor.undoAll')}</Button>
<Button size="sm" icon={<Save size={16} />} loading={busy} disabled={!dirty || !form.name.trim()} onClick={save} data-testid="floor-save">{t('floor.save')}</Button>
</div>
<div className="flex flex-wrap items-center gap-3 text-label text-ink-2">
<Switch checked={!!form.grid_on} onChange={v => setF('grid_on', v)} label={t('floor.grid')} data-testid="floor-grid" /> <Switch checked={!!form.grid_on} onChange={v => setF('grid_on', v)} label={t('floor.grid')} data-testid="floor-grid" />
{form.grid_on && ( {form.grid_on && (
<Select size="sm" value={String(form.grid_size)} onChange={e => setF('grid_size', Number(e.target.value))} aria-label={t('floor.gridSize')} <Dropdown size="sm" className="w-44" value={form.grid_size} onChange={v => setF('grid_size', v)} aria-label={t('floor.gridSize')} data-testid="floor-grid-size" options={gridOptions} />
options={[...new Set([...GRID_SIZES, form.grid_size])].sort((a, b) => a - b).map(v => ({ value: String(v), label: t('floor.gridCell', { size: v }) }))} />
)} )}
<Switch checked={shapeMode} onChange={v => { setShapeMode(v); setSel(null) }} label={t('floor.editShape')} data-testid="floor-shape-mode" /> {shapeMode ? (
<span className="flex items-center gap-2">
<Button size="sm" variant="ghost" disabled={shapeBusy} onClick={() => { setF('outline', base.outline ?? null); leaveShape() }} data-testid="floor-shape-cancel">{t('floor.cancel')}</Button>
<Button size="sm" icon={<Check size={16} />} loading={shapeBusy} onClick={saveShape} data-testid="floor-shape-save">{t('floor.saveShape')}</Button>
</span>
) : (
<Button size="sm" variant="secondary" icon={<PenTool size={16} />} onClick={enterShape} data-testid="floor-shape-mode">{t('floor.editShape')}</Button>
)}
<span className="flex items-center gap-1">
<IconButton size="sm" variant="secondary" label={t('floor.zoomOut')} onClick={() => zoomBy(1 / 1.25)} data-testid="floor-zoom-out"><Minus size={16} /></IconButton>
<Segmented size="sm" value={zoom == null ? fit : null} onChange={v => { setFit(v); setZoom(null) }} aria-label={t('floor.fit')}
options={[{ value: 'width', label: t('floor.fitWidth'), testId: 'floor-fit-width' }, { value: 'all', label: t('floor.fitAll'), testId: 'floor-fit-all' }]} />
<IconButton size="sm" variant="secondary" label={t('floor.zoomIn')} onClick={() => zoomBy(1.25)} data-testid="floor-zoom-in"><Plus size={16} /></IconButton>
</span>
<Button variant="secondary" size="sm" icon={<Undo2 size={16} />} disabled={!dirty || busy}
onClick={() => { setLayout(initial); setForm({ ...base }); setSel(null) }}>{t('floor.undoAll')}</Button>
<Button size="sm" icon={<Save size={16} />} loading={busy} disabled={!dirty || !form.name.trim()} onClick={save} data-testid="floor-save">{t('floor.save')}</Button>
</div> </div>
{shapeMode && <p className="text-caption text-ink-2">{t('floor.shapeHint')}</p>}
<div className="rounded-card border border-line bg-canvas overflow-auto max-h-[70vh]"> <div className="grid gap-2 content-start min-w-0">
<svg ref={svg} viewBox={`${-PAD} ${-PAD} ${plan.width + 2 * PAD} ${plan.height + 2 * PAD}`} tabIndex={0} onKeyDown={keys} role="application" aria-label={t('floor.canvas')} <div ref={box} className={cx('rounded-card border border-line bg-canvas overflow-auto', fit === 'all' || zoom != null ? 'h-[calc(100dvh-17rem)] min-h-[22rem]' : 'max-h-[calc(100dvh-17rem)]')}
className="block w-full h-auto touch-none select-none outline-none focus-visible:ring-2 focus-visible:ring-[var(--x-accent)]" style={{ scrollbarGutter: 'stable' }}>
onPointerMove={move} onPointerUp={end} onPointerCancel={end} onPointerDown={() => setSel(null)} data-testid="floor-canvas"> <svg ref={svg} viewBox={`${-PAD} ${-PAD} ${vbW} ${vbH}`} tabIndex={0} onKeyDown={keys} role="application" aria-label={t('floor.canvas')}
width={Math.max(1, vbW * scale)} height={Math.max(1, vbH * scale)}
className={cx('block mx-auto touch-none select-none outline-none focus-visible:ring-2 focus-visible:ring-[var(--x-accent)]', shapeMode && edgeHover && 'cursor-copy')}
onPointerMove={move} onPointerUp={end} onPointerCancel={end} onPointerDown={down} onPointerLeave={() => setEdgeHover(null)} data-testid="floor-canvas">
<Floor plan={plan} showGrid={!!plan.grid_on} /> <Floor plan={plan} showGrid={!!plan.grid_on} />
{layout.items.map(i => ( {layout.items.map(i => (
<Item key={i.key} item={i} label={t('floor.kinds.bar')} selected={sel?.type === 'item' && sel.id === i.key} <Item key={i.key} item={i} label={t('floor.kinds.bar')} selected={sel?.type === 'item' && sel.id === i.key} corner={covered.has(i.key)}
style={{ cursor: shapeMode ? 'default' : 'move' }} pointerEvents={shapeMode ? 'none' : undefined} style={{ cursor: shapeMode ? 'default' : 'move' }} pointerEvents={shapeMode ? 'none' : undefined}
onPointerDown={e => start(e, { type: 'item', id: i.key })} data-testid="floor-item" data-kind={i.kind} /> onPointerDown={e => start(e, { type: 'item', id: i.key })} data-testid="floor-item" data-kind={i.kind} />
))} ))}
@@ -125,27 +230,55 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
style={{ cursor: shapeMode ? 'default' : 'move' }} pointerEvents={shapeMode ? 'none' : undefined} style={{ cursor: shapeMode ? 'default' : 'move' }} pointerEvents={shapeMode ? 'none' : undefined}
onPointerDown={e => start(e, { type: 'table', id: tb.id })} data-testid="floor-table" /> onPointerDown={e => start(e, { type: 'table', id: tb.id })} data-testid="floor-table" />
))} ))}
{resizable && handles.map(h => {
const x = selected.x + (h.includes('e') ? 1 : h.includes('w') ? -1 : 0) * selected.width / 2
const y = selected.y + (h.includes('s') ? 1 : h.includes('n') ? -1 : 0) * selected.height / 2
return (
<rect key={h} x={x - r / 2} y={y - r / 2} width={r} height={r} rx={r / 4} fill="var(--x-surface)" stroke="var(--x-accent)" strokeWidth={2 / scale}
style={{ cursor: CURSOR[h] }} data-testid={`floor-handle-${h}`}
onPointerDown={e => start(e, { ...sel, handle: h })} />
)
})}
{shapeMode && edgeHover && (
<g transform={`translate(${edgeHover.x} ${edgeHover.y})`} pointerEvents="none" data-testid="floor-edge-add">
<circle r={r} fill="var(--x-accent)" />
<path d={`M ${-r * 0.5} 0 H ${r * 0.5} M 0 ${-r * 0.5} V ${r * 0.5}`} stroke="var(--x-accent-fg)" strokeWidth={2.5 / scale} strokeLinecap="round" />
</g>
)}
{shapeMode && corners.map(([x, y], i) => ( {shapeMode && corners.map(([x, y], i) => (
<circle key={i} cx={x} cy={y} r={Math.max(10, plan.width / 90)} data-testid="floor-corner" <circle key={i} cx={x} cy={y} r={r} data-testid="floor-corner"
fill={sel?.type === 'corner' && sel.index === i ? 'var(--x-accent)' : 'var(--x-surface)'} stroke="var(--x-accent)" strokeWidth="3" fill={sel?.type === 'corner' && sel.index === i ? 'var(--x-accent)' : 'var(--x-surface)'} stroke="var(--x-accent)" strokeWidth={3 / scale}
style={{ cursor: 'grab' }} onPointerDown={e => start(e, { type: 'corner', index: i })} /> style={{ cursor: 'grab' }} onPointerDown={e => { setCornerTip(null); start(e, { type: 'corner', index: i }) }}
onPointerEnter={() => showTip(i)} onPointerLeave={hideTip} />
))} ))}
{shapeMode && cornerTip != null && corners[cornerTip] && (
// the bubble over a corner: remove it (not below 3 corners)
<g transform={`translate(${corners[cornerTip][0]} ${corners[cornerTip][1] - r * 3.2})`} onPointerEnter={keepTip} onPointerLeave={hideTip} data-testid="floor-corner-tip">
<rect x={-r * 1.6} y={-r * 1.3} width={r * 3.2} height={r * 2.6} rx={r * 0.5} fill="var(--x-surface)" stroke="var(--x-line-strong)" strokeWidth={1.5 / scale} />
<path d={`M ${-r * 0.35} ${r * 1.3} L 0 ${r * 1.9} L ${r * 0.35} ${r * 1.3} Z`} fill="var(--x-surface)" stroke="var(--x-line-strong)" strokeWidth={1.5 / scale} />
<g role="button" aria-label={t('floor.removeCorner')} style={{ cursor: corners.length > 3 ? 'pointer' : 'not-allowed' }} opacity={corners.length > 3 ? 1 : 0.4}
onPointerDown={e => {
e.stopPropagation()
if (corners.length <= 3) return
setForm(f => ({ ...f, outline: removeCorner(outlineOf(f), cornerTip) }))
setCornerTip(null); setSel(null)
}} data-testid="floor-corner-remove">
<rect x={-r * 1.6} y={-r * 1.3} width={r * 3.2} height={r * 2.6} fill="transparent" />
<Trash2 x={-r * 0.8} y={-r * 0.8} width={r * 1.6} height={r * 1.6} color="var(--x-danger-ink)" />
</g>
</g>
)}
</svg> </svg>
</div> </div>
<p className="text-caption text-ink-3">{t('floor.keysHint')}</p> <p className="text-caption text-ink-3">{shapeMode ? t('floor.shapeHint') : t('floor.keysHint')}</p>
</div> </div>
<aside className="grid gap-4 content-start lg:max-h-[calc(100vh-10rem)] lg:overflow-y-auto"> <aside className="grid gap-4 content-start lg:sticky lg:top-0">
{shapeMode ? ( {shapeMode ? (
<Panel title={t('floor.shapeTitle')}> <Panel title={t('floor.shapeTitle')}>
<p className="text-caption text-ink-2">{t('floor.cornerCount', { count: corners.length })}</p> <p className="text-caption text-ink-2">{t('floor.cornerCount', { count: corners.length })}</p>
<div className="flex flex-wrap gap-2"> <p className="text-caption text-ink-2">{t('floor.shapeHowTo')}</p>
<Button size="sm" variant="secondary" disabled={sel?.type !== 'corner'} data-testid="floor-corner-add" <Button size="sm" variant="secondary" disabled={!form.outline} className="justify-self-start" onClick={() => { setF('outline', null); setSel(null) }}>{t('floor.rectangle')}</Button>
onClick={() => setForm(f => ({ ...f, outline: addCorner(outlineOf(f), sel.index) }))}>{t('floor.addCorner')}</Button>
<Button size="sm" variant="secondary" disabled={sel?.type !== 'corner' || corners.length <= 3}
onClick={() => { setForm(f => ({ ...f, outline: removeCorner(outlineOf(f), sel.index) })); setSel(null) }}>{t('floor.removeCorner')}</Button>
<Button size="sm" variant="ghost" disabled={!form.outline} onClick={() => { setF('outline', null); setSel(null) }}>{t('floor.rectangle')}</Button>
</div>
</Panel> </Panel>
) : selected ? ( ) : selected ? (
<Selected thing={selected} sel={sel} plan={plan} t={t} <Selected thing={selected} sel={sel} plan={plan} t={t}
@@ -154,7 +287,7 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
) : ( ) : (
<Panel title={t('floor.add')}> <Panel title={t('floor.add')}>
<Field label={t('floor.newTableShape')}> <Field label={t('floor.newTableShape')}>
<Select size="sm" value={newShape} onChange={e => setNewShape(e.target.value)} options={SHAPES.map(s => ({ value: s, label: t(`floor.shapes.${s}`) }))} /> <Segmented size="sm" value={newShape} onChange={setNewShape} options={SHAPES.map(s => ({ value: s, label: t(`floor.shapes.${s}`) }))} />
</Field> </Field>
{own.length + other.length === 0 ? <p className="text-caption text-ink-3">{t('floor.allPlaced')}</p> : ( {own.length + other.length === 0 ? <p className="text-caption text-ink-3">{t('floor.allPlaced')}</p> : (
<div className="grid gap-2"> <div className="grid gap-2">
@@ -165,11 +298,11 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
</div> </div>
)} )}
<div className="grid gap-1.5"> <div className="grid gap-1.5">
<span className="text-label font-semibold text-ink">{t('floor.things')}</span> <span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('floor.things')}</span>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{ITEM_KINDS.map(k => ( {ITEM_KINDS.map(k => (
<Button key={k} size="sm" variant="secondary" data-testid={`floor-add-${k}`} <Button key={k} size="sm" variant="secondary" data-testid={`floor-add-${k}`}
onClick={() => { const r = addItem(layout, plan, k, k === 'label' ? t('floor.labelText') : null); setLayout(r.layout); setSel({ type: 'item', id: r.key }) }}> onClick={() => { const res = addItem(layout, plan, k, k === 'label' ? t('floor.labelText') : null); setLayout(res.layout); setSel({ type: 'item', id: res.key }) }}>
{t(`floor.kinds.${k}`)} {t(`floor.kinds.${k}`)}
</Button> </Button>
))} ))}
@@ -181,7 +314,7 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
<Panel title={t('floor.settings')}> <Panel title={t('floor.settings')}>
<Field label={t('floor.name')}><Input size="sm" value={form.name} maxLength={60} onChange={e => setF('name', e.target.value)} data-testid="floor-name" /></Field> <Field label={t('floor.name')}><Input size="sm" value={form.name} maxLength={60} onChange={e => setF('name', e.target.value)} data-testid="floor-name" /></Field>
<Field label={t('floor.zone')} hint={t('floor.zoneHint')}> <Field label={t('floor.zone')} hint={t('floor.zoneHint')}>
<Select size="sm" value={form.group_id ?? ''} onChange={e => setF('group_id', e.target.value === '' ? null : Number(e.target.value))} <Dropdown size="sm" value={form.group_id ?? ''} onChange={v => setF('group_id', v === '' ? null : v)}
options={[{ value: '', label: t('floor.noZone') }, ...groups.map(g => ({ value: g.id, label: g.name }))]} /> options={[{ value: '', label: t('floor.noZone') }, ...groups.map(g => ({ value: g.id, label: g.name }))]} />
</Field> </Field>
<div className="grid grid-cols-2 gap-2"> <div className="grid grid-cols-2 gap-2">
@@ -222,8 +355,8 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
function Panel({ title, children }) { function Panel({ title, children }) {
return ( return (
<section className="grid gap-3 p-4 rounded-card border border-line bg-surface shadow-raised"> <section className="grid gap-3 p-card rounded-card border border-line bg-surface shadow-raised">
<h3 className="text-label font-semibold text-ink uppercase tracking-wide">{title}</h3> <h3 className="text-overline font-semibold text-ink-3 uppercase tracking-wide">{title}</h3>
{children} {children}
</section> </section>
) )
@@ -248,7 +381,8 @@ function TableButtons({ tables, title, onAdd, quiet = false }) {
function Selected({ thing, sel, plan, t, onChange, onRemove }) { function Selected({ thing, sel, plan, t, onChange, onRemove }) {
const isTable = sel.type === 'table' const isTable = sel.type === 'table'
const setSize = (w, h) => onChange(resize(thing, plan, w, h)) const isArea = !isTable && thing.kind === 'area'
const cells = v => t('floor.cells', { count: v, value: String(v).replace('.', t('floor.decimal')) })
return ( return (
<Panel title={isTable ? t('floor.table', { name: thing.name }) : t(`floor.kinds.${thing.kind}`)}> <Panel title={isTable ? t('floor.table', { name: thing.name }) : t(`floor.kinds.${thing.kind}`)}>
{isTable && ( {isTable && (
@@ -276,10 +410,39 @@ function Selected({ thing, sel, plan, t, onChange, onRemove }) {
<Input size="sm" value={thing.text ?? ''} maxLength={60} onChange={e => onChange({ text: e.target.value })} data-testid="floor-item-text" /> <Input size="sm" value={thing.text ?? ''} maxLength={60} onChange={e => onChange({ text: e.target.value })} data-testid="floor-item-text" />
</Field> </Field>
)} )}
<div className="grid grid-cols-2 gap-2"> {isArea ? (
<Field label={t('floor.itemWidth')}><Input size="sm" type="number" min={4} value={thing.width} onChange={e => setSize(Number(e.target.value), undefined)} /></Field> <>
<Field label={t('floor.itemHeight')}><Input size="sm" type="number" min={4} value={thing.height} onChange={e => setSize(undefined, Number(e.target.value))} /></Field> <Field label={t('floor.colour')}>
<div className="flex flex-wrap gap-2" role="radiogroup" aria-label={t('floor.colour')} data-testid="floor-area-colours">
{AREA_COLOURS.map(c => (
<button key={c} type="button" role="radio" aria-checked={thing.color === c} aria-label={c} onClick={() => onChange({ color: c })}
className={cx('w-8 h-8 rounded-full border-2', thing.color === c ? 'border-accent ring-2 ring-[var(--x-accent)] ring-offset-2 ring-offset-[var(--x-surface)]' : 'border-line')}
style={{ background: c, opacity: 0.85 }} />
))}
<button type="button" role="radio" aria-checked={!thing.color} onClick={() => onChange({ color: null })}
className={cx('px-2 h-8 rounded-full border-2 text-caption text-ink-2', !thing.color ? 'border-accent' : 'border-line')}>{t('floor.noColour')}</button>
</div> </div>
</Field>
<p className="text-caption text-ink-2">{t('floor.areaResizeHint')}</p>
</>
) : (
// sizes in grid cells, by half cells (2026-11-21); a wall's thickness in steps
<div className="grid gap-2">
<div className="flex items-center gap-2">
<span className="flex-1 text-label text-ink-2">{t(thing.kind === 'wall' ? 'floor.length' : 'floor.itemWidth')}</span>
<Stepper value={toCells(thing.width, plan)} min={0.5} max={60} step={0.5} format={cells} label={t('floor.itemWidth')}
onChange={v => onChange(resizeCells(thing, plan, v, null))} data-testid="floor-width" />
</div>
<div className="flex items-center gap-2">
<span className="flex-1 text-label text-ink-2">{t(thing.kind === 'wall' ? 'floor.thickness' : 'floor.itemHeight')}</span>
{thing.kind === 'wall'
? <Stepper value={thing.height} steps={WALL_THICKNESS} format={v => `${v} px`} label={t('floor.thickness')} onChange={v => onChange({ height: v })} />
: <Stepper value={toCells(thing.height, plan)} min={0.5} max={60} step={0.5} format={cells} label={t('floor.itemHeight')}
onChange={v => onChange(resizeCells(thing, plan, null, v))} data-testid="floor-height" />}
</div>
<p className="text-caption text-ink-3">{t('floor.cellsHint')}</p>
</div>
)}
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
<span className="text-label text-ink-2 mr-auto">{t('floor.rotation', { deg: Math.round(thing.rotation || 0) })}</span> <span className="text-label text-ink-2 mr-auto">{t('floor.rotation', { deg: Math.round(thing.rotation || 0) })}</span>
<IconButton size="sm" variant="secondary" label={t('floor.rotateLeft')} onClick={() => onChange({ rotation: rotate(thing.rotation || 0, -15) })}><RotateCcw size={16} /></IconButton> <IconButton size="sm" variant="secondary" label={t('floor.rotateLeft')} onClick={() => onChange({ rotation: rotate(thing.rotation || 0, -15) })}><RotateCcw size={16} /></IconButton>
@@ -29,17 +29,17 @@ export default function FloorPlansTab() {
{ id: null, name: t('floor.noZone'), plans: plans.filter(p => p.group_id == null || !groups.some(g => g.id === p.group_id)) }].filter(z => z.plans.length) { id: null, name: t('floor.noZone'), plans: plans.filter(p => p.group_id == null || !groups.some(g => g.id === p.group_id)) }].filter(z => z.plans.length)
return ( return (
<div className="p-4 md:p-6 grid gap-4" data-testid="floor-plans"> <div className="grid gap-4" data-testid="floor-plans">
<nav className="grid gap-2" aria-label={t('floor.title')}> <nav className="grid gap-2" aria-label={t('floor.title')}>
<p className="text-label text-ink-2 max-w-4xl">{t('floor.intro')}</p> <p className="text-label text-ink-2 max-w-4xl">{t('floor.intro')}</p>
<div className="flex flex-wrap items-end gap-x-4 gap-y-2"> <div className="flex flex-wrap items-end gap-x-4 gap-y-2">
{byZone.map(z => ( {byZone.map(z => (
<div key={z.id ?? 'none'} className="grid gap-1"> <div key={z.id ?? 'none'} className="grid gap-1">
<span className="text-caption font-semibold text-ink-3 uppercase tracking-wide">{z.name}</span> <span className="text-overline font-semibold text-ink-3 uppercase tracking-wide">{z.name}</span>
<div className="flex flex-wrap gap-1.5"> <div className="flex flex-wrap gap-1.5">
{z.plans.map(p => ( {z.plans.map(p => (
<button key={p.id} type="button" onClick={() => setChosen(p.id)} aria-current={plan?.id === p.id ? 'true' : undefined} data-testid="floor-plan-item" data-name={p.name} <button key={p.id} type="button" onClick={() => setChosen(p.id)} aria-current={plan?.id === p.id ? 'true' : undefined} data-testid="floor-plan-item" data-name={p.name}
className={cx('px-3 py-1.5 rounded-control border text-label font-medium transition-colors duration-fast text-left', className={cx('inline-flex items-center h-control-sm px-3 rounded-control border text-label font-medium transition-colors duration-fast text-left',
plan?.id === p.id ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface hover:bg-surface-2 text-ink')}> plan?.id === p.id ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface hover:bg-surface-2 text-ink')}>
{p.name} {p.name}
<span className="ml-2 text-caption text-ink-3 font-normal">{t('floor.tableCount', { count: data.tables.filter(x => x.plan_id === p.id).length })}</span> <span className="ml-2 text-caption text-ink-3 font-normal">{t('floor.tableCount', { count: data.tables.filter(x => x.plan_id === p.id).length })}</span>
@@ -1,7 +1,7 @@
// The floor plan editor's state as plain data (plan step 6.8, D-31), tested in tests/floor.test.mjs. // The floor plan editor's state as plain data (plan step 6.8, D-31), tested in tests/floor.test.mjs.
// A layout = { tables: [...placed tables], items: [...] } for one plan; the editor changes it // A layout = { tables: [...placed tables], items: [...] } for one plan; the editor changes it
// locally and saves it whole (PUT /api/floor-plans/{id}/layout). // locally and saves it whole (PUT /api/floor-plans/{id}/layout).
import { ITEM_SIZES, clamp, defaultSize, moveTo, snapSize } from '@xenia/floorplan/geometry' import { AREA_COLOURS, ITEM_SIZES, clamp, defaultSize, moveTo, snapSize } from '@xenia/floorplan/geometry'
/** The layout of a plan from GET /api/floor-plans. Items get local keys (`key`). */ /** The layout of a plan from GET /api/floor-plans. Items get local keys (`key`). */
export function layoutOf(data, planId) { export function layoutOf(data, planId) {
@@ -52,7 +52,8 @@ let counter = 0
export function addItem(layout, plan, kind, text = null) { export function addItem(layout, plan, kind, text = null) {
const [w, h] = ITEM_SIZES[kind] const [w, h] = ITEM_SIZES[kind]
const grid = gridOf(plan) const grid = gridOf(plan)
const item = moveTo({ key: `n${++counter}`, kind, width: snapSize(w, grid), height: kind === 'wall' ? h : snapSize(h, grid), rotation: 0, text }, plan.width / 2, plan.height / 2, plan) const item = moveTo({ key: `n${++counter}`, kind, width: snapSize(w, grid), height: kind === 'wall' ? h : snapSize(h, grid), rotation: 0, text,
color: kind === 'area' ? AREA_COLOURS[layout.items.filter(i => i.kind === 'area').length % AREA_COLOURS.length] : null }, plan.width / 2, plan.height / 2, plan)
return { layout: { ...layout, items: [...layout.items, item] }, key: item.key } return { layout: { ...layout, items: [...layout.items, item] }, key: item.key }
} }
@@ -91,6 +92,23 @@ export function resize(thing, plan, width, height) {
return { width: w, height: h } return { width: w, height: h }
} }
/** Sizes in grid cells (2026-11-21): one cell is the plan's grid size (also while the grid is
* hidden), counted in half cells, so a table follows the grid resolution picked. */
export const cellOf = plan => plan.grid_size || 40
export const toCells = (v, plan) => Math.max(0.5, Math.round((v / cellOf(plan)) * 2) / 2)
/** A new size in cells (null: that side unchanged); the centre stays on the grid. */
export function resizeCells(thing, plan, wCells, hCells) {
const c = cellOf(plan)
const width = wCells != null ? Math.max(0.5, wCells) * c : thing.width
const height = hCells != null ? Math.max(0.5, hCells) * c : thing.height
const m = moveTo({ ...thing, width, height }, thing.x, thing.y, plan)
return { width, height, x: m.x, y: m.y }
}
/** A wall's thickness, in steps (px). */
export const WALL_THICKNESS = [4, 6, 8, 12, 16, 20, 24, 32]
/** A rotation turned by `by` degrees, kept within 0–359. */ /** A rotation turned by `by` degrees, kept within 0–359. */
export const rotate = (deg, by) => (((deg + by) % 360) + 360) % 360 export const rotate = (deg, by) => (((deg + by) % 360) + 360) % 360
@@ -98,7 +116,7 @@ export const rotate = (deg, by) => (((deg + by) % 360) + 360) % 360
export function layoutBody(layout) { export function layoutBody(layout) {
return { return {
tables: layout.tables.map(t => ({ id: t.id, x: t.x, y: t.y, width: t.width, height: t.height, rotation: t.rotation || 0, shape: t.shape || 'square', seats: t.seats ?? null })), tables: layout.tables.map(t => ({ id: t.id, x: t.x, y: t.y, width: t.width, height: t.height, rotation: t.rotation || 0, shape: t.shape || 'square', seats: t.seats ?? null })),
items: layout.items.map(i => ({ kind: i.kind, x: i.x, y: i.y, width: i.width, height: i.height, rotation: i.rotation || 0, text: i.text || null })), items: layout.items.map(i => ({ kind: i.kind, x: i.x, y: i.y, width: i.width, height: i.height, rotation: i.rotation || 0, text: i.text || null, color: i.kind === 'area' ? i.color || null : null })),
} }
} }
@@ -8,7 +8,7 @@ import toast from 'react-hot-toast'
import { Plus, Trash2 } from 'lucide-react' import { Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, Input, Select, Spinner } from '@xenia/ui' import { Button, Dialog, Field, IconButton, Input, Page, Select, Spinner } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts' import { Pill } from '../overview/parts'
@@ -65,8 +65,7 @@ export default function ThrowawaysPage() {
] ]
return ( return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="waste-page"> <Page testId="waste-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header> <header>
<h1 className="text-title font-semibold text-ink">{t('waste.title')}</h1> <h1 className="text-title font-semibold text-ink">{t('waste.title')}</h1>
<p className="text-label text-ink-2">{t('waste.subtitle')}</p> <p className="text-label text-ink-2">{t('waste.subtitle')}</p>
@@ -100,7 +99,6 @@ export default function ThrowawaysPage() {
{history.isPending ? <div className="p-4"><Spinner /></div> {history.isPending ? <div className="p-4"><Spinner /></div>
: <Table columns={columns(false)} rows={rows} rowTestId="waste-row" empty={t('waste.noneInPeriod')} initialSort={{ key: 'logged_at', dir: 'desc' }} />} : <Table columns={columns(false)} rows={rows} rowTestId="waste-row" empty={t('waste.noneInPeriod')} initialSort={{ key: 'logged_at', dir: 'desc' }} />}
</Panel> </Panel>
</div>
{removing && ( {removing && (
<Dialog open size="sm" onClose={() => setRemoving(null)} title={t('waste.deleteTitle', { name: removing.product_name })} <Dialog open size="sm" onClose={() => setRemoving(null)} title={t('waste.deleteTitle', { name: removing.product_name })}
footer={<> footer={<>
@@ -108,7 +106,7 @@ export default function ThrowawaysPage() {
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing)}>{t('waste.deleteYes')}</Button> <Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing)}>{t('waste.deleteYes')}</Button>
</>} /> </>} />
)} )}
</div> </Page>
) )
} }
@@ -2,6 +2,7 @@
// Upload → into the library and set here at once ("upload on the spot") // Upload → into the library and set here at once ("upload on the spot")
// From library → the picker // From library → the picker
// Remove → nothing here any more (the photo stays in the library) // Remove → nothing here any more (the photo stays in the library)
// Layout (2026-11-21): the two buttons, the picture's name under them, then Remove.
// After an upload on the spot, "Name it after <the product>" sets the photo's display name to // After an upload on the spot, "Name it after <the product>" sets the photo's display name to
// `nameAfter` in Latin letters (latin() from @xenia/i18n). The file names on disk are the backend's. // `nameAfter` in Latin letters (latin() from @xenia/i18n). The file names on disk are the backend's.
// //
@@ -51,15 +52,16 @@ export default function MediaField({ value, onChange, nameAfter, nameAfterLabel,
<div className="flex gap-3 items-start"> <div className="flex gap-3 items-start">
<MediaThumb item={value} className="w-20 h-20 rounded-card border border-line shrink-0" /> <MediaThumb item={value} className="w-20 h-20 rounded-card border border-line shrink-0" />
<div className="grid gap-2 min-w-0"> <div className="grid gap-2 min-w-0">
{value && <span className="text-label text-ink truncate" title={value.name} data-testid="media-field-name">{value.name}</span>}
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
<Button size="sm" variant="secondary" icon={<ImagePlus size={14} />} loading={busy} onClick={() => input.current?.click()} <Button size="sm" variant="secondary" icon={<ImagePlus size={14} />} loading={busy} onClick={() => input.current?.click()}
data-testid="media-field-upload">{t(value ? 'media.replace' : 'media.uploadPhoto')}</Button> data-testid="media-field-upload">{t(value ? 'media.replace' : 'media.uploadPhoto')}</Button>
<Button size="sm" variant="secondary" icon={<Images size={14} />} disabled={busy} onClick={() => setPicking(true)} <Button size="sm" variant="secondary" icon={<Images size={14} />} disabled={busy} onClick={() => setPicking(true)}
data-testid="media-field-pick">{t('media.fromLibrary')}</Button> data-testid="media-field-pick">{t('media.fromLibrary')}</Button>
{value && <Button size="sm" variant="ghost" icon={<X size={14} />} disabled={busy} onClick={() => { onChange(null); setFresh(null) }}
data-testid="media-field-remove">{t('media.removePhoto')}</Button>}
</div> </div>
{/* 2026-11-21: the picture's name under the buttons, then "Remove" (red under the pointer) */}
{value && <span className="text-label text-ink truncate" title={value.name} data-testid="media-field-name">{value.name}</span>}
{value && <Button size="sm" variant="ghost" tone="danger" className="justify-self-start" icon={<X size={14} />} disabled={busy} onClick={() => { onChange(null); setFresh(null) }}
data-testid="media-field-remove">{t('media.removePhoto')}</Button>}
{value && fresh === value.id && suggested && suggested !== value.name && ( {value && fresh === value.id && suggested && suggested !== value.name && (
<button type="button" className="text-label text-accent-ink font-medium text-left disabled:opacity-50" disabled={busy} <button type="button" className="text-label text-accent-ink font-medium text-left disabled:opacity-50" disabled={busy}
onClick={rename} data-testid="media-field-name-after"> onClick={rename} data-testid="media-field-name-after">
@@ -7,7 +7,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Upload } from 'lucide-react' import { Upload } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, EmptyState, Input, Select, Spinner, cx } from '@xenia/ui' import { Button, EmptyState, Input, Page, Select, Spinner, cx } from '@xenia/ui'
import { listMedia } from './mediaApi' import { listMedia } from './mediaApi'
import { ACCEPT, preparing } from './mediaLogic' import { ACCEPT, preparing } from './mediaLogic'
import MediaDetails from './MediaDetails' import MediaDetails from './MediaDetails'
@@ -57,8 +57,8 @@ export default function MediaPage() {
const closeDetails = useCallback(() => setOpen(null), []) const closeDetails = useCallback(() => setOpen(null), [])
return ( return (
<div className={cx('p-4 md:p-6 grid gap-5 max-w-7xl min-h-full content-start', dragging && 'outline-2 outline-dashed outline-accent -outline-offset-8')} <Page className={cx(dragging && 'outline-2 outline-dashed outline-accent -outline-offset-8')}
data-testid="media-page" testId="media-page"
onDragOver={e => { if ([...(e.dataTransfer?.types || [])].includes('Files')) { e.preventDefault(); setDragging(true) } }} onDragOver={e => { if ([...(e.dataTransfer?.types || [])].includes('Files')) { e.preventDefault(); setDragging(true) } }}
onDragLeave={e => { if (e.currentTarget === e.target) setDragging(false) }} onDragLeave={e => { if (e.currentTarget === e.target) setDragging(false) }}
onDrop={onDrop}> onDrop={onDrop}>
@@ -95,6 +95,6 @@ export default function MediaPage() {
{open && <MediaDetails id={open} onClose={closeDetails} {open && <MediaDetails id={open} onClose={closeDetails}
onChanged={m => setPage(p => p && { ...p, items: p.items.map(x => (x.id === m.id ? { ...x, ...m } : x)) })} onChanged={m => setPage(p => p && { ...p, items: p.items.map(x => (x.id === m.id ? { ...x, ...m } : x)) })}
onDeleted={id => setPage(p => p && { ...p, items: p.items.filter(x => x.id !== id), total: p.total - 1 })} />} onDeleted={id => setPage(p => p && { ...p, items: p.items.filter(x => x.id !== id), total: p.total - 1 })} />}
</div> </Page>
) )
} }
@@ -8,7 +8,7 @@ import toast from 'react-hot-toast'
import { Check, ChevronDown, Pin, PinOff, Plus, Trash2 } from 'lucide-react' import { Check, ChevronDown, Pin, PinOff, Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, IconButton, Input, Switch, Textarea, cx } from '@xenia/ui' import { Button, Dialog, IconButton, Input, Page, Switch, Textarea, cx } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import { Panel } from '../reports/kit/parts' import { Panel } from '../reports/kit/parts'
@@ -36,8 +36,7 @@ export default function NotesPage() {
const { pinned, rest } = splitNotes(notes) const { pinned, rest } = splitNotes(notes)
const { open, done } = splitTodos(todos) const { open, done } = splitTodos(todos)
return ( return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="notes-page"> <Page testId="notes-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header> <header>
<h1 className="text-title font-semibold text-ink">{t('notes.title')}</h1> <h1 className="text-title font-semibold text-ink">{t('notes.title')}</h1>
<p className="text-label text-ink-2">{t('notes.subtitle', { notes: notes.length, todos: open.length })}</p> <p className="text-label text-ink-2">{t('notes.subtitle', { notes: notes.length, todos: open.length })}</p>
@@ -62,7 +61,6 @@ export default function NotesPage() {
</div> </div>
</Panel> </Panel>
</div> </div>
</div>
{removing && ( {removing && (
<Dialog open size="sm" onClose={() => setRemoving(null)} title={t(removing.kind === 'note' ? 'notes.deleteNote' : 'notes.deleteTodo')} <Dialog open size="sm" onClose={() => setRemoving(null)} title={t(removing.kind === 'note' ? 'notes.deleteNote' : 'notes.deleteTodo')}
description={removing.item.body.length > 120 ? `${removing.item.body.slice(0, 120)}…` : removing.item.body} description={removing.item.body.length > 120 ? `${removing.item.body.slice(0, 120)}…` : removing.item.body}
@@ -71,12 +69,12 @@ export default function NotesPage() {
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing, { onSuccess: () => setRemoving(null) })} data-testid="notes-delete-confirm">{t('notes.deleteYes')}</Button> <Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing, { onSuccess: () => setRemoving(null) })} data-testid="notes-delete-confirm">{t('notes.deleteYes')}</Button>
</>} /> </>} />
)} )}
</div> </Page>
) )
} }
function Label({ children }) { function Label({ children }) {
return <span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{children}</span> return <span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{children}</span>
} }
function NewNote() { function NewNote() {
@@ -27,7 +27,7 @@ export default function FeeProductCard({ product, onSaved }) {
} }
return ( return (
<section className="p-4 rounded-card border border-line bg-surface grid gap-3" aria-labelledby="fee-product-h" data-testid="fee-product"> <section className="grid gap-3 max-w-2xl" aria-labelledby="fee-product-h" data-testid="fee-product">
<div className="grid gap-1"> <div className="grid gap-1">
<h2 id="fee-product-h" className="text-title font-semibold text-ink">{t('feeProduct.title')}</h2> <h2 id="fee-product-h" className="text-title font-semibold text-ink">{t('feeProduct.title')}</h2>
<p className="text-label text-ink-2">{t('feeProduct.intro')}</p> <p className="text-label text-ink-2">{t('feeProduct.intro')}</p>
+46 -39
View File
@@ -1,3 +1,4 @@
// Online ordering settings: Online orders → Settings (2026-11-20; was its own page /online/fees).
// Online ordering (plan phase 3S, steps S.3–S.5): the ordering settings (OrderingSettings), // Online ordering (plan phase 3S, steps S.3–S.5): the ordering settings (OrderingSettings),
// delivery areas and fees, and the fee's line on the receipt (FeeProductCard). Backend: /api/connect/fees // delivery areas and fees, and the fee's line on the receipt (FeeProductCard). Backend: /api/connect/fees
// (connect_orders.fees). The venue lists the areas it delivers to and the fee rules, looked // (connect_orders.fees). The venue lists the areas it delivers to and the fee rules, looked
@@ -6,12 +7,13 @@
// win. The cloud applies the same rules at checkout (the same engine), so "Test an order" // win. The cloud applies the same rules at checkout (the same engine), so "Test an order"
// shows exactly what a customer will be charged. No rules = no fee. // shows exactly what a customer will be charged. No rules = no fee.
import { useCallback, useEffect, useMemo, useState } from 'react' import { useCallback, useEffect, useMemo, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { ArrowDown, ArrowUp, MapPin, Pencil, Plus, Trash2, Truck } from 'lucide-react' import { ArrowDown, ArrowUp, MapPin, Pencil, Plus, Trash2, Truck } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { SALES_POINTS } from '@xenia/access' import { SALES_POINTS } from '@xenia/access'
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Spinner, Switch } from '@xenia/ui' import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Spinner, Switch, Tabs } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import FeeProductCard from './FeeProductCard' import FeeProductCard from './FeeProductCard'
import OrderingLink from './OrderingLink' import OrderingLink from './OrderingLink'
@@ -26,6 +28,9 @@ export default function FeesPage() {
const [data, setData] = useState(null) const [data, setData] = useState(null)
const [error, setError] = useState(null) const [error, setError] = useState(null)
const [dialog, setDialog] = useState(null) // { kind: 'area' | 'rule', item? } | { kind: 'delete', what, item } const [dialog, setDialog] = useState(null) // { kind: 'area' | 'rule', item? } | { kind: 'delete', what, item }
const [params, setParams] = useSearchParams()
const section = ['rules', 'areas', 'settings'].includes(params.get('fees')) ? params.get('fees') : 'rules'
const setSection = v => setParams(p => { const n = new URLSearchParams(p); n.set('fees', v); return n }, { replace: true })
const load = useCallback(async () => { const load = useCallback(async () => {
try { try {
@@ -49,14 +54,11 @@ export default function FeesPage() {
} }
} }
if (error) return <div className="p-6"><EmptyState title={error} /></div> if (error) return <EmptyState title={error} />
if (!data) return <div className="p-6 flex justify-center"><Spinner /></div> if (!data) return <div className="py-10 flex justify-center"><Spinner /></div>
return ( return (
<div className="p-4 md:p-6 grid gap-6 max-w-6xl" data-testid="fees-page"> <div className="grid gap-6" data-testid="fees-page">
<header className="grid gap-1">
<h1 className="text-heading font-semibold text-ink">{t('ordering.pageTitle')}</h1>
</header>
{data.links?.order && <OrderingLink url={data.links.order} />} {data.links?.order && <OrderingLink url={data.links.order} />}
@@ -67,16 +69,23 @@ export default function FeesPage() {
<p className="text-body text-ink-2 max-w-3xl">{t('fees.intro')}</p> <p className="text-body text-ink-2 max-w-3xl">{t('fees.intro')}</p>
</div> </div>
<div className="grid gap-6 lg:grid-cols-[1fr_22rem] items-start"> {/* left: the fee rules, the areas and the fee's settings as tabs; right: test an order (2026-11-20) */}
<section className="grid gap-3" aria-labelledby="fee-rules"> <div className="grid gap-6 xl:grid-cols-[minmax(0,3fr)_minmax(19rem,1fr)] items-start">
<div className="flex items-center gap-2"> <section className="rounded-card border border-line bg-surface shadow-raised min-w-0" data-testid="fees-sections">
<h2 id="fee-rules" className="flex-1 text-title font-semibold text-ink">{t('fees.rules')}</h2> <Tabs inset value={section} onChange={setSection}
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'rule' })} data-testid="rule-add">{t('fees.addRule')}</Button> tabs={[
</div> { id: 'rules', label: t('fees.rules'), badge: data.rules.length || null, testId: 'fees-tab-rules' },
{data.rules.length === 0 ? ( { id: 'areas', label: t('fees.areas'), badge: data.areas.length || null, testId: 'fees-tab-areas' },
{ id: 'settings', label: t('fees.settings'), testId: 'fees-tab-settings' },
]}
end={section === 'rules' ? <Button size="sm" icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'rule' })} data-testid="rule-add">{t('fees.addRule')}</Button>
: section === 'areas' ? <Button size="sm" icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'area' })} data-testid="area-add">{t('fees.addArea')}</Button>
: null} />
<div className="p-card">
{section === 'rules' && (data.rules.length === 0 ? (
<EmptyState icon={<Truck size={28} />} title={t('fees.noRules')} description={t('fees.noRulesBody')} /> <EmptyState icon={<Truck size={28} />} title={t('fees.noRules')} description={t('fees.noRulesBody')} />
) : ( ) : (
<ol className="grid gap-2" data-testid="rules"> <ol className="grid gap-3" data-testid="rules">
{data.rules.map((r, i) => ( {data.rules.map((r, i) => (
<RuleRow key={r.id} rule={r} n={i + 1} areaNames={areaNames} first={i === 0} last={i === data.rules.length - 1} <RuleRow key={r.id} rule={r} n={i + 1} areaNames={areaNames} first={i === 0} last={i === data.rules.length - 1}
onMove={step => act(() => client.put('/api/connect/fees/rules/order', moveRule(data.rules, r.id, step)))} onMove={step => act(() => client.put('/api/connect/fees/rules/order', moveRule(data.rules, r.id, step)))}
@@ -85,36 +94,32 @@ export default function FeesPage() {
onDelete={() => setDialog({ kind: 'delete', what: 'rule', item: r })} /> onDelete={() => setDialog({ kind: 'delete', what: 'rule', item: r })} />
))} ))}
</ol> </ol>
)} ))}
</section> {section === 'areas' && (data.areas.length === 0 ? (
<EmptyState icon={<MapPin size={28} />} title={t('fees.noAreas')} />
<div className="grid gap-6">
<section className="grid gap-3" aria-labelledby="fee-areas">
<div className="flex items-center gap-2">
<h2 id="fee-areas" className="flex-1 text-title font-semibold text-ink">{t('fees.areas')}</h2>
<Button variant="secondary" icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'area' })} data-testid="area-add">{t('fees.addArea')}</Button>
</div>
{data.areas.length === 0 ? (
<p className="text-label text-ink-2">{t('fees.noAreas')}</p>
) : ( ) : (
<ul className="grid gap-2" data-testid="areas"> <ul className="grid gap-3" data-testid="areas">
{data.areas.map(a => ( {data.areas.map(a => (
<li key={a.id} className="p-3 rounded-card border border-line bg-surface flex items-start gap-2" data-testid="area"> <li key={a.id} className="px-card py-card-y rounded-card border border-line bg-surface flex items-center gap-3" data-testid="area">
<MapPin size={16} className="mt-0.5 text-ink-3 shrink-0" aria-hidden="true" /> <MapPin size={16} className="text-ink-3 shrink-0" aria-hidden="true" />
<span className="flex-1 min-w-0"> <span className="flex-1 min-w-0">
<span className={`block text-body font-medium ${a.is_active ? 'text-ink' : 'text-ink-3 line-through'}`}>{a.name}</span> <span className={`block text-body font-medium ${a.is_active ? 'text-ink' : 'text-ink-3 line-through'}`}>{a.name}</span>
<span className="block text-caption text-ink-2 truncate">{a.postcodes.length ? a.postcodes.join(', ') : t('fees.byNameOnly')}</span> <span className="block text-caption text-ink-2 truncate">{a.postcodes.length ? a.postcodes.join(', ') : t('fees.byNameOnly')}</span>
</span> </span>
<IconButton size="sm" variant="ghost" label={t('fees.edit')} onClick={() => setDialog({ kind: 'area', item: a })}><Pencil size={16} /></IconButton> <span className="flex gap-1.5">
<IconButton size="sm" variant="ghost" label={t('fees.delete')} onClick={() => setDialog({ kind: 'delete', what: 'area', item: a })}><Trash2 size={16} /></IconButton> <IconButton size="sm" variant="ghost" tone="accent" label={t('fees.edit')} onClick={() => setDialog({ kind: 'area', item: a })}><Pencil size={16} /></IconButton>
<IconButton size="sm" variant="ghost" tone="danger" label={t('fees.delete')} onClick={() => setDialog({ kind: 'delete', what: 'area', item: a })}><Trash2 size={16} /></IconButton>
</span>
</li> </li>
))} ))}
</ul> </ul>
)} ))}
{section === 'settings' && (data.fee_product
? <FeeProductCard key={JSON.stringify(data.fee_product)} product={data.fee_product} onSaved={load} />
: <EmptyState title={t('fees.noSettings')} />)}
</div>
</section> </section>
<TestOrder areas={data.areas} /> <TestOrder areas={data.areas} />
{data.fee_product && <FeeProductCard key={JSON.stringify(data.fee_product)} product={data.fee_product} onSaved={load} />}
</div>
</div> </div>
{dialog?.kind === 'area' && ( {dialog?.kind === 'area' && (
@@ -151,15 +156,17 @@ function RuleRow({ rule, n, areaNames, first, last, onMove, onToggle, onEdit, on
const params = p => ({ ...p, min: p.min, max: p.max, minMoney: p.min != null ? formatMoney(p.min) : '', maxMoney: p.max != null ? formatMoney(p.max) : '', const params = p => ({ ...p, min: p.min, max: p.max, minMoney: p.min != null ? formatMoney(p.min) : '', maxMoney: p.max != null ? formatMoney(p.max) : '',
days: (p.days ?? []).map(x => t(`fees.dayShort.${x}`)).join(', ') }) days: (p.days ?? []).map(x => t(`fees.dayShort.${x}`)).join(', ') })
return ( return (
<li className={`p-3 rounded-card border border-line bg-surface grid gap-1.5 ${rule.is_active ? '' : 'opacity-60'}`} data-testid="rule" data-rule={rule.id}> <li className={`px-card py-card-y rounded-card border border-line bg-surface grid gap-2 ${rule.is_active ? '' : 'opacity-60'}`} data-testid="rule" data-rule={rule.id}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="text-caption font-semibold text-ink-3 w-5">{n}</span> <span className="text-caption font-semibold text-ink-3 w-5">{n}</span>
<span className="flex-1 min-w-0 text-body font-semibold text-ink truncate">{rule.name}</span> <span className="flex-1 min-w-0 text-body font-semibold text-ink truncate">{rule.name}</span>
<span className="flex items-center gap-1 shrink-0">
<IconButton size="sm" variant="ghost" label={t('fees.up')} disabled={first} onClick={() => onMove(-1)}><ArrowUp size={16} /></IconButton> <IconButton size="sm" variant="ghost" label={t('fees.up')} disabled={first} onClick={() => onMove(-1)}><ArrowUp size={16} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('fees.down')} disabled={last} onClick={() => onMove(1)}><ArrowDown size={16} /></IconButton> <IconButton size="sm" variant="ghost" label={t('fees.down')} disabled={last} onClick={() => onMove(1)}><ArrowDown size={16} /></IconButton>
<Switch checked={rule.is_active} onChange={onToggle} aria-label={t('fees.active')} /> <IconButton size="sm" variant="ghost" tone="accent" label={t('fees.edit')} onClick={onEdit}><Pencil size={16} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('fees.edit')} onClick={onEdit}><Pencil size={16} /></IconButton> <IconButton size="sm" variant="ghost" tone="danger" label={t('fees.delete')} onClick={onDelete}><Trash2 size={16} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('fees.delete')} onClick={onDelete}><Trash2 size={16} /></IconButton> <Switch className="ml-2" checked={rule.is_active} onChange={onToggle} aria-label={t('fees.active')} />
</span>
</div> </div>
<div className="pl-7 text-label text-ink-2 grid gap-0.5"> <div className="pl-7 text-label text-ink-2 grid gap-0.5">
<span> <span>
@@ -332,7 +339,7 @@ function TestOrder({ areas }) {
setBusy(false) setBusy(false)
} }
return ( return (
<section className="p-4 rounded-card border border-line bg-surface-2 grid gap-3" aria-labelledby="fee-test" data-testid="fee-test"> <section className="p-card rounded-card border border-line bg-surface shadow-raised grid gap-3" aria-labelledby="fee-test" data-testid="fee-test">
<h2 id="fee-test" className="text-title font-semibold text-ink">{t('fees.test')}</h2> <h2 id="fee-test" className="text-title font-semibold text-ink">{t('fees.test')}</h2>
<Field label={t('fees.testSalesPoint')}> <Field label={t('fees.testSalesPoint')}>
<Select value={form.sales_point} onChange={e => set('sales_point', e.target.value)}> <Select value={form.sales_point} onChange={e => set('sales_point', e.target.value)}>
@@ -4,17 +4,22 @@
// then ready (takeaway) or out for delivery, then delivered. Each card shows the customer, when // then ready (takeaway) or out for delivery, then delivered. Each card shows the customer, when
// they want it, the venue's own price check and the lines. The lists refresh on the live // they want it, the venue's own price check and the lines. The lists refresh on the live
// events (a new order, a status change), after a reconnect, and every 20 seconds. // events (a new order, a status change), after a reconnect, and every 20 seconds.
// Settings (2026-11-20, was the page /online/fees): ordering hours, delivery areas and fees, for
// whoever has connect_orders.fees. The tab is kept in the address (?tab=).
import { useState } from 'react' import { useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { useQueryClient } from '@tanstack/react-query' import { useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { Check, RefreshCw, StickyNote, X } from 'lucide-react' import { Check, RefreshCw, StickyNote, X } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, Field, Spinner, Textarea, cx } from '@xenia/ui' import { useCan } from '@xenia/access'
import { Button, EmptyState, Field, Page, Spinner, Tabs, Textarea, cx } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import { lineTotal, orderTotal } from '../overview/overviewLogic' import { lineTotal, orderTotal } from '../overview/overviewLogic'
import { Pill } from '../overview/parts' import { Pill } from '../overview/parts'
import FeesPage from './FeesPage'
import { ONLINE_TABS, ONLINE_TONE, onlineKind, onlineNextStep } from './onlineOrdersLogic' import { ONLINE_TABS, ONLINE_TONE, onlineKind, onlineNextStep } from './onlineOrdersLogic'
const EVENTS = ['online_order_received', 'online_order_updated'] const EVENTS = ['online_order_received', 'online_order_updated']
@@ -33,9 +38,13 @@ function useList(tab) {
export default function OnlineOrdersPage() { export default function OnlineOrdersPage() {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const qc = useQueryClient() const qc = useQueryClient()
const [tab, setTab] = useState('incoming') const canSettings = useCan('connect_orders.fees')
const [params, setParams] = useSearchParams()
const asked = params.get('tab')
const tab = asked === 'settings' ? (canSettings ? 'settings' : 'incoming') : ONLINE_TABS.includes(asked) ? asked : 'incoming'
const setTab = id => setParams(p => { const n = new URLSearchParams(p); n.set('tab', id); return n }, { replace: true })
const lists = { incoming: useList('incoming'), active: useList('active'), history: useList('history') } const lists = { incoming: useList('incoming'), active: useList('active'), history: useList('history') }
const current = lists[tab] const current = lists[tab] ?? lists.incoming
const refresh = () => qc.invalidateQueries({ queryKey: ['online-orders'] }) const refresh = () => qc.invalidateQueries({ queryKey: ['online-orders'] })
async function act(fn) { async function act(fn) {
@@ -47,34 +56,29 @@ export default function OnlineOrdersPage() {
: client.post(`/api/connect/orders/${id}/status`, { status: extra }) : client.post(`/api/connect/orders/${id}/status`, { status: extra })
)) ))
return ( const tabs = [
<div className="flex flex-col h-full overflow-hidden" data-testid="online-orders"> ...ONLINE_TABS.map(k => {
<div className="shrink-0 flex items-end gap-1 border-b border-line px-4 md:px-6 pt-2" role="tablist">
{ONLINE_TABS.map(k => {
const count = lists[k].data?.length ?? 0 const count = lists[k].data?.length ?? 0
return { id: k, label: t(`onlineOrders.tab.${k}`), badge: count > 0 ? count : null, warn: k === 'incoming', testId: `online-tab-${k}` }
}),
...(canSettings ? [{ id: 'settings', label: t('onlineOrders.tab.settings'), testId: 'online-tab-settings' }] : []),
]
return ( return (
<button key={k} type="button" role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`online-tab-${k}`} <Page testId="online-orders"
className={cx('flex items-center gap-2 px-4 py-3 -mb-px border-b-2 text-body whitespace-nowrap transition-colors duration-fast', top={<Tabs size="lg" tabs={tabs} value={tab} onChange={setTab}
tab === k ? 'border-accent text-ink font-semibold' : 'border-transparent text-ink-2 hover:text-ink')}> end={tab !== 'settings' && <Button size="sm" variant="ghost" icon={<RefreshCw size={14} />} loading={current.isFetching} onClick={refresh}>{t('onlineOrders.refresh')}</Button>} />}>
{t(`onlineOrders.tab.${k}`)} {tab === 'settings' ? <FeesPage /> : (<>
{count > 0 && <span className={cx('px-1.5 rounded-full text-caption font-bold tabular-nums', k === 'incoming' ? 'bg-danger-soft text-danger-ink' : 'bg-surface-2 text-ink-2')}>{count}</span>}
</button>
)
})}
<span className="flex-1" />
<Button size="sm" variant="ghost" className="mb-2" icon={<RefreshCw size={14} />} loading={current.isFetching} onClick={refresh}>{t('onlineOrders.refresh')}</Button>
</div>
<div className="flex-1 overflow-y-auto p-4 md:p-6">
{current.error && <EmptyState compact title={errorMessage(current.error, t)} />} {current.error && <EmptyState compact title={errorMessage(current.error, t)} />}
{current.isPending ? <div className="py-10 flex justify-center"><Spinner /></div> {current.isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: current.data?.length === 0 ? <EmptyState title={t(`onlineOrders.empty.${tab}`)} /> : current.data?.length === 0 ? <EmptyState title={t(`onlineOrders.empty.${tab}`)} />
: ( : (
<div className="grid gap-4 max-w-3xl"> <div className="grid gap-4 grid-cols-[repeat(auto-fill,minmax(min(100%,26rem),1fr))] items-start">
{current.data?.map(o => <OrderCard key={o.id} order={o} onAction={onAction} />)} {current.data?.map(o => <OrderCard key={o.id} order={o} onAction={onAction} />)}
</div> </div>
)} )}
</div> </>)}
</div> </Page>
) )
} }
@@ -33,20 +33,22 @@ export default function OrderingSettings({ ordering, onSaved }) {
} }
return ( return (
<section className="p-4 rounded-card border border-line bg-surface grid gap-4" aria-labelledby="ordering-h" data-testid="ordering-settings"> <section className="p-card rounded-card border border-line bg-surface grid gap-4" aria-labelledby="ordering-h" data-testid="ordering-settings">
<div className="grid gap-1"> <div className="grid gap-1">
<h2 id="ordering-h" className="text-title font-semibold text-ink">{t('ordering.title')}</h2> <h2 id="ordering-h" className="text-title font-semibold text-ink">{t('ordering.title')}</h2>
<p className="text-label text-ink-2">{t('ordering.intro')}</p> <p className="text-label text-ink-2">{t('ordering.intro')}</p>
</div> </div>
<div className="grid gap-2 sm:grid-cols-2"> {/* takeaway, delivery and "any time" side by side, each at least 16rem, wrapping when they don't fit */}
<div className="grid gap-x-10 gap-y-4 grid-cols-[repeat(auto-fit,minmax(16rem,1fr))]">
{['takeaway', 'delivery'].map(s => ( {['takeaway', 'delivery'].map(s => (
<Switch key={s} checked={form.services.includes(s)} onChange={() => toggleService(s)} <Switch key={s} checked={form.services.includes(s)} onChange={() => toggleService(s)}
label={t(`ordering.service.${s}`)} description={t(`ordering.serviceHint.${s}`)} data-testid={`ordering-${s}`} /> label={t(`ordering.service.${s}`)} description={t(`ordering.serviceHint.${s}`)} data-testid={`ordering-${s}`} />
))} ))}
<Switch checked={form.anyTime} onChange={v => set('anyTime', v)} label={t('ordering.anyTime')} description={t('ordering.anyTimeHint')} />
</div> </div>
<Hours anyTime={form.anyTime} days={form.days} onAnyTime={v => set('anyTime', v)} onDays={d => set('days', d)} testId="ordering-hours" /> <Hours anyTime={form.anyTime} days={form.days} onAnyTime={v => set('anyTime', v)} onDays={d => set('days', d)} testId="ordering-hours" noSwitch />
<div className="grid gap-3 sm:grid-cols-3"> <div className="grid gap-3 sm:grid-cols-3">
<Field label={t('ordering.prep')} hint={t('ordering.prepHint')}> <Field label={t('ordering.prep')} hint={t('ordering.prepHint')}>
@@ -106,16 +108,16 @@ export default function OrderingSettings({ ordering, onSaved }) {
} }
/** Hours per day (several ranges, past midnight), or any time. */ /** Hours per day (several ranges, past midnight), or any time. */
function Hours({ anyTime, days, onAnyTime, onDays, anyLabel, anyHint, testId }) { function Hours({ anyTime, days, onAnyTime, onDays, anyLabel, anyHint, testId, noSwitch = false }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const setDay = (d, ranges) => onDays(days.map((r, i) => (i === d ? ranges : r))) const setDay = (d, ranges) => onDays(days.map((r, i) => (i === d ? ranges : r)))
return ( return (
<div className="grid gap-2"> <div className="grid gap-2">
<Switch checked={anyTime} onChange={onAnyTime} label={anyLabel ?? t('ordering.anyTime')} description={anyHint ?? t('ordering.anyTimeHint')} /> {!noSwitch && <Switch checked={anyTime} onChange={onAnyTime} label={anyLabel ?? t('ordering.anyTime')} description={anyHint ?? t('ordering.anyTimeHint')} />}
{!anyTime && ( {!anyTime && (
<ul className="grid gap-1.5" data-testid={testId}> <ul className="grid divide-y divide-line rounded-card border border-line" data-testid={testId}>
{DAYS.map(d => ( {DAYS.map(d => (
<li key={d} className="grid grid-cols-[6rem_1fr] gap-2 items-start"> <li key={d} className="grid grid-cols-[7rem_1fr] gap-3 items-start px-card py-3">
<span className="text-body text-ink pt-2">{t(`fees.dayLong.${d}`)}</span> <span className="text-body text-ink pt-2">{t(`fees.dayLong.${d}`)}</span>
<div className="grid gap-1.5"> <div className="grid gap-1.5">
{days[d].length === 0 && <span className="text-label text-ink-3 pt-2">{t('ordering.closedDay')}</span>} {days[d].length === 0 && <span className="text-label text-ink-3 pt-2">{t('ordering.closedDay')}</span>}
@@ -1,3 +1,4 @@
// The tables' QR codes: Tables → QR codes (2026-11-20; was its own page /online/qr).
// The tables' QR codes (plan phase 3S, step S.7): one code per table that opens the QR menu // The tables' QR codes (plan phase 3S, step S.7): one code per table that opens the QR menu
// at that table. The venue chooses whether guests can order from it (straight onto the // at that table. The venue chooses whether guests can order from it (straight onto the
// table's order, to the kitchen, with a message to the table's waiters) or only read it. A // table's order, to the kitchen, with a message to the table's waiters) or only read it. A
@@ -9,11 +10,11 @@ import toast from 'react-hot-toast'
import { Printer, RefreshCw } from 'lucide-react' import { Printer, RefreshCw } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Spinner, Switch } from '@xenia/ui' import { Button, Dialog, EmptyState, PrintArea, PrintSheet, Spinner, Switch } from '@xenia/ui'
import { QrCode } from '@xenia/ui/qr' import { QrCode } from '@xenia/ui/qr'
import client from '../../api/client' import client from '../../api/client'
export default function QrCodesPage() { export default function TableQrCodes() {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const [data, setData] = useState(null) const [data, setData] = useState(null)
const [error, setError] = useState(null) const [error, setError] = useState(null)
@@ -31,17 +32,13 @@ export default function QrCodesPage() {
setBusy(false) setBusy(false)
} }
if (error) return <div className="p-6"><EmptyState title={error} /></div> if (error) return <EmptyState title={error} />
if (!data) return <div className="p-6 flex justify-center"><Spinner /></div> if (!data) return <div className="py-10 flex justify-center"><Spinner /></div>
return ( return (
<div className="p-4 md:p-6 grid gap-6 max-w-6xl" data-testid="qr-page"> <div className="grid gap-5" data-testid="qr-page">
<header className="grid gap-1 print:hidden"> <section className="p-card rounded-card border border-line bg-surface shadow-raised grid gap-3 print:hidden">
<h1 className="text-heading font-semibold text-ink">{t('qr.title')}</h1> <p className="text-body text-ink-2">{t('qr.intro')}</p>
<p className="text-body text-ink-2 max-w-3xl">{t('qr.intro')}</p>
</header>
<section className="p-4 rounded-card border border-line bg-surface grid gap-3 print:hidden">
<Switch checked={data.ordering} disabled={busy} data-testid="qr-ordering" <Switch checked={data.ordering} disabled={busy} data-testid="qr-ordering"
onChange={on => act(() => client.put('/api/connect/qr/ordering', { on }), t('fees.saved'))} onChange={on => act(() => client.put('/api/connect/qr/ordering', { on }), t('fees.saved'))}
label={t('qr.ordering')} description={t(data.ordering ? 'qr.orderingOn' : 'qr.orderingOff')} /> label={t('qr.ordering')} description={t(data.ordering ? 'qr.orderingOn' : 'qr.orderingOff')} />
@@ -57,7 +54,7 @@ export default function QrCodesPage() {
) : ( ) : (
<ul className="grid gap-4 print:gap-6" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(13rem, 1fr))' }} data-testid="qr-tables"> <ul className="grid gap-4 print:gap-6" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(13rem, 1fr))' }} data-testid="qr-tables">
{data.tables.map(tb => ( {data.tables.map(tb => (
<li key={tb.id} className="p-4 rounded-card border border-line bg-surface grid justify-items-center gap-2 break-inside-avoid" data-testid="qr-table" data-table={tb.id} data-url={tb.url}> <li key={tb.id} className="p-card rounded-card border border-line bg-surface grid justify-items-center gap-2 break-inside-avoid" data-testid="qr-table" data-table={tb.id} data-url={tb.url}>
<span className="text-title font-semibold text-ink">{t('qr.table', { name: tb.name })}</span> <span className="text-title font-semibold text-ink">{t('qr.table', { name: tb.name })}</span>
{tb.group && <span className="text-label text-ink-2">{tb.group}</span>} {tb.group && <span className="text-label text-ink-2">{tb.group}</span>}
<QrCode value={tb.url} size={168} framed={false} /> <QrCode value={tb.url} size={168} framed={false} />
@@ -70,6 +67,22 @@ export default function QrCodesPage() {
</ul> </ul>
)} )}
{data.tables.length > 0 && (
// what "Print all codes" puts on paper: only the codes, as cards to cut out (2026-11-20)
<PrintArea data-testid="qr-print">
<PrintSheet columns={3}>
{data.tables.map(tb => (
<div key={tb.id}>
<span style={{ fontSize: '15pt', fontWeight: 700 }}>{t('qr.table', { name: tb.name })}</span>
{tb.group && <span style={{ fontSize: '9pt' }}>{tb.group}</span>}
<QrCode value={tb.url} size={150} framed={false} />
<span style={{ fontSize: '8pt' }}>{t(data.ordering ? 'qr.scanOrder' : 'qr.scanRead')}</span>
</div>
))}
</PrintSheet>
</PrintArea>
)}
{confirmAll && ( {confirmAll && (
<Dialog open size="sm" title={t('qr.rotateAllTitle')} onClose={() => setConfirmAll(false)} <Dialog open size="sm" title={t('qr.rotateAllTitle')} onClose={() => setConfirmAll(false)}
footer={<> footer={<>
@@ -10,7 +10,7 @@ import toast from 'react-hot-toast'
import { ArrowLeft, Ban, CheckCheck, CreditCard, Printer } from 'lucide-react' import { ArrowLeft, Ban, CheckCheck, CreditCard, Printer } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Select, Spinner, cx } from '@xenia/ui' import { Button, Dialog, EmptyState, Page, Select, Spinner, cx } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import { useDuration } from '../overview/hooks' import { useDuration } from '../overview/hooks'
@@ -54,8 +54,7 @@ function NewOrder({ tableId }) {
const table = tables.find(x => x.id === tableId) const table = tables.find(x => x.id === tableId)
const open = async () => (await client.post('/api/orders/', { table_id: tableId, order_type: 'here' })).data.id const open = async () => (await client.post('/api/orders/', { table_id: tableId, order_type: 'here' })).data.id
return ( return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="order-new"> <Page testId="order-new">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3"> <header className="flex flex-wrap items-center gap-3">
<Back /> <Back />
<h1 className="text-title font-semibold text-ink">{t('orders.newTitle', { table: table ? tableName(table) : tableId ?? '' })}</h1> <h1 className="text-title font-semibold text-ink">{t('orders.newTitle', { table: table ? tableName(table) : tableId ?? '' })}</h1>
@@ -66,8 +65,7 @@ function NewOrder({ tableId }) {
qc.invalidateQueries({ queryKey: ['orders-active'] }) qc.invalidateQueries({ queryKey: ['orders-active'] })
navigate(`/orders/${id}`, { replace: true }) navigate(`/orders/${id}`, { replace: true })
}} /> }} />
</div> </Page>
</div>
) )
} }
@@ -121,8 +119,7 @@ function OrderView({ orderId }) {
} }
return ( return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="order-page" data-status={order.status}> <Page testId="order-page" data-status={order.status}>
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3"> <header className="flex flex-wrap items-center gap-3">
<Back /> <Back />
<h1 className="text-title font-semibold text-ink">{order.table_name ? t('orders.title', { table: order.table_name }) : t('orders.titleNoTable', { id: order.id })}</h1> <h1 className="text-title font-semibold text-ink">{order.table_name ? t('orders.title', { table: order.table_name }) : t('orders.titleNoTable', { id: order.id })}</h1>
@@ -167,7 +164,6 @@ function OrderView({ orderId }) {
)} )}
{tab === 'prices' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><PriceEventList events={priceEvents} /></section>} {tab === 'prices' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><PriceEventList events={priceEvents} /></section>}
{tab === 'history' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><AuditList order={order} /></section>} {tab === 'history' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><AuditList order={order} /></section>}
</div>
{paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose} {paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose}
onClose={() => setPaying(null)} onClose={() => setPaying(null)}
@@ -192,6 +188,6 @@ function OrderView({ orderId }) {
<Button variant="danger" icon={<Printer size={16} />} loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}</Button> <Button variant="danger" icon={<Printer size={16} />} loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}</Button>
</>} /> </>} />
)} )}
</div> </Page>
) )
} }
@@ -25,7 +25,7 @@ export default function OrderPeople({ order, open, staff, onChanged }) {
return ( return (
<section className="rounded-card border border-line bg-surface shadow-raised p-4 grid gap-3" data-testid="order-people"> <section className="rounded-card border border-line bg-surface shadow-raised p-4 grid gap-3" data-testid="order-people">
<div className="grid gap-2"> <div className="grid gap-2">
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.people.staff')}</h3> <h3 className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('orders.people.staff')}</h3>
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
{order.waiters.length === 0 && <span className="text-label text-ink-3">{t('orders.people.noStaff')}</span>} {order.waiters.length === 0 && <span className="text-label text-ink-3">{t('orders.people.noStaff')}</span>}
{order.waiters.map(w => ( {order.waiters.map(w => (
@@ -65,7 +65,7 @@ function Customer({ order, open, onChanged }) {
return ( return (
<div className="grid gap-2 border-t border-line pt-3"> <div className="grid gap-2 border-t border-line pt-3">
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.people.customer')}</h3> <h3 className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('orders.people.customer')}</h3>
{order.customer_id ? ( {order.customer_id ? (
<div className="flex items-center gap-2 p-2 rounded-control bg-info-soft text-info-ink"> <div className="flex items-center gap-2 p-2 rounded-control bg-info-soft text-info-ink">
<UserRound size={16} aria-hidden="true" /> <UserRound size={16} aria-hidden="true" />
@@ -37,7 +37,7 @@ export default function PrintProblemsCard({ orderId = null, onOpen }) {
</span>}> </span>}>
<PrintProblemsPanel problems={shown} printers={data?.printers ?? []} run={run} showPlace={orderId == null} <PrintProblemsPanel problems={shown} printers={data?.printers ?? []} run={run} showPlace={orderId == null}
onOpen={onOpen ? p => onOpen(p.order_id, p.table_name) : undefined} /> onOpen={onOpen ? p => onOpen(p.order_id, p.table_name) : undefined} />
<p className="px-4 pb-3 text-caption text-ink-3">{t('orders.printHelp')}</p> <p className="px-card pb-3 text-caption text-ink-3">{t('orders.printHelp')}</p>
</Card> </Card>
) )
} }
@@ -4,11 +4,15 @@
// and can tell its waiters (or everyone) a message. Tickets that didn't print are listed below // and can tell its waiters (or everyone) a message. Tickets that didn't print are listed below
// with what can be done about them (6.10). // with what can be done about them (6.10).
// Everything stays current through the live events. // Everything stays current through the live events.
// 2026-11-20: the toolbar is the shared one (view, state chips, zones as a multi-select), a click on
// the card opens the table (no separate button), and the tables' QR codes are a view here (?view=qr;
// was the page /online/qr) for whoever manages the QR menu.
import { useState } from 'react' import { useState } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate, useSearchParams } from 'react-router-dom'
import { Clock, Lock, Printer, Zap } from 'lucide-react' import { Clock, LayoutGrid, Lock, Map as MapIcon, Printer, QrCode, Zap } from 'lucide-react'
import { useCan, useModule } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, IconButton, Select, Spinner, cx } from '@xenia/ui' import { Dropdown, EmptyState, FilterChip, IconButton, Page, Segmented, Spinner, Toolbar, ToolbarSpacer, cx } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import LiveFloor from '../floor/LiveFloor' import LiveFloor from '../floor/LiveFloor'
@@ -16,6 +20,7 @@ import { useDuration } from '../overview/hooks'
import { TABLE_STATES, durationParts, orderTotal, tableCards, tableName } from '../overview/overviewLogic' import { TABLE_STATES, durationParts, orderTotal, tableCards, tableName } from '../overview/overviewLogic'
import { Money, Pill } from '../overview/parts' import { Money, Pill } from '../overview/parts'
import PrintProblemsCard from './PrintProblemsCard' import PrintProblemsCard from './PrintProblemsCard'
import TableQrCodes from '../online/TableQrCodes'
import { BORDER, SOFT, SOLID } from '../overview/tones' import { BORDER, SOFT, SOLID } from '../overview/tones'
import QuickActions from './QuickActions' import QuickActions from './QuickActions'
import { NO_ZONE, cardTarget, filterCards, flagsByTable, personName } from './orderLogic' import { NO_ZONE, cardTarget, filterCards, flagsByTable, personName } from './orderLogic'
@@ -27,9 +32,15 @@ export default function TablesPage() {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const tc = useTranslation('common').t const tc = useTranslation('common').t
const navigate = useNavigate() const navigate = useNavigate()
const [view, setView] = useState('list') const qrModule = useModule('connect_menu')
const qrAllowed = useCan('connect_menu.manage')
const qrOn = qrModule && qrAllowed
const [params, setParams] = useSearchParams()
const views = ['list', 'map', ...(qrOn ? ['qr'] : [])]
const view = views.includes(params.get('view')) ? params.get('view') : 'list'
const setView = v => setParams(p => { const n = new URLSearchParams(p); n.set('view', v); return n }, { replace: true })
const [states, setStates] = useState([]) const [states, setStates] = useState([])
const [zone, setZone] = useState('') const [zones, setZones] = useState([])
const [quick, setQuick] = useState(null) // a card const [quick, setQuick] = useState(null) // a card
const { data: tables = [], isPending: loadingTables } = useLiveQuery({ const { data: tables = [], isPending: loadingTables } = useLiveQuery({
@@ -45,49 +56,47 @@ export default function TablesPage() {
const { data: staff = [] } = useLiveQuery({ queryKey: ['waiters'], queryFn: () => client.get('/api/waiters/').then(r => r.data), staleTime: 60_000 }) const { data: staff = [] } = useLiveQuery({ queryKey: ['waiters'], queryFn: () => client.get('/api/waiters/').then(r => r.data), staleTime: 60_000 })
const cards = tableCards(tables, orders) const cards = tableCards(tables, orders)
const shown = filterCards(cards, { states, zone }) const shown = filterCards(cards, { states, zones })
const flags = flagsByTable(flagDefs, flagRows) const flags = flagsByTable(flagDefs, flagRows)
const name = id => personName(staff.find(s => s.id === id)) || `#${id}` const name = id => personName(staff.find(s => s.id === id)) || `#${id}`
const toggleState = s => setStates(list => (list.includes(s) ? list.filter(x => x !== s) : [...list, s])) const toggleState = s => setStates(list => (list.includes(s) ? list.filter(x => x !== s) : [...list, s]))
if (loadingTables || loadingOrders) return <div className="h-full grid place-items-center"><Spinner /></div> if (loadingTables || loadingOrders) return <div className="h-full grid place-items-center"><Spinner /></div>
const viewIcon = { list: <LayoutGrid size={15} />, map: <MapIcon size={15} />, qr: <QrCode size={15} /> }
const oneZone = zones.length === 1 && zones[0] !== NO_ZONE ? Number(zones[0]) : null
return ( return (
<div className="h-full overflow-y-auto p-4 lg:p-6 grid gap-4 content-start" data-testid="tables-page"> <Page testId="tables-page">
<div className="flex flex-wrap items-center gap-2"> <Toolbar className="print:hidden">
<div className="flex rounded-control border border-line overflow-hidden" role="group"> <Segmented value={view} onChange={setView} aria-label={t('orders.tables.viewAs')}
{['list', 'map'].map(v => ( options={views.map(v => ({ value: v, label: v === 'qr' ? t('orders.tables.qrCodes') : tc(`floorMap.${v}`), icon: viewIcon[v], testId: `tables-view-${v}` }))} />
<button key={v} type="button" aria-pressed={view === v} onClick={() => setView(v)} data-testid={`tables-view-${v}`} <ToolbarSpacer />
className={cx('px-3 py-1.5 text-label font-medium', view === v ? 'bg-accent-soft text-accent-ink' : 'bg-surface text-ink-2 hover:bg-surface-2')}>
{tc(`floorMap.${v}`)}
</button>
))}
</div>
<span className="flex-1" />
{view === 'list' && TABLE_STATES.map(s => ( {view === 'list' && TABLE_STATES.map(s => (
<button key={s} type="button" aria-pressed={states.includes(s)} onClick={() => toggleState(s)} data-testid={`tables-state-${s}`} <FilterChip key={s} tone={STATE_TONE[s]} pressed={states.includes(s)} onClick={() => toggleState(s)} data-testid={`tables-state-${s}`}
className={cx('inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border text-label font-semibold', count={cards.filter(c => c.state === s).length}>
states.includes(s) ? `${SOFT[STATE_TONE[s]]} ${BORDER[STATE_TONE[s]]}` : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
<span className={cx('w-2 h-2 rounded-full', SOLID[STATE_TONE[s]])} aria-hidden="true" />
{t(`overview.tableState.${s}`)} {t(`overview.tableState.${s}`)}
<span className="tabular-nums text-ink">{cards.filter(c => c.state === s).length}</span> </FilterChip>
</button>
))} ))}
<Select size="sm" value={zone} onChange={e => setZone(e.target.value)} aria-label={t('orders.tables.zone')} data-testid="tables-zone"> {view !== 'qr' && (
<option value="">{t('orders.tables.allZones')}</option> <Dropdown multiple value={zones} onChange={setZones} allLabel={t('orders.tables.allZones')} aria-label={t('orders.tables.zone')} data-testid="tables-zone"
{groups.map(g => <option key={g.id} value={String(g.id)}>{g.name}</option>)} options={[
<option value={NO_ZONE}>{t('orders.tables.noZone')}</option> ...groups.map(g => ({ value: String(g.id), label: g.name, dot: g.color || undefined })),
</Select> { value: NO_ZONE, label: t('orders.tables.noZone') },
</div> ]} />
)}
</Toolbar>
{view === 'qr' && <TableQrCodes />}
{view === 'map' && ( {view === 'map' && (
<LiveFloor zone={zone && zone !== NO_ZONE ? Number(zone) : null} onOpen={id => navigate(`/orders/${id}`)} /> <LiveFloor zone={oneZone} onOpen={id => navigate(`/orders/${id}`)} />
)} )}
{view === 'list' && (shown.length === 0 {view === 'list' && (shown.length === 0
? <EmptyState title={t('orders.tables.none')} /> ? <EmptyState title={t('orders.tables.none')} />
: ( : (
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(17rem,1fr))]"> <div className="grid gap-4 grid-cols-[repeat(auto-fill,minmax(min(100%,20.5rem),1fr))]">
{shown.map(card => ( {shown.map(card => (
<TableCard key={card.table.id} card={card} zone={groups.length > 1 ? groups.find(g => g.id === card.table.group_id)?.name : null} flags={flags[card.table.id] ?? []} waiterName={name} <TableCard key={card.table.id} card={card} zone={groups.length > 1 ? groups.find(g => g.id === card.table.group_id)?.name : null} flags={flags[card.table.id] ?? []} waiterName={name}
onOpen={() => navigate(cardTarget(card))} onQuick={() => setQuick(card)} /> onOpen={() => navigate(cardTarget(card))} onQuick={() => setQuick(card)} />
@@ -95,10 +104,10 @@ export default function TablesPage() {
</div> </div>
))} ))}
<PrintProblemsCard onOpen={id => navigate(`/orders/${id}`)} /> {view !== 'qr' && <PrintProblemsCard onOpen={id => navigate(`/orders/${id}`)} />}
{quick && <QuickActions card={quick} flagDefs={flagDefs} current={flags[quick.table.id] ?? []} onClose={() => setQuick(null)} />} {quick && <QuickActions card={quick} flagDefs={flagDefs} current={flags[quick.table.id] ?? []} onClose={() => setQuick(null)} />}
</div> </Page>
) )
} }
@@ -114,7 +123,7 @@ function TableCard({ card, zone, flags, waiterName, onOpen, onQuick }) {
return ( return (
<div className={cx('relative rounded-card border bg-surface shadow-raised overflow-hidden grid', BORDER[tone])} data-testid="table-card" data-state={state} data-table={table.id}> <div className={cx('relative rounded-card border bg-surface shadow-raised overflow-hidden grid', BORDER[tone])} data-testid="table-card" data-state={state} data-table={table.id}>
<span className={cx('absolute inset-y-0 left-0 w-1.5', SOLID[tone])} aria-hidden="true" /> <span className={cx('absolute inset-y-0 left-0 w-1.5', SOLID[tone])} aria-hidden="true" />
<button type="button" onClick={onOpen} className="text-left pl-5 pr-4 pt-3 pb-2 grid gap-2 hover:bg-surface-2 transition-colors duration-fast" <button type="button" onClick={onOpen} data-testid="table-open" className="text-left pl-5 pr-4 pt-4 pb-3 grid gap-2.5 hover:bg-surface-2 transition-colors duration-fast"
aria-label={t('orders.tables.open', { table: tableName(table), state: t(`overview.tableState.${state}`) })}> aria-label={t('orders.tables.open', { table: tableName(table), state: t(`overview.tableState.${state}`) })}>
<span className="flex items-start gap-2"> <span className="flex items-start gap-2">
<span className="flex-1 grid gap-1"> <span className="flex-1 grid gap-1">
@@ -137,24 +146,23 @@ function TableCard({ card, zone, flags, waiterName, onOpen, onQuick }) {
</span> </span>
<span className="grid grid-cols-2 gap-2"> <span className="grid grid-cols-2 gap-2">
<span className="grid"> <span className="grid">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.total')}</span> <span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('orders.total')}</span>
{order ? <Money value={orderTotal(order.items)} className="text-title font-semibold text-ink" /> : <span className="text-title text-ink-3">—</span>} {order ? <Money value={orderTotal(order.items)} className="text-title font-semibold text-ink" /> : <span className="text-title text-ink-3">—</span>}
</span> </span>
<span className="grid"> <span className="grid">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.tables.time')}</span> <span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('orders.tables.time')}</span>
<span className={cx('text-title tabular-nums inline-flex items-center gap-1', long ? 'font-bold text-warning-ink' : 'text-ink')}> <span className={cx('text-title tabular-nums inline-flex items-center gap-1', long ? 'font-bold text-warning-ink' : 'text-ink')}>
{order ? <><Clock size={14} aria-hidden="true" />{since(order.opened_at)}</> : <span className="text-ink-3">—</span>} {order ? <><Clock size={14} aria-hidden="true" />{since(order.opened_at)}</> : <span className="text-ink-3">—</span>}
</span> </span>
</span> </span>
</span> </span>
</button> </button>
<div className="flex items-center gap-2 pl-5 pr-2 py-2 border-t border-line"> <div className="flex items-center gap-2 pl-5 pr-2 py-1.5 border-t border-line">
<span className="flex-1 min-w-0 truncate text-label text-ink-2"> <span className="flex-1 min-w-0 truncate text-label text-ink-2">
{!order ? (table.seat_count ? t('orders.tables.seats', { count: table.seat_count }) : '') {!order ? (table.seat_count ? t('orders.tables.seats', { count: table.seat_count }) : '')
: order.waiters.length ? order.waiters.map(w => waiterName(w.waiter_id)).join(', ') : t('orders.tables.noWaiter')} : order.waiters.length ? order.waiters.map(w => waiterName(w.waiter_id)).join(', ') : t('orders.tables.noWaiter')}
</span> </span>
<IconButton size="sm" variant="ghost" label={t('orders.quick.title', { table: tableName(table) })} onClick={onQuick} data-testid="table-quick"><Zap size={16} /></IconButton> <IconButton size="sm" variant="ghost" label={t('orders.quick.title', { table: tableName(table) })} onClick={onQuick} data-testid="table-quick"><Zap size={16} /></IconButton>
<Button size="sm" variant={order ? 'secondary' : 'primary'} onClick={onOpen} data-testid="table-open">{order ? t('orders.tables.view') : t('orders.tables.take')}</Button>
</div> </div>
</div> </div>
) )
@@ -81,12 +81,13 @@ export const NO_ZONE = 'none'
/** Cards (overviewLogic.tableCards) shown for the chosen states (none = all) and zone /** Cards (overviewLogic.tableCards) shown for the chosen states (none = all) and zone
* ('' = all, NO_ZONE = tables without a zone, else a zone id as text). */ * ('' = all, NO_ZONE = tables without a zone, else a zone id as text). */
export function filterCards(cards, { states = [], zone = '' } = {}) { export function filterCards(cards, { states = [], zone = '', zones } = {}) {
// zones: several at once (the toolbar's multi-select, 2026-11-20); [] = all. zone: one (older callers)
const picked = zones ?? (zone ? [zone] : [])
return cards.filter(c => { return cards.filter(c => {
if (states.length && !states.includes(c.state)) return false if (states.length && !states.includes(c.state)) return false
if (zone === NO_ZONE) return !c.table.group_id if (!picked.length) return true
if (zone) return String(c.table.group_id ?? '') === zone return picked.some(z => (z === NO_ZONE ? !c.table.group_id : String(c.table.group_id ?? '') === z))
return true
}) })
} }
@@ -70,7 +70,7 @@ function BookingRow({ booking: b, onEdit, onStatus, onConfirm, onDecline }) {
const { formatTime, formatDateTime } = useFormat() const { formatTime, formatDateTime } = useFormat()
const table = b.table_label || (b.table_id ? `#${b.table_id}` : null) const table = b.table_label || (b.table_id ? `#${b.table_id}` : null)
return ( return (
<li className="flex items-center gap-3 px-4 py-2.5" data-testid="booking-row" data-status={b.status}> <li className="flex items-center gap-3 px-card py-3" data-testid="booking-row" data-status={b.status}>
<span className="w-12 shrink-0 text-center grid"> <span className="w-12 shrink-0 text-center grid">
<span className="text-body font-bold tabular-nums text-ink">{formatTime(b.reserved_for)}</span> <span className="text-body font-bold tabular-nums text-ink">{formatTime(b.reserved_for)}</span>
<span className="text-caption text-ink-3">{formatDateTime(b.reserved_for, { day: 'numeric', month: 'short' })}</span> <span className="text-caption text-ink-3">{formatDateTime(b.reserved_for, { day: 'numeric', month: 'short' })}</span>
@@ -6,11 +6,10 @@ import { useState } from 'react'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n' import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Spinner, cx } from '@xenia/ui' import { Button, Dialog, EmptyState, Spinner, Tabs } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import { CashTab, ChecksTab, MoneyTab, PrintersTab, StaffTab, ZonesTab } from './DaySummaryTabs' import { CashTab, ChecksTab, MoneyTab, PrintersTab, StaffTab, ZonesTab } from './DaySummaryTabs'
import { Pill } from './parts'
export default function DaySummaryDialog({ dayId, closing = false, onClose, onClosed }) { export default function DaySummaryDialog({ dayId, closing = false, onClose, onClosed }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
@@ -40,13 +39,13 @@ export default function DaySummaryDialog({ dayId, closing = false, onClose, onCl
} }
const tabs = [ const tabs = [
{ id: 'money', label: t('overview.day.tab.money') }, { id: 'money', label: t('overview.day.tab.money'), testId: 'day-tab-money' },
{ id: 'staff', label: t('overview.day.tab.staff'), badge: data?.waiters?.length }, { id: 'staff', label: t('overview.day.tab.staff'), badge: data?.waiters?.length, testId: 'day-tab-staff' },
{ id: 'zones', label: t('overview.day.tab.zones'), badge: data?.zones?.length }, { id: 'zones', label: t('overview.day.tab.zones'), badge: data?.zones?.length, testId: 'day-tab-zones' },
{ id: 'printers', label: t('overview.day.tab.printers'), badge: data?.printers?.length }, { id: 'printers', label: t('overview.day.tab.printers'), badge: data?.printers?.length, testId: 'day-tab-printers' },
...(closing ? [ ...(closing ? [
{ id: 'cash', label: t('overview.day.tab.cash') }, { id: 'cash', label: t('overview.day.tab.cash'), testId: 'day-tab-cash' },
{ id: 'checks', label: t('overview.day.tab.checks'), badge: data?.checks ? data.checks.open_orders + data.checks.active_shifts : null, warn: data?.checks?.with_unpaid_items > 0 }, { id: 'checks', label: t('overview.day.tab.checks'), badge: data?.checks ? data.checks.open_orders + data.checks.active_shifts : null, warn: data?.checks?.with_unpaid_items > 0, testId: 'day-tab-checks' },
] : []), ] : []),
] ]
@@ -58,23 +57,17 @@ export default function DaySummaryDialog({ dayId, closing = false, onClose, onCl
</>) </>)
return ( return (
<Dialog open size="lg" onClose={onClose} footer={footer || undefined} <Dialog open size="xl" onClose={onClose} footer={footer || undefined}
title={closing ? t('overview.day.closeTitle') : t('overview.day.statsTitle')} title={closing ? t('overview.day.closeTitle') : t('overview.day.statsTitle')}
description={data && <span className="inline-flex items-center gap-2"> description={data && <span className="inline-flex flex-wrap items-center gap-x-1.5 text-label" data-testid="day-status">
<Pill tone={data.status === 'open' ? 'success' : 'neutral'}>{data.status === 'open' ? t('overview.day.open') : t('overview.day.closedState')}</Pill> {data.status === 'open'
{t('overview.day.openedAt', { time: formatDateTime(data.opened_at, 'datetimeShort') })} ? <span className="inline-flex items-center gap-1.5 font-semibold text-success-ink"><span className="w-2 h-2 rounded-full bg-success" aria-hidden="true" />{t('overview.day.open')}</span>
: <span>{t('overview.day.closedState')}</span>}
<span aria-hidden="true">·</span>
<span>{t('overview.day.openedAt', { time: formatDateTime(data.opened_at, 'datetimeShort') })}</span>
</span>}> </span>}>
<div className="grid gap-4" data-testid="day-summary"> <div className="grid gap-4" data-testid="day-summary">
<div className="flex gap-1 overflow-x-auto border-b border-line -mx-1 px-1" role="tablist"> <Tabs tabs={tabs} value={tab} onChange={setTab} />
{tabs.map(tb => (
<button key={tb.id} type="button" role="tab" aria-selected={tab === tb.id} onClick={() => setTab(tb.id)} data-testid={`day-tab-${tb.id}`}
className={cx('flex items-center gap-1.5 px-3 py-2 -mb-px border-b-2 text-label whitespace-nowrap transition-colors duration-fast',
tab === tb.id ? 'border-accent text-ink font-semibold' : 'border-transparent text-ink-2 hover:text-ink')}>
{tb.label}
{tb.badge != null && <span className={cx('min-w-5 px-1 rounded-full text-caption font-bold tabular-nums', tb.warn ? 'bg-danger-soft text-danger-ink' : 'bg-surface-2 text-ink-2')}>{tb.badge}</span>}
</button>
))}
</div>
{isPending && <div className="py-10 flex justify-center"><Spinner /></div>} {isPending && <div className="py-10 flex justify-center"><Spinner /></div>}
{error && <EmptyState compact title={errorMessage(error, t)} />} {error && <EmptyState compact title={errorMessage(error, t)} />}
{data && (<> {data && (<>
@@ -9,7 +9,7 @@ import { PAY_METHODS, cashCheck, paymentTotals } from './overviewLogic'
import { Avatar, Figure, Money, Pill, SplitBar } from './parts' import { Avatar, Figure, Money, Pill, SplitBar } from './parts'
import { SOFT } from './tones' import { SOFT } from './tones'
const PAY_TONE = { cash: 'success', card: 'info', transfer: 'accent', treat: 'warning', other: 'neutral' } const PAY_TONE = { cash: 'success', card: 'info', transfer: 'accent', treat: 'warning', other: 'neutral', onTab: 'special' }
function usePayParts() { function usePayParts() {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
@@ -18,7 +18,7 @@ function usePayParts() {
function Row({ label, value, tone, warn, indent, sub, info }) { function Row({ label, value, tone, warn, indent, sub, info }) {
return ( return (
<div className={cx('flex items-baseline justify-between gap-3 py-1', indent && 'pl-4 text-label')}> <div className={cx('flex items-baseline justify-between gap-3 py-1 text-label', indent && 'pl-4')}>
<span className={cx('flex-1 flex items-center gap-1', warn ? 'text-warning-ink' : indent ? 'text-ink-2' : 'text-ink')}>{label}{info}</span> <span className={cx('flex-1 flex items-center gap-1', warn ? 'text-warning-ink' : indent ? 'text-ink-2' : 'text-ink')}>{label}{info}</span>
<span className="text-right grid"> <span className="text-right grid">
<span className={cx('font-semibold tabular-nums', tone ?? 'text-ink')}>{value}</span> <span className={cx('font-semibold tabular-nums', tone ?? 'text-ink')}>{value}</span>
@@ -30,13 +30,23 @@ function Row({ label, value, tone, warn, indent, sub, info }) {
function Section({ title, children, shaded }) { function Section({ title, children, shaded }) {
return ( return (
<div className={cx('px-4 py-3 border-b border-line last:border-b-0', shaded && 'bg-surface-2')}> <div className={cx('px-card py-card-y border-b border-line last:border-b-0', shaded && 'bg-surface-2')}>
<div className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{title}</div> <div className="text-overline font-semibold uppercase tracking-wide text-ink-3 mb-1.5">{title}</div>
{children} {children}
</div> </div>
) )
} }
/** One of the day's figures in its own box (v1's stat boxes). */
function StatBox({ label, children }) {
return (
<div className="rounded-card border border-line bg-surface-2 px-4 py-3 grid gap-1 content-start min-w-0">
<span className="text-overline font-semibold uppercase tracking-wide text-ink-3 truncate">{label}</span>
<span className="text-title font-bold tabular-nums text-ink truncate">{children}</span>
</div>
)
}
export function MoneyTab({ data }) { export function MoneyTab({ data }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const { formatMoney, formatDateTime } = useFormat() const { formatMoney, formatDateTime } = useFormat()
@@ -45,15 +55,14 @@ export function MoneyTab({ data }) {
const sign = v => (v >= 0 ? 'text-success-ink' : 'text-danger-ink') const sign = v => (v >= 0 ? 'text-success-ink' : 'text-danger-ink')
return ( return (
<div className="grid gap-4" data-testid="day-money"> <div className="grid gap-4" data-testid="day-money">
<div className="grid grid-cols-2 md:grid-cols-4 gap-3"> {/* the six figures of the day, each in its own box, all the same size (as in v1) */}
<Figure label={t('overview.day.revenue')}><Money value={data.total_revenue} /></Figure> <div className="grid grid-cols-2 sm:grid-cols-3 gap-3" data-testid="day-figures">
<Figure label={t('overview.day.orders')}>{data.total_orders}</Figure> <StatBox label={t('overview.day.revenue')}><Money value={data.total_revenue} /></StatBox>
<Figure label={t('overview.day.items')}>{data.total_items_ordered}</Figure> <StatBox label={t('overview.day.orders')}>{data.total_orders}</StatBox>
<Figure label={t('overview.day.waiters')}>{staff.length}</Figure> <StatBox label={t('overview.day.items')}>{data.total_items_ordered}</StatBox>
</div> <StatBox label={t('overview.day.waiters')}>{staff.length}</StatBox>
<div className="flex flex-wrap gap-6"> <StatBox label={t('overview.day.opened')}>{formatDateTime(data.opened_at, 'datetimeShort')}</StatBox>
<Figure label={t('overview.day.opened')}>{formatDateTime(data.opened_at, 'datetimeShort')}</Figure> <StatBox label={t('overview.day.closed')}>{data.closed_at ? formatDateTime(data.closed_at, 'datetimeShort') : <span className="text-success-ink">{t('overview.day.stillOpen')}</span>}</StatBox>
<Figure label={t('overview.day.closed')}>{data.closed_at ? formatDateTime(data.closed_at, 'datetimeShort') : <span className="text-success-ink">{t('overview.day.stillOpen')}</span>}</Figure>
</div> </div>
<div className="rounded-card border border-line overflow-hidden"> <div className="rounded-card border border-line overflow-hidden">
@@ -108,13 +117,16 @@ export function MoneyTab({ data }) {
</div> </div>
<div className="grid gap-2"> <div className="grid gap-2">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('overview.day.payments')}</span> <span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('overview.day.payments')}</span>
{data.total_revenue > 0 ? <SplitBar parts={pay(paymentTotals(data.waiters))} /> : <span className="text-label text-ink-3">—</span>} {/* lines put on tabs are sold but not paid: their own part of the bar */}
{data.total_revenue + (data.tabbed_revenue || 0) > 0
? <SplitBar parts={[...pay(paymentTotals(data.waiters)), { key: 'onTab', tone: PAY_TONE.onTab, label: t('overview.pay.onTab'), value: data.tabbed_revenue || 0 }]} />
: <span className="text-label text-ink-3">—</span>}
</div> </div>
{data.store_closing_cash != null && ( {data.store_closing_cash != null && (
<div className="rounded-card border border-line px-4 py-3"> <div className="rounded-card border border-line px-card py-card-y">
<div className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('overview.day.drawer')}</div> <div className="text-overline font-semibold uppercase tracking-wide text-ink-3 mb-1.5">{t('overview.day.drawer')}</div>
<Row label={t('overview.day.drawerExpected')} value={formatMoney(data.store_expected_closing)} /> <Row label={t('overview.day.drawerExpected')} value={formatMoney(data.store_expected_closing)} />
<Row label={t('overview.day.drawerCounted')} value={formatMoney(data.store_closing_cash)} /> <Row label={t('overview.day.drawerCounted')} value={formatMoney(data.store_closing_cash)} />
<Row label={t('overview.day.drawerDiff')} warn={data.store_cash_discrepancy !== 0} <Row label={t('overview.day.drawerDiff')} warn={data.store_cash_discrepancy !== 0}
@@ -140,7 +152,7 @@ export function StaffTab({ data }) {
return ( return (
<div key={w.waiter_id} className="rounded-card border border-line overflow-hidden"> <div key={w.waiter_id} className="rounded-card border border-line overflow-hidden">
<button type="button" onClick={() => setOpen(shown ? null : w.waiter_id)} aria-expanded={shown} <button type="button" onClick={() => setOpen(shown ? null : w.waiter_id)} aria-expanded={shown}
className="w-full flex flex-wrap items-center gap-3 px-4 py-3 text-left bg-surface hover:bg-surface-2"> className="w-full flex flex-wrap items-center gap-x-6 gap-y-3 px-card py-card-y text-left bg-surface hover:bg-surface-2">
<Avatar name={w.waiter_name} /> <Avatar name={w.waiter_name} />
<span className="flex-1 min-w-32 grid"> <span className="flex-1 min-w-32 grid">
<span className="text-body font-semibold text-ink">{w.waiter_name}</span> <span className="text-body font-semibold text-ink">{w.waiter_name}</span>
@@ -155,7 +167,7 @@ export function StaffTab({ data }) {
<ChevronDown size={16} className={cx('text-ink-3 transition-transform duration-base', shown && 'rotate-180')} aria-hidden="true" /> <ChevronDown size={16} className={cx('text-ink-3 transition-transform duration-base', shown && 'rotate-180')} aria-hidden="true" />
</button> </button>
{shown && ( {shown && (
<div className="border-t border-line bg-surface-2 p-4 grid gap-3"> <div className="border-t border-line bg-surface-2 p-card grid gap-4">
<div className="grid grid-cols-2 md:grid-cols-4 gap-3"> <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<Figure label={t('overview.day.shiftStart')}>{w.shift_started_at ? formatTime(w.shift_started_at) : '—'}</Figure> <Figure label={t('overview.day.shiftStart')}>{w.shift_started_at ? formatTime(w.shift_started_at) : '—'}</Figure>
<Figure label={t('overview.day.shiftEnd')}>{w.shift_ended_at ? formatTime(w.shift_ended_at) : <span className="text-success-ink">{t('overview.day.shiftRunning')}</span>}</Figure> <Figure label={t('overview.day.shiftEnd')}>{w.shift_ended_at ? formatTime(w.shift_ended_at) : <span className="text-success-ink">{t('overview.day.shiftRunning')}</span>}</Figure>
@@ -181,7 +193,7 @@ export function ZonesTab({ data }) {
return ( return (
<div className="grid gap-2" data-testid="day-zones"> <div className="grid gap-2" data-testid="day-zones">
{data.zones.map(z => ( {data.zones.map(z => (
<div key={z.group_id} className="rounded-card border border-line p-4 grid gap-3"> <div key={z.group_id} className="rounded-card border border-line p-card grid gap-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{/* a zone's colour is the venue's choice (data), not styling */} {/* a zone's colour is the venue's choice (data), not styling */}
<span className={cx('w-3 h-3 rounded-sm shrink-0', !z.color && 'bg-ink-3')} style={z.color ? { background: z.color } : undefined} aria-hidden="true" /> <span className={cx('w-3 h-3 rounded-sm shrink-0', !z.color && 'bg-ink-3')} style={z.color ? { background: z.color } : undefined} aria-hidden="true" />
@@ -210,7 +222,7 @@ export function PrintersTab({ data }) {
{data.printers.map(p => { {data.printers.map(p => {
const rate = p.jobs > 0 ? Math.round((p.success / p.jobs) * 100) : 0 const rate = p.jobs > 0 ? Math.round((p.success / p.jobs) * 100) : 0
return ( return (
<div key={p.printer_id} className="rounded-card border border-line p-4 grid gap-3"> <div key={p.printer_id} className="rounded-card border border-line p-card grid gap-3">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<span className="w-9 h-9 grid place-items-center rounded-control bg-surface-2 text-ink-2"><Printer size={18} aria-hidden="true" /></span> <span className="w-9 h-9 grid place-items-center rounded-control bg-surface-2 text-ink-2"><Printer size={18} aria-hidden="true" /></span>
<span className="flex-1 grid"> <span className="flex-1 grid">
@@ -247,8 +259,8 @@ export function CashTab({ data, counted, onCounted, value }) {
const tone = check ? (check.state === 'even' ? 'success' : 'danger') : null const tone = check ? (check.state === 'even' ? 'success' : 'danger') : null
return ( return (
<div className="grid gap-4" data-testid="day-cash"> <div className="grid gap-4" data-testid="day-cash">
<div className="rounded-card border border-line bg-surface-2 px-4 py-3"> <div className="rounded-card border border-line bg-surface-2 px-card py-card-y">
<div className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('overview.day.takings')}</div> <div className="text-overline font-semibold uppercase tracking-wide text-ink-3 mb-1.5">{t('overview.day.takings')}</div>
<Row label={t('overview.day.staffTook')} value={formatMoney(data.total_waiter_collected)} /> <Row label={t('overview.day.staffTook')} value={formatMoney(data.total_waiter_collected)} />
{data.tabs?.received_outside_shifts?.total > 0 && <Row indent label={t('overview.day.tabOutsideShifts')} value={formatMoney(data.tabs.received_outside_shifts.total)} {data.tabs?.received_outside_shifts?.total > 0 && <Row indent label={t('overview.day.tabOutsideShifts')} value={formatMoney(data.tabs.received_outside_shifts.total)}
info={<InfoTip>{t('overview.day.tabOutsideShiftsTip')}</InfoTip>} />} info={<InfoTip>{t('overview.day.tabOutsideShiftsTip')}</InfoTip>} />}
@@ -38,7 +38,7 @@ export default function MessagesCard({ staff, tables }) {
const to = messageTargets(m, staff) const to = messageTargets(m, staff)
const acks = messageAcks(m, staff.length) const acks = messageAcks(m, staff.length)
return ( return (
<li key={m.id} className="flex items-start gap-3 px-4 py-2.5" data-testid="message-row"> <li key={m.id} className="flex items-start gap-3 px-card py-3" data-testid="message-row">
<span className="flex-1 min-w-0 grid"> <span className="flex-1 min-w-0 grid">
<span className="text-body font-semibold text-ink">{m.body}</span> <span className="text-body font-semibold text-ink">{m.body}</span>
<span className="text-caption text-ink-3">{t('overview.messages.to', { who: to ? to.join(', ') : t('overview.messages.everyone'), time: formatTime(m.created_at) })}</span> <span className="text-caption text-ink-3">{t('overview.messages.to', { who: to ? to.join(', ') : t('overview.messages.everyone'), time: formatTime(m.created_at) })}</span>
@@ -27,7 +27,7 @@ export default function NotesCard() {
return ( return (
<div className="relative" onMouseEnter={enter} onMouseLeave={leave}> <div className="relative" onMouseEnter={enter} onMouseLeave={leave}>
<button type="button" onClick={() => navigate('/notes')} onFocus={() => setPreview(true)} onBlur={leave} <button type="button" onClick={() => navigate('/notes')} onFocus={() => setPreview(true)} onBlur={leave}
className="w-full flex items-center gap-3 p-4 rounded-card border border-line bg-surface shadow-raised text-left hover:shadow-popover transition-shadow duration-fast" className="w-full flex items-center gap-3 px-card py-4 rounded-card border border-line bg-surface shadow-raised text-left hover:shadow-popover transition-shadow duration-fast"
data-testid="notes-card"> data-testid="notes-card">
<span className="flex-1 min-w-0 grid"> <span className="flex-1 min-w-0 grid">
<span className="text-body-lg font-semibold text-ink">{t('overview.notes.title')}</span> <span className="text-body-lg font-semibold text-ink">{t('overview.notes.title')}</span>
@@ -41,7 +41,7 @@ export default function NotesCard() {
{items.map(item => { {items.map(item => {
const Icon = item.kind === 'todo' ? (item.is_done ? CheckSquare : Square) : item.is_pinned ? Pin : FileText const Icon = item.kind === 'todo' ? (item.is_done ? CheckSquare : Square) : item.is_pinned ? Pin : FileText
return ( return (
<li key={`${item.kind}-${item.id}`} className="flex items-start gap-2 px-4 py-2.5"> <li key={`${item.kind}-${item.id}`} className="flex items-start gap-2 px-card py-2.5">
<Icon size={14} className="mt-0.5 shrink-0 text-ink-3" aria-hidden="true" /> <Icon size={14} className="mt-0.5 shrink-0 text-ink-3" aria-hidden="true" />
<span className={cx('text-label text-ink line-clamp-2', item.is_done && 'line-through opacity-50')}>{item.body}</span> <span className={cx('text-label text-ink line-clamp-2', item.is_done && 'line-through opacity-50')}>{item.body}</span>
</li> </li>
@@ -112,7 +112,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
<div className="grid gap-3 -mx-2" data-testid="order-dialog"> <div className="grid gap-3 -mx-2" data-testid="order-dialog">
{order.waiters.length > 0 && ( {order.waiters.length > 0 && (
<div className="flex flex-wrap items-center gap-2 px-2"> <div className="flex flex-wrap items-center gap-2 px-2">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('overview.order.staff')}</span> <span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('overview.order.staff')}</span>
{order.waiters.map(w => <Pill key={w.waiter_id} tone="accent">{nameOf(w.waiter_id)}</Pill>)} {order.waiters.map(w => <Pill key={w.waiter_id} tone="accent">{nameOf(w.waiter_id)}</Pill>)}
</div> </div>
)} )}

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