Compare commits

..
25 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 3eeafb565a feat(backend,waiter,terminal,manager): split the bill by amount
Owner 2026-11-23 (plan 6F.6). Venue setting payments.split_amount (off | two_equal | two_custom |
multiple_equal, each level with the ones before; default off) and payments.split_max_parts (10);
key ordering.payments.split_amount (everyone who takes payments; Alembic 0050 grants it).
POST /api/orders/{id}/split-bills settles the chosen unpaid lines (status 'split': sold, no shift,
no payment method) and adds part lines (system product split_part, "Split bill 1/3", printed and
served; equal parts with the remainder on the last, or two parts with part 1 typed). Parts are paid
like any line (cash, card, tab). POST .../split-bills/{bill}/undo while no part is paid or tabbed.
Counting (services/sales.py): settled lines are the sales, parts never (a refunded part comes off
the settled lines by share); drawers and payment methods count the parts. Older reports use
split_bills.sold_filter / counts_as_sale. Locks: parts can't be cancelled, moved, combined or
re-priced; settled lines are no longer active; closing or cancelling an order with unpaid parts is
refused. Fiscal: one receipt with the settled lines when the last part is paid, with each method's
amount (txt driver: CD per card amount, then CR for cash).
Waiter: Pay -> "Split the amount" (pre-filled from the customers), the split bill above the lines
with Undo. Counter: "By amount" in the payment (quick sale split and paid at once, Q-4; a table's
lines split then paid). Manager: the pay dialog splits, the order shows its split bills, Settings ->
Operation card. Shared rules in @xenia/ordering/split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:57:54 +02:00
bonaminandClaude Opus 5.5 72e175ab73 feat(backend,waiter,terminal,manager): +1 on a sent line and changing a line's quantity
Owner 2026-11-23 (plan 6F.5). Product flag one_more_enabled (off by default; product editor).
POST /api/orders/{id}/items/{item}/again: a new line like the old one (choices, removed, note,
course), priced now, sent to the kitchen like any new line. Waiter app and the counter's table
panel: +1 beside such lines; the first tap arms it, more taps count up, 'Send +N' sends, 4 s idle
disarms (no stray sends).
POST /api/orders/{id}/items/{item}/quantity: venue setting orders.quantity_change (off | add_only |
add_and_remove, default off), key ordering.items.change_quantity (owner, store manager; Alembic 0049
grants it); up only changes the line, down cuts a cancelled part ('quantity lowered', split_from_id)
and prints a cancellation only when asked (the dialog presets yes while the kitchen hasn't finished).
Waiter: 'Change quantity' in a line's actions (now -> new, -/+). cut_part() now shared with split.
GET /api/orders/{id} items carry the product's one_more_enabled / unit_type, deal ids, split_from_id,
cancel_reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:26:46 +02:00
bonaminandClaude Opus 5.5 0a353c5f97 feat(backend,waiter,manager): moves between tables and orders on the record
Owner 2026-11-23 (plan 6F.4). services/moves.py: every table transfer, lines moved and orders merged
is an order_moves row with its lines (order_move_items: line, quantity then); OrderItem.split_from_id
links a split part to its line, so a part carries the moves made before the split; combining moves
the removed lines' moves to the kept one. Alembic 0048: the tables, the column, and a backfill from
the audit notes written before (note='backfill'). A split part now also keeps the line's price change,
kitchen state, course, cost and names (it used to restart as pending at the menu price).
GET /api/orders/{id}/moves (the order's path, each line's); GET /api/reports/moves (+ export).
Waiter: a moved order's banner (T2 -> T5), moved lines marked, a line's Move history. Manager: the
order's Moves tab, each moved line's path, Reports -> Moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:03:11 +02:00
bonaminandClaude Opus 5.5 f87f9ff23c feat(backend,waiter,manager): prices changed by hand are on the record
Owner 2026-11-23 (plan 6F.3). services/price_changes.py: the venue's switch orders.price_change
(off | before_sending | anytime, default anytime as before), orders.price_change_reason and its
quick reasons; keys ordering.prices.modify (the cart), new modify_sent (a sent or served line) and
view_changes (who sees them). Every by-hand price (waiter cart, a sent line, the counter's %
discount) writes a manual_price PriceEventLog row (before, after, quantity, who, approving manager,
stage, reason) plus a PRICE_CHANGED audit row; before, the sent-line change overwrote the price with
no record. Alembic 0047: event columns; modify_sent for everyone holding modify (and the venues'
role overrides), view_changes for owners and store managers.
Waiter: the reason picker when the venue asks, a sent line's price on modify_sent and the venue's
switch, the line's price history. Manager: Settings -> Operation 'Prices changed by hand', the
changes on the order's lines and history, Reports -> Cancellations, discounts and price changes
(+ export). Counter: no discount when the venue turned price changes off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 07:41:43 +02:00
bonaminandClaude Opus 5.5 e3f4f3eeee feat(manager,waiter): money and weights typed with a comma or a dot everywhere
Owner 2026-11-23 (plan 6F.2): new DecimalInput / MoneyInput in @xenia/ui (keeps what is typed,
reports a number, null when empty, NaN when not a number) on parseNumber. The waiter app's starting
cash, weighed quantity and typed prices were type=number + parseFloat (a Greek keypad's comma was
dropped: 12,50 became 12 or nothing); now text fields read with parseNumber, and a wrong starting
cash shows a message. The manager's price rules, deals and order-total condition use the new
fields; every Number(x.replace(',', '.')) now reads through parseNumber (1.234,50 too). Guard test
packages/i18n/tests/typed-numbers.test.mjs refuses parseFloat, .replace(',', '.') and decimal
type=number fields in the apps. e2e: shift close with 20,50, waiter starting cash 25,50.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 07:08:54 +02:00
bonaminandClaude Opus 5.5 e708202f3a feat(manager): help tips on the settings and fields people tend to misread
Owner 2026-11-23 (plan 6F.1b): 26 new tips in English and Greek: Operation (own shifts, hidden
takings, card payments, closing tables, the serve step, courses, quick notes), Sign-in (waiter and
device modes, usernames, one session, idle sign-out), venue language and time zone, the fiscal
device, locking, the server's address, the product editor (unit, available, quick add, VAT group,
cost), a device's sign-in, a person's role, the cash counted at a shift's end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 06:41:37 +02:00
bonaminandClaude Opus 5.5 99145e83da feat(manager): help tips open after 1.5 s of hover, at once on click
Owner 2026-11-23 (plan 6F.1a): InfoTip waits INFOTIP_HOVER_MS (1500 ms) with the pointer on the i
before opening (leaving earlier cancels); a click or tap still opens it at once and keeps it open.
ui e2e checks the delay, the cancel and the click, and now runs without any backend (a Docker stack
left on :8000 in Greek made the i18n sample fail).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 06:34:55 +02:00
bonaminandClaude Opus 5.5 33a5125abc feat(manager): Settings full width with its cards in columns, tabs that wrap instead of hiding
Owner 2026-11-23 (plan 6F.0): Settings was the only 880 px page and its 11 tabs scrolled out of
sight ('Operatio...'). Now full width like every page; each tab's cards sit in the new @xenia/ui
<Columns> (cards flow down then across, 34rem columns: two on 1080p, three on an ultrawide, one on a
laptop), settings rows keep switches at the right edge. Tabs everywhere wrap onto another row when
they don't fit. manager_layout e2e: Settings tabs, a 1366x768 screen, every tab visible.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 06:24:44 +02:00
bonaminandClaude Opus 5.5 cd8218689c feat(signage): widget settings regrouped (main / Text and colours / More), alignment that lines up multi-line widgets, multi-line texts, gallery title, logos larger than the slide; calibration past the recognised resolution and shown the first time
Owner review 2026-11-23 of every widget:
- A widget card is its main settings (the row and what needs room under it: pictures, a gallery's
  pictures or folder, weather details and place, a countdown's start and end, reviews' stars and
  author, a scrolling text's speed, a shape's colours and border, QR caption), then "Text and
  colours" (new LookFields.jsx: text colour, plate, font, style, size, weight, highlight, shadow,
  QR colours; a logo's / gallery's border), then More settings (opacity, rotation, animation, fit,
  typing, blink, QR logo; shadow / border only where there is no Text and colours).
- Date format / separator and clock 12/24 / separator are main settings.
- Alignment only where it lines something up; the TV now aligns the lines of a text, the hours
  (centre: days and times meet in the middle), contact rows, Wi-Fi (code left / right / above),
  the weather's column / card / list / hourly, reviews (stars too), a countdown, a QR caption.
- Text and message: a 2-line textarea in its own row; Enter makes new lines (the TV sizes by the
  longest line and the number of lines).
- Gallery: a title above or below the pictures (title_position).
- A widget's box may reach 400 % of the slide (a logo zoomed in past the slide's edges saved again).
- "Auto" stays "Auto" in Greek; scrolling text Left / Right; reviews' stars choice no longer clipped;
  countdown "When it ends" hint as an info tip (fields level).

Calibration: an edge may go past the recognised window (down to -2000 px); the dialog's rows are
centred, "Each click moves" sits above its choice, the window size is labelled "Recognised
resolution" with what it means; the TV asks for its screen answer on every calibrate event and
while calibrating (the outline shows the first time), the dialog sends "on" again after 1.5 s.
NumberInput takes a leading minus when min < 0. E2E: waits for the Add-a-slide dialog to go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 05:40:04 +02:00
bonaminandClaude Opus 5.5 1b111c0e27 feat: the venue's identity in every app: its colour as the accent of the waiters' phones and every terminal screen, customer display looks on the identity, the signage logo widget falls back to the venue's logo
Settings -> Venue -> accent "The venue's identity" (venue.theme = identity): bootstrap
carries the identity's first colour and logos; @xenia/ui applyVenueTheme makes the
accent tokens (light and dark, readable foregrounds) from it. A display look's
"Colours and logo" can be the venue's identity. Plan 6R.20, F-117.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:30:14 +02:00
bonaminandClaude Opus 5.5 0bd32d9171 fix(signage): the stacks test follows the 7-day forecast (6R.18: from + days capped at 7, not 3)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:10:25 +02:00
bonaminandClaude Opus 5.5 84c2d5b2d8 feat(signage): the weather all the way: a week, the next hours, feels like, humidity, wind, rain chance, sunrise / sunset, UV, in words; row, column, card, list of days or hourly layouts
services/weather.py asks Open-Meteo for 7 days, the next 24 hours and the details
(mph for Fahrenheit); older answers without them still read. The widget's layout,
the details it adds and the place's name; up to 7 days. Plan 6R.18, F-116.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:07:03 +02:00
bonaminandClaude Opus 5.5 673113aff7 feat(signage): More settings for every widget (opacity, rotation, shadow, border, entrance animation, a logo's fit; text weight, highlight, typing out; date and clock formats; a logo in a QR code)
Folded under each widget card like Text and colours. The TV puts them on the element
that places the widget (fx), animations on translate / scale so its place's transform
stays (an older TV only fades); an entrance animates to the widget's own opacity.
Calibrating: a strict-mode remount no longer ends it. Plan 6R.17, F-115.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:01:42 +02:00
bonaminandClaude Opus 5.5 1eb7e5e3a9 feat(signage): gallery widget (pictures and videos one after another, from a list or a media folder); media folders on the Media page
Folders are only a grouping in the database (media_folders, media.folder_id, Alembic
0046): made, renamed, deleted (files stay) on the Media page, a file filed from its
details, uploads go into the folder shown, the picker filters by folder. The gallery
widget: its own pictures/videos in order or a folder as it is now, seconds each,
fade / slide / zoom, cover / contain. Plan 6R.16, F-114.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:41:17 +02:00
bonaminandClaude Opus 5.5 189bd2777b feat(signage): reviews typed in by hand and their widget; Add a widget at the top of the widgets, the list in layers (new widgets on top)
Reviews (name, stars, text, date, where) under Signage -> Message & settings, shown
one at a time by the reviews widget (a minimum of stars, seconds each); not pulled
from Google (owner's choice). The widgets section: one "Add a widget" menu at its
top instead of a button per kind; the cards are layers, the top one drawn over the
others, so a new widget goes on top; the arrows bring forward / send backward.
Plan 6R.19, F-113.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:21:17 +02:00
bonaminandClaude Opus 5.5 f26e51273c feat(signage): new widgets (shape, scrolling text, countdown, opening hours, Wi-Fi, contact details); the venue's opening hours on the server, edited on the Schedule page
Shapes: rectangle, circle, triangle, polygon, star or own corners, fill or gradient,
border. Countdown: to a time every day or a date, from now / a span before / a set
time, in venue time (the slide shows what is left right now). Opening hours, Wi-Fi
(with a join-the-network code) and contact details read the venue's identity and
opening hours (GET/PUT /api/identity/hours; Schedule -> Opening hours, shaded on its
timeline); the editor warns with a link when they're missing. Plan 6R.15, F-112.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 13:24:54 +02:00
bonaminandClaude Opus 5.5 2a38602d45 feat(manager): the venue's identity (Settings -> Identity): name, slogan, named colours, logos, guest Wi-Fi, contact details
Set once (GET/PUT /api/identity, venue.name + venue.identity); every colour field
offers the venue's colours first (VenueColoursProvider in @xenia/ui); signage screens
get the identity and the venue's time zone with their venue and are told on a change;
logos are protected in the media library; wifiQr() for the join-the-network code.
Plan 6R.14, F-111.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 13:10:58 +02:00
bonaminandClaude Opus 5.5 1c8d45e00c feat(signage): slides keep their shape on any screen, custom shapes (21:9, 16:10…), Calibrate the picture edge by edge with presets
A slide is drawn at its playlist's shape, as large as fits the screen's picture,
the bands in its own background (or stretched, the screen's choice). Playlists and
library slides may have a shape of their own (aspect, Alembic 0045). Signage ->
Screens -> Calibrate the picture: the TV outlines its area with arrows and its size,
each edge moves pixel by pixel or a preset centres a shape; the TV follows live
(signage.calibrate) and reports its window (POST /screen/viewport). Plan 6R.13, F-110.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 13:04:24 +02:00
bonaminandClaude Opus 5.5 d5c19e17ce fix(signage): Screens tab full width (the devices note and each screen, one per row; its fields up to 4xl)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:05:23 +02:00
bonaminandClaude Opus 5.5 14d592d963 feat(terminal): older TVs get a legacy build with a compatibility layer; modern output unchanged
- @vitejs/plugin-legacy: browsers without import.meta.resolve (older than Chrome 105 /
  Firefox 106 / Safari 16.4) load a second copy built for Chrome 79 / Firefox 78 / Safari 13
  with polyfills. The modern targets and the stylesheet stay on Vite's own defaults, so modern
  chunks are byte-identical to before (only plugin-legacy's 230-byte guard in the entry).
- terminal/src/compat.js (legacy copy only): swaps in <name>.compat.css (lightningcss for the
  older targets), sets container-size variables for signage slides, emulates flex gap.
- @xenia/signage cq()/CQ_BOX: container units as before where supported, calc(var()) fallback
  otherwise; EmbeddedSlide no longer uses inline `inset`.
- Shared Notice (@xenia/ui); "Devices that work" in Pair a device and Signage -> Screens (EN/EL).
- tests/e2e/compat.mjs: modern browser loads nothing extra; a simulated older TV runs the legacy
  copy and the layer, pairs, and plays a slide at the same sizes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 17:26:16 +02:00
bonaminandClaude Opus 5.5 aa8ba5d1d4 feat(signage): menus play whole rounds, seconds fields with − / +, widget limit setting, widgets as big as their content (owner review 6)
- A menu board with pages plays whole rounds (menuMs rounds its seconds up); the editor says how
  long it really plays under "Seconds on screen", the card and the playlist total use it.
- Seconds on screen / per page: shared NumberInput (− / +, may be emptied: an error under the
  field and Save blocked until filled; 1 s at least, server ge=1).
- Performance (Signage -> Message & settings): widgets per slide (signage.max_widgets, 10
  recommended, up to 50), checked by the server (signage.too_many_widgets) and the editor.
- Text, clock, date, QR, weather, logo placed by hand: the box is exactly the content (its height
  x text size sets the size, the width follows; handles scale keeping the shape; text size grows
  the box); a slide's widget may run off the slide while 5 % stays on it.
- Slider: the value as close to the slider as the frame's padding; floor and table-colour sliders
  use the shared Slider. Timeline cards' ring no longer clipped; larger playlist buttons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 15:11:48 +02:00
bonaminandClaude Opus 5.5 aa3fe85053 feat(signage): venue badges, widgets' own look, widgets placed inside stacks, Save and leave, shared controls (owner review 5)
- Badges: the venue's list (setting signage.badges: names el/en, colours, an icon from a food and
  drink set) edited under Signage -> "Message & settings"; sent with the venue to screens and
  previews; several badges per product (MenuList.badges lists, a single one still read) in the
  shared multiple Dropdown; a board's badge colour / text colour override them (None = each own).
- Widgets: colour, background plate, font, bold / italic / underline, text size, QR colours;
  widgets in a stack's part get every setting, vertical alignment, and a custom box inside their
  place, picked (stack, then widget) and dragged on the preview (selection by path "2.1.0").
- Menu slides: vertical alignment of the list (board_valign); "Where the list sits" is now
  "Horizontal alignment".
- Message of the day: one component in the settings tab, on the Overview and from its widget.
- Leaving a slide with changes: "Save and leave" (ConfirmDialog altLabel).
- @xenia/ui: ColourField (with colour.js helpers), FieldRow (framed only while wrapped), Slider,
  IconPicker, Segmented multiple; native selects on the Overview and signage replaced by Dropdown,
  the device settings' colour input by ColourField.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 14:17:27 +02:00
bonaminandClaude Opus 5.5 aaa0914778 feat(signage): look rows that wrap, one colour field with opacity, badges' text, several widgets per stack part, pages up to 2200 px (owner review 4)
- Menu text look: each field names its part ("Headings size"), rows wrap in aligned columns on
  alternating bands; names align left / right; line and letter spacing as lists (Auto default);
  each field changes only itself (followers frozen before the other changes); badge colour +
  badge text colour (auto: readableOn); "Reset the look" with a question.
- ColourField everywhere in signage: a Popover panel (new @xenia/ui Popover, portal, kept in the
  window) with 12 presets, picker, opacity (#rrggbbaa) and typed code; HEX accepts 8 digits.
- Stacks: Cell.widgets (a stored `widget` still reads), several widgets per part laid across the
  stack's direction; extras by path stack.part.place; Add a widget adds, each removable / ordered.
- Page rule: --x-page-max is 2200px (no longer follows the window height).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 12:53:14 +02:00
bonaminandClaude Opus 5.5 e8c8ec825e feat(signage): menu look part by part, board-only names, stack bar, Delete key (owner review 3)
- Menus (slides and widgets): headings / names / prices each with size,
  colour, font, bold / italic / underline and alignment; dots size, colour
  and style; line and letter spacing; photo size and shape (menuLook)
- Names aligned right end together, prices in a page-wide column
- Names for one board only (names, category_names) with a pencil on the
  board's list; the catalogue name stays for the waiters
- Fixed: menu lists inherited the page's fixed line height (big text
  overlapped); a menu slide's list grew past the screen (no 2nd column)
- Stacks: parts sized by dragging the lines on the bar; "Add a widget"
- Delete / Backspace removes the picked widget

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:51:03 +02:00
bonaminandClaude Opus 5.5 1b993e4573 feat(signage): stacks, menu and text widgets, widget order (owner review 2)
- Stacks: horizontal / vertical, 2-6 parts with % shares; each part shows
  a widget, a stack one level deep, or a whole Slides-library slide
- Menu widget (a board's list in its box), text widget, weather for
  tomorrow / the day after and in picture / degrees / both styles
- Widgets' order (arrows, drag with a drop line), drawn in list order;
  arrow keys move the picked widget from its card too
- Server: extras by widget path (QR links, menus, embedded slides),
  POST /preview/slide, resolve(keep_hidden) so hidden products stay
  greyed in the editor's list; screens told when an embedded slide changes
- Editor rows tidied: framed sliders, colours as fields, text look on one
  row, Switch boxed toggles from its whole frame

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:44:23 +02:00
250 changed files with 13650 additions and 1175 deletions
+16 -5
View File
@@ -16,7 +16,7 @@
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 width:** it fills the content area up to 2200 px (`--x-page-max`). On a 1080p monitor the page fills the screen; on an ultrawide it stays 2200 px wide and is **centred**. The width never depends on the window's height (owner 2026-11-21: a short window used to narrow the page),
- **the padding and gaps** (`--x-page-pad`, `--x-page-gap`), the same on every page.
```jsx
@@ -30,11 +30,12 @@ Every page's root is `<Page>` from `@xenia/ui`. It provides:
</Page>
```
- `top={<Tabs … />}` keeps a tab strip above the scrolling part (Online orders, Settings). The tab is kept in the address (`?tab=`).
- `top={<Tabs … />}` keeps a tab strip above the scrolling part (Online orders, Settings). The tab is kept in the address (`?tab=`). Tabs that don't fit **wrap onto another row**; they are never hidden in a sideways scroll (6F.0, owner 2026-11-23).
- `header={<PageHeader … />}` with `top`: the page's title and description come **first**, then the tabs (Offers & pricing). Each tab then starts with its own head: title, description, its "New" button at the top right.
- `fit`: the page is exactly the screen's height and doesn't scroll; its `Pane`s do, each on its own (Products). Put them in an element with `x-page__fill`. Phones scroll as usual.
- The scrollbar's room is always kept (`scrollbar-gutter: stable`), so a short tab is exactly as wide as a long one.
- `width="form"` for settings and forms (centred at `--x-page-form-max`, 880 px). Lists, tables and dashboards use the default (full).
- Every page is full width, **Settings included** (6F.0, owner 2026-11-23: an 880 px Settings page looked narrower than the rest and cut its tabs). Settings and other pages of cards put them in `<Columns>`: cards flow top to bottom, then into the next column, each column at least 34rem (two on 1080p, three on an ultrawide, one on a laptop or phone); `x-columns__wide` / `<ColumnsWide>` spans all columns (an intro row, a wide editor). `width="form"` (880 px, centred) stays only for a single form that reads better narrow; no page uses it now.
- A settings row (`SettingRow`) keeps its control in a 16rem box on the right: selects and inputs fill it, switches and buttons sit at its right edge.
- **Never** put `p-*`, `max-w-*`, `mx-auto`, `h-full` or `overflow-*` on a page's root, and never nest a second width limit inside it.
- Checked by `tests/e2e/manager_layout.mjs` (1920×1080 and 3440×1440: every page fills / is centred, and scrolls). Add a new page to its `PAGES` list.
@@ -45,9 +46,19 @@ Every page is on `<Page>` except Inventory → Stock (a placeholder). Two-column
| Need | Use | Notes |
|---|---|---|
| A page | `Page`, `PageHeader` | §2 |
| Cards in columns (settings) | `Columns`, `ColumnsWide` | §2; a card never splits across two columns |
| Filters / actions over a list | `Toolbar`, `ToolbarSpacer` | every control in it the same height; the search box grows |
| Search | `SearchInput` | icon, clear button; `onChange(text)` |
| Choose one / several | `Dropdown` (`multiple`) | **never a native `<select>` in a toolbar.** Multi: value is an array, `[]` = all (`allLabel`). Options can carry a `dot` (a zone's colour) and a `hint`. Search box from 9 options. Same heights as `Input`. Native `Select` stays only inside forms where the phone's own picker is better |
| A small panel under a button | `Popover` (`open`, `anchor` = the button's ref, `onClose`) | a colour picker, an "Add…" menu. Drawn over everything (portal), flips above, stays inside the window: **never an `absolute` panel inside a section** (it is clipped and makes the section scroll) |
| A colour (a venue's: data) | `ColourField` (`auto`, `opacity`, `presets`) | a field with its swatch and code; its panel (over the page) has 12 ready colours, the picker, the opacity (`#rrggbbaa`) and the code. `auto` = a first choice that leaves it to something else ("As the slide"). **Never** a bare `<input type="color">` |
| An icon from a set | `IconPicker` (`icons` = { key: component }) | a field showing the icon; a grid of the set over the page, "No icon" first |
| Money, a weight, any number with decimals | `MoneyInput` (€, cents), `DecimalInput` (`decimals`, `allowNegative`, `suffix`) | typed with a comma **or** a dot ("12,50", "1.234,50"); reports a number, `null` when empty, `NaN` when it isn't a number (show the error). **Never** `type="number"` with a decimal step, `parseFloat` or `.replace(',', '.')`: they drop the comma a Greek keypad types (6F.2; guarded by `packages/i18n/tests/typed-numbers.test.mjs`). Fields kept as text read it with `parseNumber` |
| A whole number (seconds, counts) | `NumberInput` (`min`, `max`, `suffix`) | − / + on its sides, as tall as an input; it may be emptied while typing (`onChange(null)`): the form shows the error and blocks saving. **Never** clamp on every key (the user can't clear the field). With a `min` below 0 a minus may be typed in front |
| A note in a box (what works, a caution) | `Notice` (`tone`, `title`, `icon`, `items` = [{ tone, label, text }]) | a tinted box with a bar on its left; `items` are points with a tone dot and a bold label. **Never** a local `bg-info-soft` paragraph rebuilt per page |
| A slider with its value | `Slider` (`suffix`) | framed and as tall as the fields beside it; the value sits as close to it as the frame's padding. **Never** a bare `<input type="range">` |
| Fields that should wrap | `FieldRow` (`min`, `shade` on every other row) | each field keeps its least width; a row that wraps is framed (and tinted with `shade`), a row on one line looks like any row |
| Toggles that go together (bold / italic / underline) | `Segmented multiple` | value is an array |
| A toggle filter (a state) | `FilterChip` (`tone`, `count`) | |
| Two or three views (List / Map / QR) | `Segmented` | the view in the address (`?view=`) |
| Sections of a page or a dialog | `Tabs` (`size="lg"` on pages) | scrolls sideways only, never up/down. `inset`: the strip is a card's header (card padding at the sides, the same room above and below a button in `end`, the labels level with it, no line under it). `fill`: the tabs share the width equally (a narrow column) |
@@ -57,8 +68,8 @@ Every page is on `<Page>` except Inventory → Stock (a placeholder). Two-column
| 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 |
| Ask before doing something (delete, leave unsaved work) | `useConfirm()` → `confirm({ title, body, confirmLabel, tone })` (or `ConfirmDialog`) | **never the browser's `window.confirm`**; render the returned dialog in the component. Leaving unsaved work: add `altLabel` ("Save and leave"): the promise answers `'alt'` |
| A switch in a row of fields | `Switch boxed` | framed and as tall as an input: text left, switch right; a click anywhere in the frame toggles it |
| Two or three choices that fill a form column (alignment…) | `Segmented fill` | options share the width; icon-only options pass `ariaLabel` |
| A side drawer | `Sheet side="right"` (`size="wide"`: 600 px) | the permissions editor is `wide` |
| Something that stays at the top of a dialog or drawer | `toolbar` (Dialog / Sheet) | under the title, doesn't scroll: the permissions' search box |
+3 -2
View File
File diff suppressed because one or more lines are too long
+18
View File
@@ -110,6 +110,7 @@ CODES: dict[str, tuple[int, str]] = {
"signage.not_a_screen": (404, "Device {device_id} isn't a signage screen."),
"signage.schedule_unknown": (404, "Schedule {schedule_id} not found."),
"signage.not_a_video": (422, "Pick a video for this slide."),
"signage.too_many_widgets": (422, "A slide holds at most {max} widgets (Signage → Message & settings → Performance)."),
"signage.content_invalid": (422, "This slide's setting isn't valid ({field}: {reason})."),
"signage.order_mismatch": (409, "The playlist changed in the meantime. Reload it and try again."),
"signage.weather_offline": (503, "The weather service can't be reached: the venue's server needs internet for it."),
@@ -125,6 +126,7 @@ CODES: dict[str, tuple[int, str]] = {
"menu_tablet.order_not_found": (404, "This order was not found."),
"menu_tablet.order_answered": (409, "This order was already answered."),
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."),
"media.folder_unknown": (404, "That folder isn't in the media library any more."),
"reservation.not_found": (404, "Booking {reservation_id} not found."),
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
"reservation.table_unknown": (404, "Table {table_id} not found."),
@@ -219,6 +221,22 @@ CODES: dict[str, tuple[int, str]] = {
"order.item_not_found": (404, "That item isn't on the order any more."),
"order.item_paid": (400, "This item is already paid."),
"order.item_not_active": (400, "Only items still on the order can be changed."),
"order.price_change_off": (403, "Changing prices by hand is turned off for this venue."),
"order.one_more_off": (400, "\"One more\" isn't turned on for this product."),
"order.one_more_line": (400, "This line can't be ordered again with one tap."),
"order.quantity_change_off": (403, "Changing quantities is turned off for this venue."),
"order.quantity_remove_off": (403, "Quantities can only go up at this venue."),
"order.quantity_invalid": (400, "Choose a whole number from 1 to {max}."),
"order.quantity_line": (400, "This line's quantity can't be changed here."),
"order.price_change_sent_off": (403, "Prices can only be changed before the items are sent."),
"order.price_reason_required": (400, "Say why the price changes."),
"split.not_allowed": (403, "Splitting a bill this way isn't turned on for this venue."),
"split.lines_changed": (409, "Some of these items were paid or changed meanwhile. Look again."),
"split.amount_invalid": (400, "Each part must be more than 0 and less than the total ({total})."),
"split.part_locked": (400, "This is part of a split bill: undo the split to change it."),
"split.not_found": (404, "That split bill isn't there any more."),
"split.paid_already": (409, "A part is already paid or on a tab: the split can't be undone."),
"split.parts_unpaid": (400, "Parts of a split bill are still unpaid: take their payment first."),
"order.nothing_paid": (404, "There are no paid items to undo."),
"order.cannot_close": (400, "This order can't be closed now ({status})."),
"order.no_active_items": (400, "None of these items are on the order any more."),
+7 -2
View File
@@ -53,7 +53,8 @@
"paid_total": "Πληρωμενο: {value:.2f}e",
"pending": "ΕΚΚΡΕΜΗ:",
"remaining": "Εκκρεμει: {value:.2f}e",
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ"
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ",
"split": "ΔΙΑΧΩΡΙΣΜΟΣ (ΕΞΟΦΛΕΙΤΑΙ ΑΠΟ ΤΑ ΜΕΡΗ):"
},
"ticket": {
"compact_guests": " | {count}ατ.",
@@ -92,7 +93,8 @@
}
},
"system_product": {
"delivery_fee": "Μεταφορικά"
"delivery_fee": "Μεταφορικά",
"split_part": "Διαχωρισμός λογαριασμού"
},
"qr": {
"order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.",
@@ -104,5 +106,8 @@
"order_sent": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), στάλθηκε στην κουζίνα.",
"order_waiting": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), επιβεβαιώστε τη στο τραπέζι.",
"bill_message": "Τραπέζι {table}: οι πελάτες ζητούν τον λογαριασμό."
},
"split": {
"part_name": "Μέρος λογαριασμού {n}/{of}"
}
}
+7 -2
View File
@@ -53,7 +53,8 @@
"paid_total": "Paid: {value:.2f}e",
"pending": "PENDING:",
"remaining": "Remaining: {value:.2f}e",
"title": "ORDER SUMMARY"
"title": "ORDER SUMMARY",
"split": "SPLIT BILL (SETTLED BY THE PARTS):"
},
"ticket": {
"compact_guests": " | {count}pax",
@@ -92,7 +93,8 @@
}
},
"system_product": {
"delivery_fee": "Delivery fee"
"delivery_fee": "Delivery fee",
"split_part": "Split bill"
},
"qr": {
"order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.",
@@ -104,5 +106,8 @@
"order_sent": "Table {table} ordered from the tablet ({count} items): sent to the kitchen.",
"order_waiting": "Table {table} ordered from the tablet ({count} items): confirm it on the table.",
"bill_message": "Table {table}: the guests ask for the bill."
},
"split": {
"part_name": "Split bill {n}/{of}"
}
}
+17
View File
@@ -38,6 +38,22 @@ router = APIRouter()
_optional_bearer = HTTPBearer(auto_error=False)
def _identity_brief(db) -> dict:
"""What every app needs of the venue's identity (6R.20): its first colour (the accent when
venue.theme is "identity"), the slogan and the logos' addresses. Public, like the venue's name."""
try:
from routers.identity import identity_out
ident = identity_out(db)
except Exception:
return {"colour": None, "slogan": None, "logo": None, "logo_light": None, "logo_dark": None, "icon": None}
logos = ident.get("logos") or {}
def card(k):
return (logos.get(k) or {}).get("card")
return {"colour": (ident.get("colours") or [{}])[0].get("colour"), "slogan": ident.get("slogan"),
"logo": card("main"), "logo_light": card("light"), "logo_dark": card("dark"), "icon": (logos.get("icon") or {}).get("thumb")}
def permission_keys_for(user) -> list[str]:
"""The keys a user holds (user_permissions; superadmin: every key)."""
from core.access.check import user_keys
@@ -113,6 +129,7 @@ def bootstrap(
"language": i18n.venue_language(),
"currency": _setting(db, "venue.currency", "EUR"),
"theme": _setting(db, "venue.theme", "amber") or "amber", # the accent colour (4.6, data-venue-theme)
"identity": _identity_brief(db), # 6R.20: its colour and logos for the apps
"business_day_rollover_hour": timeutil.rollover_hour(),
},
"modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective],
@@ -0,0 +1,28 @@
"""Signage slide shapes (6R.13, owner 2026-11-22): a playlist or a library slide may be built for a
custom shape ("21:9", "16:10", …) besides landscape / portrait. NULL = its orientation's 16:9 / 9:16.
Revision ID: 0045_signage_shapes
Revises: 0044_signage_saved_slides
Create Date: 2026-11-22 10:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0045_signage_shapes'
down_revision = '0044_signage_saved_slides'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('signage_playlists') as b:
b.add_column(sa.Column('aspect', sa.String(), nullable=True))
with op.batch_alter_table('signage_saved_slides') as b:
b.add_column(sa.Column('aspect', sa.String(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('signage_saved_slides') as b:
b.drop_column('aspect')
with op.batch_alter_table('signage_playlists') as b:
b.drop_column('aspect')
@@ -0,0 +1,41 @@
"""Media folders (6R.16, owner 2026-11-22): the Media page groups files in folders. Only a grouping in
the database (media.folder_id); the files stay where they are on disk. A gallery widget can show a folder.
Revision ID: 0046_media_folders
Revises: 0045_signage_shapes
Create Date: 2026-11-22 16:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0046_media_folders'
down_revision = '0045_signage_shapes'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'media_folders',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('position', sa.Integer(), nullable=False, server_default='0'),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_media_folders_id', 'media_folders', ['id'])
with op.batch_alter_table('media') as b:
b.add_column(sa.Column('folder_id', sa.Integer(), nullable=True))
b.create_index('ix_media_folder_id', ['folder_id'])
b.create_foreign_key('fk_media_folder', 'media_folders', ['folder_id'], ['id'], ondelete='SET NULL')
def downgrade() -> None:
with op.batch_alter_table('media') as b:
b.drop_constraint('fk_media_folder', type_='foreignkey')
b.drop_index('ix_media_folder_id')
b.drop_column('folder_id')
op.drop_index('ix_media_folders_id', 'media_folders')
op.drop_table('media_folders')
@@ -0,0 +1,45 @@
"""Prices changed by hand, on the record (owner 2026-11-23, plan 6F.3).
- price_event_log: approved_by_user_id, stage (cart | sent | served), quantity, for the new
event type manual_price (services/price_changes.py).
- The keys ordering.prices.modify_sent (everyone who holds ordering.prices.modify today: nobody
loses what they could do) and ordering.prices.view_changes (owners and store managers).
Revision ID: 0047_price_changes
Revises: 0046_media_folders
Create Date: 2026-11-23 12:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0047_price_changes'
down_revision = '0046_media_folders'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('price_event_log') as b:
b.add_column(sa.Column('approved_by_user_id', sa.Integer(), nullable=True))
b.add_column(sa.Column('stage', sa.String(), nullable=True))
b.add_column(sa.Column('quantity', sa.Float(), nullable=True))
b.create_foreign_key('fk_price_event_approved_by', 'users', ['approved_by_user_id'], ['id'])
bind = op.get_bind()
bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select user_id, 'ordering.prices.modify_sent' from user_permissions where key = 'ordering.prices.modify'"))
# a venue that changed a role's default for modify gets the same for modify_sent
bind.execute(sa.text("insert or ignore into role_permissions (role, key, granted) "
"select role, 'ordering.prices.modify_sent', granted from role_permissions where key = 'ordering.prices.modify'"))
bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, 'ordering.prices.view_changes' from users where role in ('owner', 'store_manager')"))
def downgrade() -> None:
bind = op.get_bind()
bind.execute(sa.text("delete from user_permissions where key in ('ordering.prices.modify_sent', 'ordering.prices.view_changes')"))
bind.execute(sa.text("delete from role_permissions where key = 'ordering.prices.modify_sent'"))
with op.batch_alter_table('price_event_log') as b:
b.drop_constraint('fk_price_event_approved_by', type_='foreignkey')
b.drop_column('quantity')
b.drop_column('stage')
b.drop_column('approved_by_user_id')
@@ -0,0 +1,121 @@
"""Moves on the record (owner 2026-11-23, plan 6F.4, services/moves.py).
- order_moves / order_move_items: every table transfer, lines moved, orders merged, with its lines.
- order_items.split_from_id: the line a line was cut from (a split), so its path follows it.
- Backfill from the audit log written before 6F.4 (notes "Transferred from table A to table B",
"Moved to order #N (table T)", "Items merged from order #N (table T)"): one move each, marked
note='backfill'. A transfer's lines are the order's lines added before it; quantities unknown.
Revision ID: 0048_order_moves
Revises: 0047_price_changes
Create Date: 2026-11-23 15:00:00
"""
import json
import re
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0048_order_moves'
down_revision = '0047_price_changes'
branch_labels = None
depends_on = None
_TABLE = r"(?:table )?(\d+|None)"
def _int(v):
return int(v) if v not in (None, "None", "") else None
def upgrade() -> None:
op.create_table(
'order_moves',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('kind', sa.String(), nullable=False),
sa.Column('from_order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=True),
sa.Column('to_order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=True),
sa.Column('from_table_id', sa.Integer(), sa.ForeignKey('tables.id'), nullable=True),
sa.Column('to_table_id', sa.Integer(), sa.ForeignKey('tables.id'), nullable=True),
sa.Column('by_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('approved_by_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('business_day_id', sa.Integer(), sa.ForeignKey('business_days.id'), nullable=True),
sa.Column('at', UTCDateTime(), nullable=False),
sa.Column('note', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
)
for col in ('id', 'kind', 'from_order_id', 'to_order_id', 'business_day_id', 'at'):
op.create_index(f'ix_order_moves_{col}', 'order_moves', [col])
op.create_table(
'order_move_items',
sa.Column('move_id', sa.Integer(), sa.ForeignKey('order_moves.id', ondelete='CASCADE'), nullable=False),
sa.Column('item_id', sa.Integer(), sa.ForeignKey('order_items.id'), nullable=False),
sa.Column('quantity', sa.Float(), nullable=True),
sa.PrimaryKeyConstraint('move_id', 'item_id'),
)
op.create_index('ix_order_move_items_item_id', 'order_move_items', ['item_id'])
with op.batch_alter_table('order_items') as b:
b.add_column(sa.Column('split_from_id', sa.Integer(), nullable=True))
b.create_index('ix_order_items_split_from_id', ['split_from_id'])
b.create_foreign_key('fk_order_items_split_from', 'order_items', ['split_from_id'], ['id'])
_backfill(op.get_bind())
def _backfill(bind) -> None:
rows = bind.execute(sa.text(
"select a.id, a.order_id, a.event_type, a.waiter_id, a.item_ids, a.note, a.created_at, o.table_id, o.business_day_id "
"from order_audit_log a join orders o on o.id = a.order_id "
"where a.event_type in ('TABLE_TRANSFER', 'ITEMS_MOVED_OUT', 'ITEMS_ADDED') and a.note is not null order by a.id")).fetchall()
existing_items = {r[0] for r in bind.execute(sa.text("select id from order_items")).fetchall()}
existing_orders = {r[0] for r in bind.execute(sa.text("select id from orders")).fetchall()}
def add(kind, frm, to, ft, tt, by, at, day, items):
res = bind.execute(sa.text(
"insert into order_moves (kind, from_order_id, to_order_id, from_table_id, to_table_id, by_user_id, business_day_id, at, note) "
"values (:k, :fo, :to, :ft, :tt, :by, :day, :at, 'backfill')"),
{'k': kind, 'fo': frm if frm in existing_orders else None, 'to': to if to in existing_orders else None,
'ft': ft, 'tt': tt, 'by': by, 'day': day, 'at': at})
mid = res.lastrowid
for iid in sorted({i for i in items if i in existing_items}):
bind.execute(sa.text("insert or ignore into order_move_items (move_id, item_id, quantity) values (:m, :i, null)"),
{'m': mid, 'i': iid})
def ids(raw):
try:
v = json.loads(raw or '[]')
return [int(x) for x in v if isinstance(x, int)]
except (ValueError, TypeError):
return []
for (_id, order_id, kind, by, item_ids, note, at, table_id, day) in rows:
if kind == 'TABLE_TRANSFER':
m = re.match(rf"Transferred from table (\d+|None) to table (\d+|None)", note)
if not m:
continue
items = [r[0] for r in bind.execute(sa.text(
"select id from order_items where order_id = :o and added_at <= :at"), {'o': order_id, 'at': at}).fetchall()]
add('table_transfer', order_id, order_id, _int(m.group(1)), _int(m.group(2)), by, at, day, items)
elif kind == 'ITEMS_MOVED_OUT':
m = re.match(rf"Moved to order #(\d+) \({_TABLE}\)", note)
if not m:
continue
add('items_moved', order_id, int(m.group(1)), table_id, _int(m.group(2)), by, at, day, ids(item_ids))
elif kind == 'ITEMS_ADDED':
m = re.match(rf"Items merged from order #(\d+) \({_TABLE}\)", note)
if not m:
continue
add('orders_merged', int(m.group(1)), order_id, _int(m.group(2)), table_id, by, at, day, ids(item_ids))
def downgrade() -> None:
with op.batch_alter_table('order_items') as b:
b.drop_constraint('fk_order_items_split_from', type_='foreignkey')
b.drop_index('ix_order_items_split_from_id')
b.drop_column('split_from_id')
op.drop_index('ix_order_move_items_item_id', 'order_move_items')
op.drop_table('order_move_items')
for col in ('id', 'kind', 'from_order_id', 'to_order_id', 'business_day_id', 'at'):
op.drop_index(f'ix_order_moves_{col}', 'order_moves')
op.drop_table('order_moves')
@@ -0,0 +1,30 @@
"""One more and quantity changes (owner 2026-11-23, plan 6F.5).
- products.one_more_enabled (off: the owner turns it on per product).
- The key ordering.items.change_quantity for owners and store managers (the venue's setting
orders.quantity_change starts 'off').
Revision ID: 0049_one_more
Revises: 0048_order_moves
Create Date: 2026-11-23 18:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0049_one_more'
down_revision = '0048_order_moves'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('products') as b:
b.add_column(sa.Column('one_more_enabled', sa.Boolean(), nullable=False, server_default='0'))
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, 'ordering.items.change_quantity' from users where role in ('owner', 'store_manager')"))
def downgrade() -> None:
op.get_bind().execute(sa.text("delete from user_permissions where key = 'ordering.items.change_quantity'"))
with op.batch_alter_table('products') as b:
b.drop_column('one_more_enabled')
@@ -0,0 +1,59 @@
"""Split the bill by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py).
- split_bills: chosen lines settled together and cut into parts paid on their own.
- order_items.split_bill_id: on the settled lines (status 'split') and on the part lines.
- The key ordering.payments.split_amount for everyone who takes payments (holds
ordering.orders.close); the venue's setting payments.split_amount starts 'off'.
Revision ID: 0050_split_bills
Revises: 0049_one_more
Create Date: 2026-11-23 21:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0050_split_bills'
down_revision = '0049_one_more'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'split_bills',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=False),
sa.Column('total', sa.Float(), nullable=False),
sa.Column('mode', sa.String(), nullable=False),
sa.Column('parts', sa.Integer(), nullable=False),
sa.Column('amounts', sa.Text(), nullable=False),
sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('business_day_id', sa.Integer(), sa.ForeignKey('business_days.id'), nullable=True),
sa.Column('undone_at', UTCDateTime(), nullable=True),
sa.Column('undone_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('receipt_issued_at', UTCDateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
)
for col in ('id', 'order_id', 'business_day_id'):
op.create_index(f'ix_split_bills_{col}', 'split_bills', [col])
with op.batch_alter_table('order_items') as b:
b.add_column(sa.Column('split_bill_id', sa.Integer(), nullable=True))
b.create_index('ix_order_items_split_bill_id', ['split_bill_id'])
b.create_foreign_key('fk_order_items_split_bill', 'split_bills', ['split_bill_id'], ['id'])
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select user_id, 'ordering.payments.split_amount' from user_permissions "
"where key = 'ordering.orders.close'"))
def downgrade() -> None:
op.get_bind().execute(sa.text("delete from user_permissions where key = 'ordering.payments.split_amount'"))
with op.batch_alter_table('order_items') as b:
b.drop_constraint('fk_order_items_split_bill', type_='foreignkey')
b.drop_index('ix_order_items_split_bill_id')
b.drop_column('split_bill_id')
for col in ('id', 'order_id', 'business_day_id'):
op.drop_index(f'ix_split_bills_{col}', 'split_bills')
op.drop_table('split_bills')
+12
View File
@@ -39,9 +39,21 @@ class Media(Base):
# or no video tool on this server). `progress` 0-100 while working.
processing = Column(String, nullable=True)
progress = Column(Integer, nullable=True)
# its folder on the Media page (6R.16): only a grouping, the file stays where it is
folder_id = Column(Integer, ForeignKey("media_folders.id", ondelete="SET NULL"), nullable=True, index=True)
uploader = relationship("User", lazy="joined")
@property
def uploaded_by_name(self):
return self.uploader.full_name or self.uploader.username if self.uploader is not None else None
class MediaFolder(Base):
"""A folder of the media library (6R.16): a name and a place in the list; its files point at it."""
__tablename__ = "media_folders"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
position = Column(Integer, nullable=False, default=0, server_default='0')
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
+57
View File
@@ -133,6 +133,12 @@ class OrderItem(Base):
# Deal binding — which deal created this item, and which original item it's linked to
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
linked_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True)
# the line this one was cut from (6F.4): a split, a lowered quantity, a split payment; its moves
# before the cut are this line's too (services/moves.py)
split_from_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True)
# a split bill (6F.6): on the lines it settled (status "split") and on its part lines (the
# system product split_part, paid like any line); services/split_bills.py
split_bill_id = Column(Integer, ForeignKey("split_bills.id"), nullable=True, index=True)
order = relationship("Order", back_populates="items")
product = relationship("Product", back_populates="order_items")
@@ -261,3 +267,54 @@ def _snapshot_item_names(session, flush_context, instances):
cat = session.get(Category, obj.category_id)
obj.category_name = cat.name if cat else None
class OrderMove(Base):
"""Something moved between tables or orders (owner 2026-11-23, plan 6F.4, services/moves.py):
a whole order to another table (`table_transfer`), chosen lines to another order
(`items_moved`), or one order joined into another (`orders_merged`). Never deleted."""
__tablename__ = "order_moves"
id = Column(Integer, primary_key=True, index=True)
kind = Column(String, nullable=False, index=True) # table_transfer | items_moved | orders_merged
from_order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
to_order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
from_table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
to_table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
approved_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
note = Column(Text, nullable=True) # the importer / backfill: where it came from
items = relationship("OrderMoveItem", back_populates="move", cascade="all, delete-orphan")
class OrderMoveItem(Base):
"""A line that went with a move, and how much of it (its quantity at the time)."""
__tablename__ = "order_move_items"
move_id = Column(Integer, ForeignKey("order_moves.id", ondelete="CASCADE"), primary_key=True)
item_id = Column(Integer, ForeignKey("order_items.id"), primary_key=True, index=True)
quantity = Column(Float, nullable=True)
move = relationship("OrderMove", back_populates="items")
class SplitBill(Base):
"""A bill split by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py): chosen lines
settled together (status "split") and cut into `parts` part lines that are paid on their own.
Undone (undone_at) only while no part was paid or put on a tab."""
__tablename__ = "split_bills"
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
total = Column(Float, nullable=False)
mode = Column(String, nullable=False) # equal | custom
parts = Column(Integer, nullable=False)
amounts = Column(Text, nullable=False) # JSON [4.5, 10.5]: each part, in order
created_by = Column(Integer, ForeignKey("users.id"), nullable=True)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
undone_at = Column(UTCDateTime, nullable=True)
undone_by = Column(Integer, ForeignKey("users.id"), nullable=True)
receipt_issued_at = Column(UTCDateTime, nullable=True) # the fiscal receipt of the settled lines (last part paid)
+8 -1
View File
@@ -227,6 +227,7 @@ class PriceEventLog(Base):
# deal_offer_dismissed — waiter dismissed the deal offer
# waiter_discount — manual waiter discount applied
# free_item_added — free item added to order as result of a deal
# manual_price — a price changed by hand (6F.3, services/price_changes.py)
modifier_id = Column(Integer, ForeignKey("price_modifiers.id"), nullable=True)
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
@@ -236,10 +237,15 @@ class PriceEventLog(Base):
price_after = Column(Float, nullable=True)
delta_amount = Column(Float, nullable=True) # price_after - price_before; negative = discount
# Waiter discount fields
# Waiter discount fields (also manual_price: who changed it, and the reason)
applied_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
waiter_note = Column(Text, nullable=True)
# manual_price (6F.3, services/price_changes.py): a price changed by hand
approved_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True) # a manager's PIN (D-10)
stage = Column(String, nullable=True) # cart | sent | served
quantity = Column(Float, nullable=True) # the line's quantity at the time
# Snapshot of the conditions that evaluated to True when the event fired.
# JSON object: {"condition_type": evaluated_value, ...}
# e.g. {"day_of_week": 5, "time_range": "21:45", "price_group_active": true}
@@ -255,6 +261,7 @@ class PriceEventLog(Base):
modifier = relationship("PriceModifier", foreign_keys=[modifier_id])
deal = relationship("Deal", foreign_keys=[deal_id])
applied_by = relationship("User", foreign_keys=[applied_by_user_id])
approved_by = relationship("User", foreign_keys=[approved_by_user_id])
class WaiterDiscountSettings(Base):
+2
View File
@@ -82,6 +82,8 @@ class Product(Base):
# Quick Add: allow adding 1 unit directly from product list without opening config modal
quick_add_enabled = Column(Boolean, default=True, nullable=False)
# "One more" (6F.5): a sent line of this product shows +1 (re-order the same, printed as new)
one_more_enabled = Column(Boolean, default=False, nullable=False, server_default="0")
# Service item: non-inventoried table-service items (cutlery, glasses, etc.)
is_service_item = Column(Boolean, default=False, nullable=False)
+2
View File
@@ -23,6 +23,7 @@ class SignagePlaylist(Base):
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
orientation = Column(String, nullable=False, default="landscape") # landscape | portrait
aspect = Column(String, nullable=True) # a custom shape "21:9" (6R.13); None: 16:9 / 9:16
transition = Column(String, nullable=False, default="fade") # the slides' default
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
@@ -91,6 +92,7 @@ class SignageSavedSlide(Base):
name = Column(String, nullable=False)
description = Column(String, nullable=True)
orientation = Column(String, nullable=False, default="landscape") # landscape | portrait
aspect = Column(String, nullable=True) # a custom shape "21:9" (6R.13); None: 16:9 / 9:16
kind = Column(String, nullable=False) # menu | image | video | text | blank
duration_s = Column(Integer, nullable=False, default=10)
transition = Column(String, nullable=True)
+4 -1
View File
@@ -33,7 +33,9 @@ MODULE = Module(
SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'),
SettingDef('venue.timezone', 'Europe/Athens', 'IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.', type='str'),
SettingDef('venue.name', '', 'Venue name shown on screens and tickets.', type='str'),
SettingDef('venue.theme', 'amber', "Accent colour of the staff apps (the waiter's phones first, plan step 4.6): 'teal' | 'amber' | 'blue' | 'violet' | 'rose'", type='enum', choices=('teal', 'amber', 'blue', 'violet', 'rose')),
SettingDef('venue.opening_hours', '{}', 'Opening hours, Monday first (6R.15; JSON {days, note}; edited on the Schedule page, shown by signage).', type='json'),
SettingDef('venue.identity', '{}', "The venue's identity (6R.14): slogan, colours, logos, Wi-Fi, contact details (JSON; Settings > Identity, routers/identity.py).", type='json'),
SettingDef('venue.theme', 'amber', "Accent colour of the staff apps (the waiter's phones first, plan step 4.6): 'teal' | 'amber' | 'blue' | 'violet' | 'rose', or 'identity' = the first colour of the venue's identity (6R.20: also the counter, KDS and tablets)", type='enum', choices=('teal', 'amber', 'blue', 'violet', 'rose', 'identity')),
SettingDef('venue.type', '', 'Kind of venue (restaurant, cafe, bar...), chosen in the setup wizard.', type='str'),
SettingDef('venue.currency', 'EUR', 'ISO 4217 currency of all prices.', type='str'),
),
@@ -50,6 +52,7 @@ MODULE = Module(
Mount('routers.access', '/api/access'),
Mount('routers.notifications', '/api/platform/notifications'),
Mount('routers.scenes', '/api/scenes'),
Mount('routers.identity', '/api/identity'),
Mount('core.modules.api', '/api/platform'),
),
)
+11 -1
View File
@@ -11,9 +11,13 @@ MODULE = Module(
Perm('ordering.orders.open', 'Open orders and add items', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
Perm('ordering.orders.close', 'Take payments and close orders', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
Perm('ordering.orders.cancel', 'Cancel items already sent', roles=('owner', 'store_manager'), overridable=True),
Perm('ordering.prices.modify', "Change an item's price", roles=('owner',), overridable=True),
Perm('ordering.prices.modify', "Change an item's price before it is sent", roles=('owner',), overridable=True),
Perm('ordering.prices.modify_sent', "Change the price of an item already sent or served", roles=('owner',), overridable=True),
Perm('ordering.items.change_quantity', "Change a sent line's quantity (no new ticket)", roles=('owner', 'store_manager'), overridable=True),
Perm('ordering.prices.view_changes', 'See the prices changed by hand (who, when, why)', roles=('owner', 'store_manager')),
Perm('ordering.refunds', 'Refund payments from other shifts', roles=('owner', 'store_manager'), overridable=True),
Perm('ordering.payments.revert', 'Turn paid items back to unpaid', roles=('owner', 'store_manager'), overridable=True),
Perm('ordering.payments.split_amount', 'Split a bill by amount (equal parts or a ratio)', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter'), overridable=True),
Perm('ordering.business_day.manage', 'Open and close the business day', roles=('owner', 'store_manager', 'staff_manager')),
),
settings=(
@@ -22,9 +26,15 @@ MODULE = Module(
SettingDef('orders.auto_close_on_full_payment', 'false', "Automatically close the table order when all items have been paid: 'true' | 'false'", type='bool'),
SettingDef('orders.close_with_unpaid', 'false', "Allow closing an order that still has unpaid items (they are written off as unpaid): 'true' | 'false'. When 'false', closing asks for the payment first (plan step 4.8).", type='bool'),
SettingDef('orders.bypass_kds_serve', 'false', "Skip KDS pending/serve flow — new orders and items are immediately marked as served: 'true' | 'false'", type='bool'),
SettingDef('orders.quantity_change', 'off', "Changing a sent line's quantity without sending it again (6F.5): 'off' | 'add_only' | 'add_and_remove' (lowering cancels the difference; also needs ordering.orders.cancel). Who may: ordering.items.change_quantity.", type='enum', choices=('off', 'add_only', 'add_and_remove')),
SettingDef('orders.price_change', 'anytime', "Changing a line's price by hand (6F.3): 'off' | 'before_sending' (only in the cart) | 'anytime' (also a sent or served line). Who may: the keys ordering.prices.modify / modify_sent.", type='enum', choices=('off', 'before_sending', 'anytime')),
SettingDef('orders.price_change_reason', 'false', "A price changed by hand needs a reason: 'true' | 'false' (6F.3).", type='bool'),
SettingDef('orders.price_change_reasons', '[]', 'JSON array of quick reasons offered when a price is changed by hand (6F.3); [] = the built-in ones.', type='json'),
SettingDef('orders.courses', '[]', 'JSON array of course objects [{id, name, color}] defining available courses', type='json'),
SettingDef('orders.courses_enabled', 'false', "Enable per-item course assignment when ordering: 'true' | 'false'", type='bool'),
SettingDef('orders.quick_notes', '["Χωρίς αλάτι","Βγάλτε γρήγορα","Αλλεργία!","Κόψτε σε μικρά κομμάτια","Έξτρα χαρτοπετσέτες"]', 'JSON array of quick-note strings shown in the waiter note tab', type='json'),
SettingDef('payments.split_amount', 'off', "Splitting a bill by amount (6F.6), each level with the ones before: 'off' | 'two_equal' (half and half) | 'two_custom' (two parts in any ratio) | 'multiple_equal' (2 to payments.split_max_parts equal parts). Who may: ordering.payments.split_amount.", type='enum', choices=('off', 'two_equal', 'two_custom', 'multiple_equal')),
SettingDef('payments.split_max_parts', '10', 'The most equal parts a bill can be split into (6F.6, 2-50).', type='int'),
SettingDef('payments.card_enabled', 'false', "Allow waiters to record card payments (in addition to cash): 'true' | 'false'", type='bool'),
SettingDef('print.alert_after_failures', '2', 'Tell managers when a kitchen/bar ticket has failed to print this many times and is still retrying (0 = never; they are always told when a ticket is finally given up).', type='int'),
SettingDef('print.beep_on_ticket', 'true', "Play beep when a kitchen ticket prints: 'true' | 'false'", type='bool'),
@@ -17,6 +17,7 @@ MODULE = Module(
),
settings=(
SettingDef('signage.message', '', 'The message of the day on every signage screen with a message widget (Signage > Message of the day).'),
SettingDef('signage.reviews', '[]', 'The reviews the venue typed in for the reviews widget (6R.19; JSON list; Signage > Message & settings).', type='json'),
SettingDef('signage.weather.place', '', 'The place whose weather the screens show (picked from a town search in Signage).'),
SettingDef('signage.weather.latitude', '', 'Latitude of the weather place.'),
SettingDef('signage.weather.longitude', '', 'Longitude of the weather place.'),
@@ -31,5 +32,13 @@ MODULE = Module(
ConfigField('slide', 'ref', default=None, choices_from='signage_slides'),
ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')),
ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)),
# its picture (6R.13): a slide of another shape keeps its shape (bands) or fills the picture;
# px cut off each edge of the TV's window (set by Signage > Screens > Calibrate); below 0 the
# picture reaches past that edge of the window the TV reported (owner 2026-11-23)
ConfigField('fit', 'enum', default='keep', choices=('keep', 'stretch'), group='picture'),
ConfigField('area_left', 'int', default=0, min=-2000, max=4000, group='picture'),
ConfigField('area_top', 'int', default=0, min=-2000, max=4000, group='picture'),
ConfigField('area_right', 'int', default=0, min=-2000, max=4000, group='picture'),
ConfigField('area_bottom', 'int', default=0, min=-2000, max=4000, group='picture'),
)),
)
+4 -2
View File
@@ -312,8 +312,9 @@ def business_day_summary(
if o.table_id:
waiter_tables.setdefault(o.opened_by, set()).add(o.table_id)
from services.split_bills import is_part
for item in all_items:
if item.status == "cancelled":
if item.status == "cancelled" or is_part(item): # 6F.6: a split bill's parts are money, not items ordered
continue
e = _waiter_entry(item.added_by)
e["items_ordered"] += item.quantity
@@ -407,7 +408,8 @@ def business_day_summary(
for item in o.items:
if item.status == "cancelled":
continue
entry["items"] += item.quantity
if not is_part(item):
entry["items"] += item.quantity
if item.status == "paid":
entry["revenue"] += gross(item)
+10 -1
View File
@@ -64,6 +64,7 @@ class IdleBody(BaseModel):
qr_url: Optional[str] = Field(default=None, max_length=300)
qr_caption: Optional[str] = Field(default=None, max_length=80)
theme: Literal["dark", "light"] = "dark"
brand: Literal["own", "identity"] = "own" # 6R.20: the venue's identity: its colour as the accent, its logo when the look has none
@field_validator("qr_url")
@classmethod
@@ -157,7 +158,15 @@ def idle_out(db, look: DisplayLook | None) -> dict:
cfg = config_of(look)
pics = _pictures(db, [cfg["logo"], cfg["image"], *cfg["slides"]])
url = lambda i, size: (media_store.image_of(pics[i]) or {}).get(size) if i in pics else None # noqa: E731
return {**cfg, "logo_url": url(cfg["logo"], "card"), "image_url": url(cfg["image"], "full"),
logo = url(cfg["logo"], "card")
accent = None
if cfg.get("brand") == "identity":
from core.modules.api import _identity_brief
ib = _identity_brief(db)
accent = ib["colour"]
# its own logo first; else the identity's (the one made for this background, else the main one)
logo = logo or (ib["logo_light"] if cfg.get("theme", "dark") == "dark" else ib["logo_dark"]) or ib["logo"]
return {**cfg, "logo_url": logo, "accent": accent, "image_url": url(cfg["image"], "full"),
"slide_urls": [u for u in (url(i, "full") for i in cfg["slides"]) if u],
"qr_link": _qr_link(cfg) if cfg["style"] == "qr" else None}
+251
View File
@@ -0,0 +1,251 @@
"""The venue's identity (6R.14, owner 2026-11-22): set once, used by every app that shows the venue.
GET /api/identity its name, slogan, colours, logos, Wi-Fi and contact details (anyone who opens the manager)
PUT /api/identity all of it at once (core.settings.manage)
GET /api/identity/hours the opening hours, Monday first (6R.15)
PUT /api/identity/hours {days: [[{from, to}], … 7], note} (core.settings.manage or core.staff.manage: the Schedule page)
Stored as the settings `venue.name` (the name everything already shows) and `venue.identity` (JSON,
the rest). Logos are media library pictures, protected while used. Signage screens get it with
their venue (routers/signage._venue) and are told when it changes; the colours are offered first in
every colour field of signage. Other apps follow it in 6R.20.
"""
from __future__ import annotations
import json
from typing import List, Literal, Optional
from fastapi import APIRouter, Depends
from pydantic import BaseModel, ConfigDict, Field, field_validator
from sqlalchemy.orm import Session
from core.access.deps import require, require_any
from core.errors import XeniaError
from database import get_db
router = APIRouter()
KEY = "venue.identity"
HOURS = "venue.opening_hours"
TIME = r"^([01]\d|2[0-3]):[0-5]\d$"
HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$"
LOGOS = ("main", "light", "dark", "icon")
class _Strict(BaseModel):
model_config = ConfigDict(extra="forbid")
def _text(v, n):
v = " ".join(str(v or "").split())[:n]
return v or None
class Colour(_Strict):
"""One of the venue's colours: a name people see ("Main", "Olive") and its colour."""
name: str = Field(min_length=1, max_length=40)
colour: str = Field(pattern=HEX)
@field_validator("name")
@classmethod
def _name(cls, v):
v = _text(v, 40)
if not v:
raise ValueError("a colour has a name")
return v
@field_validator("colour")
@classmethod
def _lower(cls, v):
return v.lower()
class Logos(_Strict):
"""Pictures of the media library: the main logo, one for dark backgrounds (light), one for light
backgrounds (dark), a small square icon."""
main: Optional[int] = None
light: Optional[int] = None
dark: Optional[int] = None
icon: Optional[int] = None
class Wifi(_Strict):
ssid: Optional[str] = Field(default=None, max_length=32)
password: Optional[str] = Field(default=None, max_length=63)
security: Literal["WPA", "WEP", "nopass"] = "WPA"
hidden: bool = False
note: Optional[str] = Field(default=None, max_length=120) # "Ask us for the guest network"
@field_validator("ssid", "note")
@classmethod
def _trim(cls, v):
return (v or "").strip() or None
@field_validator("password")
@classmethod
def _pw(cls, v):
return v or None # spaces count in a password
class Contact(_Strict):
phone: Optional[str] = Field(default=None, max_length=40)
phone2: Optional[str] = Field(default=None, max_length=40)
email: Optional[str] = Field(default=None, max_length=120)
address: Optional[str] = Field(default=None, max_length=200)
website: Optional[str] = Field(default=None, max_length=200)
facebook: Optional[str] = Field(default=None, max_length=200)
instagram: Optional[str] = Field(default=None, max_length=200)
tiktok: Optional[str] = Field(default=None, max_length=200)
tripadvisor: Optional[str] = Field(default=None, max_length=200)
google: Optional[str] = Field(default=None, max_length=300) # its Google Maps / reviews link
whatsapp: Optional[str] = Field(default=None, max_length=40)
viber: Optional[str] = Field(default=None, max_length=40)
@field_validator("*")
@classmethod
def _trim(cls, v):
return (v or "").strip() or None if isinstance(v, str) or v is None else v
class Identity(_Strict):
slogan: Optional[str] = Field(default=None, max_length=120)
colours: List[Colour] = Field(default_factory=list, max_length=12)
logos: Logos = Field(default_factory=Logos)
wifi: Wifi = Field(default_factory=Wifi)
contact: Contact = Field(default_factory=Contact)
@field_validator("slogan")
@classmethod
def _slogan(cls, v):
return _text(v, 120)
class IdentityBody(Identity):
name: Optional[str] = Field(default=None, max_length=80)
def _setting(db, key: str) -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row and row.value is not None else ""
def _save(db, key: str, value: str) -> None:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
if row is None:
db.add(PosSettings(key=key, value=value))
else:
row.value = value
def stored(db) -> Identity:
"""The identity as stored (an old or broken value reads as empty, never an error)."""
try:
return Identity(**json.loads(_setting(db, KEY) or "{}"))
except Exception:
return Identity()
def identity_out(db) -> dict:
"""The identity for an app: the logos as pictures ({id, name, thumb, card, full} or None)."""
from models.media import Media
from services.media import image_of
ident = stored(db).model_dump()
ident["logos"] = {k: image_of(db.get(Media, v)) if v else None for k, v in ident["logos"].items()}
return {"name": _setting(db, "venue.name") or None, **ident}
def _uses(db, media_id: int) -> list:
logos = stored(db).logos
return [{"id": 0, "name": k} for k in LOGOS if getattr(logos, k) == media_id]
def _register():
from services import media as media_store
media_store.register_usage("identity", _uses)
_register()
@router.get("")
def get_identity(db: Session = Depends(get_db), user=Depends(require("core.dashboard.access"))):
return identity_out(db)
@router.put("")
def put_identity(body: IdentityBody, db: Session = Depends(get_db), user=Depends(require("core.settings.manage"))):
from models.media import Media
for k in LOGOS:
mid = getattr(body.logos, k)
if mid is None:
continue
m = db.get(Media, mid)
if m is None:
raise XeniaError("media.not_found", media_id=mid)
if m.kind != "image":
raise XeniaError("media.not_a_picture")
if "name" in body.model_fields_set:
_save(db, "venue.name", (body.name or "").strip())
_save(db, KEY, json.dumps(Identity(**body.model_dump(exclude={"name"})).model_dump(), ensure_ascii=False))
db.commit()
try:
from routers.signage import tell_all_screens
tell_all_screens(db) # the screens show the venue's name, logo, Wi-Fi…
except Exception:
pass # signage not installed / off: nothing to tell
return identity_out(db)
# ── opening hours (6R.15): edited on the Schedule page, shown by signage's opening hours widget ──
class Span(_Strict):
"""Open from … to … (venue time; `to` before `from` passes midnight)."""
from_: str = Field(alias="from", pattern=TIME)
to: str = Field(pattern=TIME)
model_config = ConfigDict(extra="forbid", populate_by_name=True)
class Hours(_Strict):
days: List[List[Span]] = Field(default_factory=lambda: [[] for _ in range(7)]) # Monday first; [] = closed
note: Optional[str] = Field(default=None, max_length=120) # "Closed on holidays"
@field_validator("days")
@classmethod
def _seven(cls, v):
if len(v) != 7 or any(len(d) > 3 for d in v):
raise ValueError("seven days, up to three spans a day")
return v
@field_validator("note")
@classmethod
def _note(cls, v):
return _text(v, 120)
def hours_out(db) -> dict:
"""{days: [[{from, to}]…7], note, set}: `set` false while no day has hours."""
try:
h = Hours(**json.loads(_setting(db, HOURS) or "{}"))
except Exception:
h = Hours()
days = [[{"from": x.from_, "to": x.to} for x in d] for d in h.days]
return {"days": days, "note": h.note, "set": any(days)}
@router.get("/hours")
def get_hours(db: Session = Depends(get_db), user=Depends(require("core.dashboard.access"))):
return hours_out(db)
@router.put("/hours")
def put_hours(body: Hours, db: Session = Depends(get_db), user=Depends(require_any("core.settings.manage", "core.staff.manage"))):
days = [[{"from": x.from_, "to": x.to} for x in sorted(d, key=lambda x: x.from_)] for d in body.days]
_save(db, HOURS, json.dumps({"days": days, "note": body.note}, ensure_ascii=False))
db.commit()
try:
from routers.signage import tell_all_screens
tell_all_screens(db)
except Exception:
pass
return hours_out(db)
+99 -7
View File
@@ -29,7 +29,7 @@ from core.access.deps import public, require_any
from core.errors import XeniaError
from database import get_db
from datetime import datetime
from models.media import Media
from models.media import Media, MediaFolder
from services import media as store
from services import video
@@ -57,6 +57,7 @@ class MediaOut(BaseModel):
builtin: bool = False
processing: Optional[str] = None # videos: waiting | working | done | failed (5.4e)
progress: Optional[int] = None
folder_id: Optional[int] = None # 6R.16
urls: dict = Field(default_factory=dict)
@@ -75,17 +76,53 @@ class MediaPage(BaseModel):
class RenameBody(BaseModel):
name: str = Field(min_length=1, max_length=120)
name: Optional[str] = Field(default=None, min_length=1, max_length=120)
folder_id: Optional[int] = None # 6R.16: its folder (None: none)
@field_validator("name")
@classmethod
def _strip(cls, v):
if v is None:
return v
v = v.strip()
if not v:
raise ValueError("empty")
return v
class FolderBody(BaseModel):
name: str = Field(min_length=1, max_length=60)
@field_validator("name")
@classmethod
def _strip(cls, v):
v = " ".join(v.split())
if not v:
raise ValueError("empty")
return v
class MoveBody(BaseModel):
ids: List[int] = Field(min_length=1, max_length=500)
folder_id: Optional[int] = None
def _folder(db: Session, folder_id: Optional[int]) -> Optional[MediaFolder]:
if folder_id is None:
return None
f = db.get(MediaFolder, folder_id)
if f is None:
raise XeniaError("media.folder_unknown", folder_id=folder_id)
return f
def _folders_out(db: Session) -> list:
from sqlalchemy import func
counts = dict(db.query(Media.folder_id, func.count(Media.id)).group_by(Media.folder_id).all())
rows = db.query(MediaFolder).order_by(MediaFolder.position, MediaFolder.name).all()
return [{"id": f.id, "name": f.name, "count": counts.get(f.id, 0)} for f in rows]
def _out(item: Media, cls=MediaOut, **extra):
return cls.model_validate(item).model_copy(update={"urls": store.urls(item), **extra})
@@ -105,9 +142,14 @@ def _name_from(filename: str | None) -> str:
@router.get("", response_model=MediaPage)
def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str] = None,
collection: Optional[Literal["builtin", "own"]] = None, limit: int = 100, offset: int = 0,
collection: Optional[Literal["builtin", "own"]] = None, folder: Optional[str] = None, limit: int = 100, offset: int = 0,
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
"""`folder`: a folder's id, or "none" for the files in no folder (6R.16)."""
query = db.query(Media)
if folder == "none":
query = query.filter(Media.folder_id.is_(None))
elif folder and folder.isdigit():
query = query.filter(Media.folder_id == int(folder))
if kind:
query = query.filter(Media.kind == kind)
if q and q.strip():
@@ -122,11 +164,13 @@ def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str
@router.post("", response_model=UploadOut, status_code=201)
def upload_media(response: Response, file: UploadFile = File(...), name: Optional[str] = Form(None),
folder_id: Optional[int] = Form(None),
db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
# The type comes from the bytes; the browser's content type only picks the size limit.
declared = (file.content_type or "").lower()
limit = store.VIDEO_MAX_BYTES if declared.startswith("video/") else store.IMAGE_MAX_BYTES
tmp, sha, size = store.receive(file.file, limit)
folder = _folder(db, folder_id)
existing = db.query(Media).filter(Media.sha256 == sha).first()
if existing is not None:
store._remove(tmp)
@@ -134,7 +178,8 @@ def upload_media(response: Response, file: UploadFile = File(...), name: Optiona
return _out(existing, UploadOut, existing=True)
info = store.ingest(tmp, sha, size)
item = Media(name=(name or "").strip()[:120] or _name_from(file.filename),
original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id, **info)
original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id,
folder_id=folder.id if folder else None, **info)
if item.kind == "video":
video.queued(item) # its still frame and playable version, in the background
try:
@@ -195,6 +240,50 @@ def _ranged(path: str, ctype: str, rng: str, headers: dict):
**headers, "Content-Range": f"bytes {start}-{end}/{size}", "Content-Length": str(end - start + 1)})
# ── folders (6R.16): only a grouping; files keep their place on disk ─────────────
@router.get("/folders")
def list_folders(db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
return {"folders": _folders_out(db), "none": db.query(Media).filter(Media.folder_id.is_(None)).count()}
@router.post("/folders", status_code=201)
def create_folder(body: FolderBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
last = db.query(MediaFolder).count()
f = MediaFolder(name=body.name, position=last)
db.add(f)
db.commit()
db.refresh(f)
return {"id": f.id, "name": f.name, "count": 0}
@router.patch("/folders/{folder_id}")
def rename_folder(folder_id: int, body: FolderBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
f = _folder(db, folder_id)
f.name = body.name
db.commit()
return next(x for x in _folders_out(db) if x["id"] == f.id)
@router.delete("/folders/{folder_id}", status_code=204)
def delete_folder(folder_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
"""The folder goes; its files stay in the library, in no folder."""
f = _folder(db, folder_id)
db.query(Media).filter(Media.folder_id == f.id).update({Media.folder_id: None})
db.delete(f)
db.commit()
return Response(status_code=204)
@router.post("/move")
def move_media(body: MoveBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
"""Several files into a folder (or out of any: folder_id null)."""
folder = _folder(db, body.folder_id)
n = db.query(Media).filter(Media.id.in_(body.ids)).update({Media.folder_id: folder.id if folder else None}, synchronize_session=False)
db.commit()
return {"moved": n}
@router.get("/{media_id}", response_model=MediaDetail)
def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
item = _get(db, media_id)
@@ -204,9 +293,12 @@ def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require
@router.patch("/{media_id}", response_model=MediaOut)
def rename_media(media_id: int, body: RenameBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
item = _get(db, media_id)
if item.builtin:
raise XeniaError("media.builtin")
item.name = body.name
if "name" in body.model_fields_set and body.name is not None:
if item.builtin:
raise XeniaError("media.builtin")
item.name = body.name
if "folder_id" in body.model_fields_set:
item.folder_id = _folder(db, body.folder_id).id if body.folder_id is not None else None # built-in pictures may be filed too
db.commit()
db.refresh(item)
return _out(item)
+1 -1
View File
@@ -299,7 +299,7 @@ def bill(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"
return {"lines": [], "total": 0, "paid": 0, "due": 0}
lines = []
for i in order.items:
if i.status == "cancelled":
if i.status in ("cancelled", "split"): # 6F.6: a split bill's parts stand for the lines it settled
continue
unit = (i.unit_price or 0) + (i.price_adjustment or 0)
texts = menu_languages.product_texts(i.product, customer=False) if i.product else {}
+310 -32
View File
@@ -61,6 +61,7 @@ from core.access.deps import require
from services.printer_service import route_and_print, route_and_print_sync, print_order_receipt, print_order_synopsis, print_cancellation_ticket
from models.settings import PosSettings
from services.ws_bus import broadcast_sync
from services import split_bills
router = APIRouter()
@@ -343,7 +344,8 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
"id": i.id,
"order_id": i.order_id,
"product_id": i.product_id,
"product": {"id": i.product.id, "name": i.product.name} if i.product else None,
"product": {"id": i.product.id, "name": i.product.name, "unit_type": i.product.unit_type or "piece",
"one_more_enabled": bool(i.product.one_more_enabled)} if i.product else None, # 6F.5: +1
"product_name": i.product_name, "category_id": i.category_id, "category_name": i.category_name,
"added_by": i.added_by,
"added_by_name": name_map.get(i.added_by),
@@ -366,6 +368,10 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
"system_key": i.system_key, # the delivery fee line (phase 3S, S.5)
"source": i.source, # waiter | counter | qr | online (4.8)
"course_id": i.course_id,
"deal_id": i.deal_id, "linked_item_id": i.linked_item_id,
"split_from_id": i.split_from_id, # 6F.4: the line it was cut from
"cancel_reason": i.cancel_reason,
"split_bill_id": i.split_bill_id, # 6F.6: settled into a split bill (status split) or one of its parts
}
def fmt_log(l):
@@ -418,6 +424,7 @@ def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends
"requested_for": _iso(order.requested_for),
"online_delivery_area": order.online_delivery_area,
"items": [fmt_item(i) for i in order.items],
"split_bills": [split_bills.bill_out(b, order.items) for b in split_bills.live_bills(db, order.id)], # 6F.6
"waiters": [{"waiter_id": w.waiter_id} for w in order.waiters],
"audit_logs": [fmt_log(l) for l in order.audit_logs],
}
@@ -584,20 +591,27 @@ def add_items(order_id: int, body: AddLinesRequest, request: Request, db: Sessio
raise XeniaError("order.not_yours")
lines, manual = _resolve_lines(db, body.lines, of_order(order))
approval = None
reasons = [None] * len(lines)
if any(manual) or any(line.discount_pct for line in lines):
from services import price_changes # the venue's switch and the reason first (6F.3)
reasons = [price_changes.check(db, sent=False, reason=(raw or {}).get("price_reason") if isinstance(raw, dict) else None,
by_hand=bool(hand)) if hand or line.discount_pct else None
for raw, line, hand in zip(body.lines, lines, manual)]
approval = _need(request, db, user, "ordering.prices.modify", target=f"order {order_id} new items")
discounts = [0.0] * len(lines)
if any(line.discount_pct for line in lines):
priced = pos_cart.price_lines(db, lines, order.order_type or "here", pos_cart.order_cart(order), point=of_order(order))
discounts = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
items = []
for raw, line, hand, disc in zip(body.lines, lines, manual, discounts):
for raw, line, hand, disc, reason in zip(body.lines, lines, manual, discounts, reasons):
adj = round(hand + disc, 2)
items.append(OrderItemInput(
product_id=line.product.id, quantity=line.quantity,
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None,
is_service_item=raw.get("is_service_item") is True, course_id=raw.get("course_id"),
price_reason=reason if adj else None,
price_approved_by=approval.approved_by if approval is not None and adj else None,
))
result = add_priced_items(order_id, AddItemsRequest(items=items, order_note=body.order_note,
customer_count=body.customer_count), db, user)
@@ -708,6 +722,11 @@ def add_priced_items(order_id: int, body: AddItemsRequest, db: Session, user: Us
db.add(item)
db.flush()
new_item_ids.append(item.id)
if item.price_adjustment: # a price changed by hand in the cart (6F.3)
from services import price_changes
price_changes.record(db, item=item, before=unit_price, after=unit_price + item.price_adjustment,
user_id=user.id, stage="cart", reason=item_in.price_reason,
approved_by=item_in.price_approved_by)
# Stamp order_id on events and queue them — written after commit
if price_events:
@@ -907,6 +926,9 @@ def cancel_item(
raise XeniaError("order.item_not_found")
if item.status == "paid":
raise XeniaError("order.item_paid")
if item.status not in ("active", "ready"):
raise XeniaError("order.item_not_active")
split_bills.refuse_parts([item]) # 6F.6: undo the split instead
now = utcnow()
item.status = "cancelled"
@@ -957,10 +979,13 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
OrderItem.status.in_(["active", "ready"]), # ready items are also payable
).all()
# Fiscal validation: if enabled, all items must have VAT group assigned before payment
# Fiscal validation: if enabled, all items must have VAT group assigned before payment.
# A split bill's parts (6F.6) aren't on a receipt themselves: the settled lines are, once the
# last part is paid (checked when the bill was made).
fiscal_on = is_fiscal_enabled(db)
if fiscal_on and items:
missing = validate_items_for_fiscal(items, db)
own = [i for i in items if not split_bills.is_part(i)]
if fiscal_on and own:
missing = validate_items_for_fiscal(own, db)
if missing:
names = ", ".join(missing)
raise XeniaError("pos.fiscal_vat_missing", names=names)
@@ -1004,7 +1029,12 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
order.closed_by = user.id
auto_closed = True
if fiscal_on and items:
bills_due = split_bills.receipts_due(db, items) # 6F.6: the last part of a split bill
for due in bills_due:
_audit(db, order_id, "SPLIT_SETTLED", waiter_id=user.id, item_ids=[i.id for i in due["lines"]],
amount=due["bill"].total, note=" + ".join(f"{p['method']} {p['amount']:.2f}" for p in due["payments"]))
fiscal_sent = fiscal_on and (bool(own) or bool(bills_due))
if fiscal_sent:
order.fiscal_status = "pending"
db.commit()
@@ -1012,18 +1042,25 @@ def pay_items(order_id: int, body: PayItemsRequest, request: Request, db: Sessio
if auto_closed:
broadcast_sync("order_closed", {"order_id": order_id, "table_id": order.table_id, "auto_closed": True})
if fiscal_on and items:
if fiscal_on and own:
from database import SessionLocal
fiscal_items = build_fiscal_items(items)
send_fiscal_receipt_background(fiscal_items, effective_method, total_paid, db,
fiscal_items = build_fiscal_items(own)
own_total = sum((i.unit_price + (i.price_adjustment or 0.0)) * i.quantity for i in own)
send_fiscal_receipt_background(fiscal_items, effective_method, own_total, db,
order_id=order_id, db_factory=SessionLocal,
timeout_seconds=60)
if fiscal_on:
from database import SessionLocal
for due in bills_due: # the settled lines as if paid normally, with each method's amount (Q-3)
send_fiscal_receipt_background(build_fiscal_items(due["lines"]), effective_method, due["bill"].total, db,
order_id=order_id, db_factory=SessionLocal, timeout_seconds=60,
payments=due["payments"])
return {
"status": order.status,
"paid_item_ids": paid_ids,
"auto_closed": auto_closed,
"fiscal": "pending" if fiscal_on and items else None,
"fiscal": "pending" if fiscal_sent else None,
}
@@ -1084,6 +1121,8 @@ def close_order(order_id: int, request: Request, db: Session = Depends(get_db),
raise XeniaError("order.not_yours")
if order.status not in ("paid", "open", "partially_paid"):
raise XeniaError("order.cannot_close", status=order.status)
if split_bills.has_unpaid_parts(db, order_id): # 6F.6: never written off: the settled lines were sold
raise XeniaError("split.parts_unpaid")
now = utcnow()
@@ -1240,6 +1279,8 @@ def cancel_order(
if not is_manager and not _waiter_can_cancel(user, db):
# a manager may approve this one cancellation with their PIN (D-10)
approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}")
if split_bills.has_unpaid_parts(db, order_id): # 6F.6: undo the split first
raise XeniaError("split.parts_unpaid")
now = utcnow()
@@ -1303,11 +1344,12 @@ def cancel_items_bulk(
OrderItem.order_id == order_id,
).all()
split_bills.refuse_parts(items) # 6F.6: undo the split instead
now = utcnow()
cancelled_ids = []
skipped_paid = []
for item in items:
if item.status == "paid":
if item.status not in ("active", "ready"): # paid, on a tab, settled by a split bill (6F.6)
skipped_paid.append(item.id)
continue
item.status = "cancelled"
@@ -1420,6 +1462,8 @@ def print_order(
if item.status == "cancelled":
continue
product_name = item.product.name if item.product else f"#{item.product_id}"
if item.split_bill_id is not None and item.status != "split":
product_name = item.product_name # 6F.6: "Split bill 1/3"
adj = getattr(item, 'price_adjustment', 0.0) or 0.0
effective_price = item.unit_price + adj
items_data.append({
@@ -1431,7 +1475,7 @@ def print_order(
"status": item.status,
})
grand_total = sum(i["total"] for i in items_data)
grand_total = sum(i["total"] for i in items_data if i["status"] != "split") # 6F.6: the parts pay for them
receipt = {
"order_id": order.id,
@@ -1485,6 +1529,9 @@ def transfer_order(
order.table_id = body.target_table_id
_audit(db, order_id, "TABLE_TRANSFER", waiter_id=user.id,
note=f"Transferred from table {old_table_id} to table {body.target_table_id}")
from services import moves # 6F.4: the whole order and its lines, on the record
moves.record(db, kind="table_transfer", source=order, target=order, items=list(order.items), user_id=user.id,
from_table_id=old_table_id, to_table_id=body.target_table_id)
db.commit()
db.refresh(order)
broadcast_sync("order_updated", {"order_id": order.id, "table_id": order.table_id, "old_table_id": old_table_id, "status": order.status, "action": "transferred"})
@@ -1527,10 +1574,14 @@ def merge_order(
raise XeniaError("order.same_order")
# Move all items to target order
from services import moves # 6F.4
moves.record(db, kind="orders_merged", source=source, target=target, items=list(source.items), user_id=user.id)
moved_item_ids = []
for item in source.items:
item.order_id = target.id
moved_item_ids.append(item.id)
from models.order import SplitBill # 6F.6: a split bill goes with its lines
db.query(SplitBill).filter(SplitBill.order_id == source.id).update({SplitBill.order_id: target.id}, synchronize_session=False)
# Copy source waiters to target (no duplicates)
existing_waiter_ids = {w.waiter_id for w in target.waiters}
@@ -1568,6 +1619,68 @@ def merge_order(
return target
# ─── Split the bill by amount (6F.6, services/split_bills.py) ─────────────────
class SplitBillRequest(BaseModel):
item_ids: List[int] = Field(min_length=1, max_length=500)
mode: str = "equal" # equal | custom (two parts)
parts: int = Field(default=2, ge=2, le=50)
first_amount: Optional[float] = Field(default=None, gt=0, le=1000000) # custom: part 1, part 2 is the rest
@router.post("/{order_id}/split-bills")
def create_split_bill(order_id: int, body: SplitBillRequest, request: Request, db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
"""Settle the chosen unpaid lines into a split bill and cut it into parts paid on their own
(equal parts, the remainder on the last; or two parts, part 1 typed). The venue's
payments.split_amount decides which splits exist; the key ordering.payments.split_amount (a
manager may approve it once, D-10) who may. The parts are paid with POST /pay like any line."""
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
approval = _need(request, db, user, "ordering.payments.split_amount", target=f"order:{order_id}")
if not _can_access_order(order, user, db):
raise XeniaError("order.not_yours")
if order.status not in ("open", "partially_paid"):
raise XeniaError("order.not_open")
ids = sorted(set(body.item_ids))
items = db.query(OrderItem).filter(OrderItem.order_id == order_id, OrderItem.id.in_(ids)).order_by(OrderItem.id).all()
if len(items) != len(ids):
raise XeniaError("split.lines_changed")
bill = split_bills.create(db, order, items, mode=body.mode, parts=body.parts, first=body.first_amount, user=user)
amounts = json.loads(bill.amounts)
note = f"{bill.parts} parts ({bill.mode}): " + " + ".join(f"{a:.2f}" for a in amounts)
approved = _approval_note(approval)
_audit(db, order_id, "SPLIT_CREATED", waiter_id=user.id, item_ids=ids, amount=bill.total,
note=f"{note}; {approved}" if approved else note)
db.commit()
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "split_created"})
db.refresh(order)
return split_bills.bill_out(bill, order.items)
@router.post("/{order_id}/split-bills/{bill_id}/undo")
def undo_split_bill(order_id: int, bill_id: int, request: Request, db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
"""Undo a split while none of its parts is paid or on a tab (Q-2): the parts are cancelled
("split undone"), the lines are unpaid again. Same key as splitting."""
from models.order import SplitBill
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
approval = _need(request, db, user, "ordering.payments.split_amount", target=f"order:{order_id}")
if not _can_access_order(order, user, db):
raise XeniaError("order.not_yours")
bill = db.get(SplitBill, bill_id)
if bill is None:
raise XeniaError("split.not_found")
back = split_bills.undo(db, order, bill, user)
_audit(db, order_id, "SPLIT_UNDONE", waiter_id=user.id, item_ids=back, amount=bill.total, note=_approval_note(approval))
db.commit()
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "split_undone"})
return {"item_ids": back}
# ─── Split a stacked item into two rows ──────────────────────────────────────
@router.post("/{order_id}/items/{item_id}/split", response_model=List[OrderItemOut])
@@ -1601,21 +1714,7 @@ def split_item(
# Reduce original item
item.quantity -= body.quantity
# Create split-off item
new_item = OrderItem(
source=item.source,
order_id=order_id,
product_id=item.product_id,
added_by=item.added_by,
quantity=body.quantity,
unit_price=item.unit_price,
selected_options=item.selected_options,
removed_ingredients=item.removed_ingredients,
notes=item.notes,
status="active",
printed=item.printed,
)
new_item = cut_part(item, body.quantity)
db.add(new_item)
db.commit()
db.refresh(item)
@@ -1623,10 +1722,141 @@ def split_item(
return [item, new_item]
def cut_part(item, quantity, **changes):
"""A new line cut from `item` (a split, a lowered quantity, 6F.4/6F.5): everything the line was
(product, price and its change, choices, note, kitchen state, course, cost, names, source) for
`quantity`, linked by split_from_id so its moves follow it. Not added to the session."""
fields = dict(
source=item.source, order_id=item.order_id, product_id=item.product_id, added_by=item.added_by,
quantity=quantity, unit_price=item.unit_price, selected_options=item.selected_options,
removed_ingredients=item.removed_ingredients, notes=item.notes, status="active", printed=item.printed,
split_from_id=item.id, kds_status=item.kds_status, course_id=item.course_id,
price_adjustment=item.price_adjustment, unit_cost=item.unit_cost, product_name=item.product_name,
category_id=item.category_id, category_name=item.category_name,
) # added_at = now: the moment it was cut (services/moves.py reads it)
fields.update(changes)
return OrderItem(**fields)
# ─── One more of a line, and a line's quantity (6F.5) ────────────────────────
class AgainRequest(BaseModel):
quantity: int = Field(default=1, ge=1, le=50)
@router.post("/{order_id}/items/{item_id}/again", response_model=AddItemsResponse)
def order_again(order_id: int, item_id: int, body: AgainRequest, request: Request, db: Session = Depends(get_db),
user: User = Depends(get_current_user)):
""""One more" (6F.5): a new line just like this one (product, choices, removed ingredients, note,
course) for `quantity`, priced by the server now and sent like any new line (kitchen ticket,
KDS). Only for products with one_more_enabled, counted in pieces, from an active, paid or
tabbed line that isn't a deal's or the system's. Needs ordering.orders.open."""
from core.access.context import current_device
from schemas.order import OrderItemInput, SelectedOptionInput
_need(request, db, user, "ordering.orders.open", target=f"order:{order_id}")
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
if not _can_access_order(order, user, db):
raise XeniaError("order.not_yours")
item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first()
if item is None:
raise XeniaError("order.item_not_found")
product = item.product
if product is None or not product.one_more_enabled:
raise XeniaError("order.one_more_off")
if item.status not in ("active", "paid", "tabbed") or item.deal_id or item.linked_item_id \
or product.system_key or (product.unit_type or "piece") != "piece":
raise XeniaError("order.one_more_line")
try:
options = [SelectedOptionInput(**o) for o in json.loads(item.selected_options or "[]") if isinstance(o, dict)]
removed = [str(x) for x in json.loads(item.removed_ingredients or "[]")]
except (ValueError, TypeError):
options, removed = [], []
device = current_device(request, db)
source = "counter" if device is not None and device.app_key == "pos_counter" else "waiter"
result = add_priced_items(order_id, AddItemsRequest(items=[OrderItemInput(
product_id=item.product_id, quantity=body.quantity, selected_options=options or None,
removed_ingredients=removed or None, notes=item.notes, course_id=item.course_id, source=source,
)]), db, user)
_audit(db, order_id, "ITEM_REORDERED", waiter_id=user.id, item_ids=[item.id],
note=f"{body.quantity:g} more of #{item.id}")
db.commit()
return result
class QuantityRequest(BaseModel):
quantity: int = Field(ge=1, le=999)
print_cancellation: bool = False # lowering: send a cancellation to the kitchen (the app asks)
@router.post("/{order_id}/items/{item_id}/quantity")
def change_quantity(order_id: int, item_id: int, body: QuantityRequest, request: Request, background_tasks: BackgroundTasks,
db: Session = Depends(get_db), user: User = Depends(get_current_user)):
"""Change a sent line's quantity without sending it again (6F.5). The venue
(orders.quantity_change: off | add_only | add_and_remove) and ordering.items.change_quantity
decide; lowering also needs ordering.orders.cancel (or a manager's PIN each). Up: the line
grows, nothing is printed. Down: the removed part becomes its own cancelled line ("quantity
lowered", split_from_id = the line) and, when asked, a cancellation ticket goes to the kitchen.
Only unpaid lines counted in pieces, not a deal's or the system's."""
from models.settings import PosSettings
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
if not _can_access_order(order, user, db):
raise XeniaError("order.not_yours")
row = db.query(PosSettings).filter(PosSettings.key == "orders.quantity_change").first()
mode = row.value if row is not None and row.value in ("off", "add_only", "add_and_remove") else "off"
if mode == "off":
raise XeniaError("order.quantity_change_off")
item = db.query(OrderItem).filter(OrderItem.id == item_id, OrderItem.order_id == order_id).first()
if item is None:
raise XeniaError("order.item_not_found")
product = item.product
if item.status != "active" or item.deal_id or item.linked_item_id or (product is not None and product.system_key) \
or (item.unit_type or "piece") != "piece" or item.quantity != int(item.quantity):
raise XeniaError("order.quantity_line")
old = int(item.quantity)
if body.quantity == old:
return {"item_id": item.id, "quantity": old, "cancelled_item_id": None}
lowering = body.quantity < old
if lowering and mode != "add_and_remove":
raise XeniaError("order.quantity_remove_off")
approval = _need(request, db, user, "ordering.items.change_quantity", target=f"order:{order_id} item:{item_id}")
cancel_approval = None
if lowering and not holds(user, "core.dashboard.access") and not _waiter_can_cancel(user, db):
cancel_approval = require_override(request, db, "ordering.orders.cancel", target=f"order:{order_id}")
note = f"{old} → {body.quantity}" + (f" · {_approval_note(approval)}" if approval is not None else "")
part = None
if lowering:
now = utcnow()
part = cut_part(item, old - body.quantity, status="cancelled", cancelled_by=user.id, cancelled_at=now,
cancel_reason="quantity lowered")
db.add(part)
item.quantity = body.quantity
db.flush()
_audit(db, order_id, "ITEM_CANCELLED", waiter_id=user.id, item_ids=[part.id],
note=("quantity lowered" + (f" · {_approval_note(cancel_approval)}" if cancel_approval is not None else "")
+ ("" if body.print_cancellation else " · no kitchen ticket")))
else:
item.quantity = body.quantity
_audit(db, order_id, "QUANTITY_CHANGED", waiter_id=user.id, item_ids=[item.id], note=note)
db.commit()
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status,
"action": "quantity_changed", "item_ids": [item.id]})
if part is not None:
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status,
"action": "items_cancelled", "item_ids": [part.id]})
if body.print_cancellation:
background_tasks.add_task(print_cancellation_ticket, order_id, [part.id])
return {"item_id": item.id, "quantity": item.quantity, "cancelled_item_id": part.id if part is not None else None}
# ─── Adjust price on an existing item ────────────────────────────────────────
class PriceAdjustRequest(BaseModel):
price_adjustment: float # delta from unit_price (can be negative)
reason: Optional[str] = Field(default=None, max_length=200) # 6F.3: needed when the venue asks for one
@router.patch("/{order_id}/items/{item_id}/price-adjust", response_model=OrderItemOut)
@@ -1638,8 +1868,10 @@ def adjust_item_price(
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
"""Apply an on-the-fly price adjustment to an active order item. Without
ordering.prices.modify a manager can approve it once (X-Xenia-Override, D-10)."""
"""Change a sent line's price by hand (6F.3): the venue must allow it after sending
(orders.price_change = anytime), it needs ordering.prices.modify_sent (a manager can approve it
once, X-Xenia-Override, D-10) and, when the venue asks, a reason. Recorded as a manual_price
event (before → after, who, the approver, the stage, the reason)."""
item = db.query(OrderItem).filter(
OrderItem.id == item_id, OrderItem.order_id == order_id
).first()
@@ -1647,19 +1879,56 @@ def adjust_item_price(
raise XeniaError("order.item_not_found")
if item.status != "active":
raise XeniaError("order.item_not_active")
split_bills.refuse_parts([item]) # 6F.6
order = db.query(Order).filter(Order.id == order_id).first()
if not _can_access_order(order, user, db):
raise XeniaError("order.not_yours")
_need(request, db, user, "ordering.prices.modify", target=f"order:{order_id} item:{item_id}")
from services import price_changes
reason = price_changes.check(db, sent=True, reason=body.reason)
approval = _need(request, db, user, "ordering.prices.modify_sent", target=f"order:{order_id} item:{item_id}")
if not -10000 <= body.price_adjustment <= 10000 or item.unit_price + body.price_adjustment < 0:
raise XeniaError("order.line.price", line=1, name=item.product_name)
item.price_adjustment = body.price_adjustment
before = item.unit_price + (item.price_adjustment or 0.0)
item.price_adjustment = round(body.price_adjustment, 2)
price_changes.record(db, item=item, before=before, after=item.unit_price + item.price_adjustment, user_id=user.id,
stage=price_changes.stage_of(item), reason=reason,
approved_by=approval.approved_by if approval is not None else None)
db.commit()
db.refresh(item)
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "item_price_adjusted"})
return item
@router.get("/{order_id}/moves")
def order_moves(order_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
"""Where an order and its lines came from (6F.4): {order: [the whole order's transfers and
merges], items: {line id: [its moves, its parents' before it was split from them]}}. Each move:
kind, at, from / to table (id, name) and order, who, the lines and quantities."""
from services import moves
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
if not _can_access_order(order, user, db):
raise XeniaError("order.not_yours")
return moves.for_order(db, order)
@router.get("/{order_id}/price-changes")
def order_price_changes(order_id: int, db: Session = Depends(get_db),
user: User = Depends(require("ordering.prices.view_changes"))):
"""The prices changed by hand on an order (6F.3), oldest first, for the waiter app and the
counter: [{id, item_id, product_name, before, after, delta, quantity, stage, reason, by, approved_by, at}]."""
from models.pricing import PriceEventLog
from services import price_changes
order = db.get(Order, order_id)
if order is None:
raise XeniaError("order.not_found", order_id=order_id)
return [price_changes.event_out(ev, db) for ev in db.query(PriceEventLog).filter(
PriceEventLog.order_id == order_id, PriceEventLog.event_type == price_changes.EVENT).order_by(PriceEventLog.id)]
# ─── Waiter-applied manual discount ─────────────────────────────────────────
from schemas.pricing import ApplyDiscountRequest, ApplyDiscountResponse
@@ -1697,6 +1966,7 @@ def apply_waiter_discount(
).all()
if not items:
raise XeniaError("order.no_active_items", status=404)
split_bills.refuse_parts(items) # 6F.6
item_unit_prices = {i.id: i.unit_price + i.price_adjustment for i in items}
@@ -1924,7 +2194,10 @@ def move_items(
).all()
if not items:
raise XeniaError("order.no_active_items")
split_bills.refuse_parts(items) # 6F.6: a part stays with its bill
from services import moves # 6F.4
moves.record(db, kind="items_moved", source=source, target=target, items=items, user_id=user.id)
moved_ids = []
for item in items:
item.order_id = target.id
@@ -1988,6 +2261,8 @@ def print_synopsis(
if item.status == "cancelled":
continue
product_name = item.product.name if item.product else f"#{item.product_id}"
if item.split_bill_id is not None and item.status != "split":
product_name = item.product_name # 6F.6: "Split bill 1/3"
adj = getattr(item, 'price_adjustment', 0.0) or 0.0
effective_price = item.unit_price + adj
items_data.append({
@@ -1999,7 +2274,7 @@ def print_synopsis(
"status": item.status,
})
total = sum(i["total"] for i in items_data)
total = sum(i["total"] for i in items_data if i["status"] != "split") # 6F.6: the parts pay for them
paid_total = sum(i["total"] for i in items_data if i["status"] == "paid")
synopsis = {
@@ -2112,6 +2387,7 @@ def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db
raise XeniaError("order.items_not_combinable", reason="not_found")
if any(i.status != "active" for i in items):
raise XeniaError("order.items_not_combinable", reason="not_unpaid")
split_bills.refuse_parts(items) # 6F.6
if any(i.deal_id or i.linked_item_id for i in items) or \
db.query(OrderItem).filter(OrderItem.linked_item_id.in_(ids)).first() is not None:
raise XeniaError("order.items_not_combinable", reason="deal")
@@ -2127,6 +2403,8 @@ def combine_items(order_id: int, body: CombineItemsRequest, request: Request, db
rest_ids = [i.id for i in rest]
db.query(PriceEventLog).filter(PriceEventLog.order_item_id.in_(rest_ids)).update(
{PriceEventLog.order_item_id: keep.id}, synchronize_session=False)
from services import moves # 6F.4
moves.repoint(db, rest_ids, keep.id)
for i in rest:
db.delete(i)
_audit(db, order_id, "ITEMS_COMBINED", waiter_id=user.id, item_ids=[keep.id] + rest_ids,
+87 -11
View File
@@ -89,6 +89,7 @@ def _product_out(p, price: float, prices: dict | None = None) -> dict:
"price": round(price, 2), "prices": {k: round(v, 2) for k, v in (prices or {}).items()},
"sold_at": [sp for sp in sales_points.sold_at(p) if sp in sales_points.IN_PERSON],
"base_price": round(p.base_price, 2), "unit_type": p.unit_type or "piece",
"one_more": bool(p.one_more_enabled), # 6F.5
"tags": _tags(p.tags),
"allergens": allergens.of(p),
"primary_category_id": p.primary_category_id,
@@ -140,8 +141,12 @@ def pos_menu(request: Request, db: Session = Depends(get_db), user=Depends(requi
by_point = {sp: pos_cart.unit_prices(db, products, sp) for sp in sales_points.IN_PERSON}
default = pos_cart.point_for(settings["default_order_type"])
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
from services import price_changes, split_bills
return {
"settings": settings,
# + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount
"settings": {**settings, "price_change": price_changes.mode(db),
# 6F.6: splitting a bill by amount (the level and the most equal parts)
"split_amount": split_bills.level(db), "split_max_parts": split_bills.max_parts(db)},
"categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order}
for c in cats],
"products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON})
@@ -177,14 +182,25 @@ class Payment(BaseModel):
lines: Optional[List[int]] = None # indexes into `lines`; None = all of them
class SaleSplit(BaseModel):
"""A quick sale split by amount (6F.6, Q-4): the parts and how each is paid, all now."""
mode: Literal["equal", "custom"] = "equal"
parts: int = Field(default=2, ge=2, le=50)
first_amount: Optional[float] = Field(default=None, gt=0, le=1000000)
methods: List[Literal["cash", "card"]] = Field(min_length=2, max_length=50) # one per part
class SaleBody(BaseModel):
order_type: Literal["takeaway", "here"] = "takeaway"
lines: List[dict] = Field(min_length=1, max_length=200)
payments: List[Payment] = Field(min_length=1, max_length=2)
payments: List[Payment] = Field(default_factory=list, max_length=2) # without `split`: at least one
split: Optional[SaleSplit] = None
cash_given: Optional[float] = Field(default=None, ge=0, le=100000)
def _payment_groups(body: SaleBody, n: int) -> list:
if not body.payments:
raise XeniaError("pos.payment_invalid", reason="lines")
if len(body.payments) == 1 and body.payments[0].lines is None:
return [(body.payments[0].method, list(range(n)))]
seen = [i for pay in body.payments for i in (pay.lines or [])]
@@ -208,17 +224,19 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
_require_shift(db, user)
orders_api._need(request, db, user, "ordering.orders.close", target="pos sale") # 4.3: taking payment is a key
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
groups = _payment_groups(body, len(lines))
_check_discounts(request, db, user, lines)
groups = _payment_groups(body, len(lines)) if body.split is None else []
approved_by = _check_discounts(request, db, user, lines)
_check_fiscal(db, {line.product for line in lines})
priced = pos_cart.price_lines(db, lines, body.order_type)
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
totals = [round((unit + adj) * line.quantity, 2) for line, (unit, _), adj in zip(lines, priced, adjs)]
if body.split is not None:
return _split_sale(body, request, db, user, lines, adjs, approved_by, totals)
cash_due = round(sum(totals[i] for method, idx in groups if method == "cash" for i in idx), 2)
_check_cash(body.cash_given, cash_due)
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user)
item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()]
paid, fiscal = [], None
for method, idx in groups:
@@ -236,6 +254,53 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
}
def _split_sale(body, request, db, user, lines, adjs, approved_by, totals):
"""A quick sale split by amount (6F.6, Q-4): the order and its lines as any quick sale, then
the lines settled into a split bill and each part paid now by its own method (one payment per
method). The fiscal receipt is the lines themselves, issued with the last part (Q-3)."""
from models.order import OrderItem
from routers import orders as orders_api
from schemas.order import AddItemsRequest, OrderCreate, PayItemsRequest
from services import split_bills
sp = body.split
orders_api._need(request, db, user, "ordering.payments.split_amount", target="pos sale")
if len(sp.methods) != sp.parts:
raise XeniaError("pos.payment_invalid", reason="lines")
if not split_bills.allowed(split_bills.level(db), sp.mode, sp.parts, split_bills.max_parts(db)):
raise XeniaError("split.not_allowed")
total = round(sum(totals), 2)
if total < 0.01 * sp.parts:
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
amounts = split_bills.amounts(total, sp.mode, sp.parts, sp.first_amount)
cash_due = round(sum(a for a, m in zip(amounts, sp.methods) if m == "cash"), 2)
_check_cash(body.cash_given, cash_due)
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user)
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user)
items = db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()
bill = split_bills.create(db, order, items, mode=sp.mode, parts=sp.parts, first=sp.first_amount, user=user)
orders_api._audit(db, order.id, "SPLIT_CREATED", waiter_id=user.id, item_ids=[i.id for i in items], amount=bill.total,
note=f"{bill.parts} parts ({bill.mode}): " + " + ".join(f"{a:.2f}" for a in amounts))
db.commit()
parts = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id, OrderItem.status == "active").order_by(OrderItem.id).all()
paid, fiscal = [], None
for method in ("cash", "card"):
ids = [p.id for p, m in zip(parts, sp.methods) if m == method]
if not ids:
continue
res = orders_api.pay_items(order.id, PayItemsRequest(item_ids=ids, payment_method=method), request, db, user)
paid.append({"method": method, "amount": round(sum(a for a, m in zip(amounts, sp.methods) if m == method), 2),
"item_ids": res["paid_item_ids"]})
fiscal = res.get("fiscal") or fiscal
drawer = _open_drawer(request, db, user, order.id) if cash_due > 0 else "none"
change = round(body.cash_given - cash_due, 2) if body.cash_given is not None and cash_due else None
return {
"order_id": order.id, "total": total, "payments": paid, "split": {"id": bill.id, "amounts": amounts, "methods": sp.methods},
"cash_given": body.cash_given, "change": change, "drawer": drawer, "fiscal": fiscal,
"print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", []),
}
# ── shared checks (3.3b, 3.3c) ─────────────────────────────────────────────────
def _require_shift(db, user):
@@ -247,9 +312,16 @@ def _require_shift(db, user):
def _check_discounts(request, db, user, lines):
"""A % discount at the counter is a price change in the cart (6F.3): the venue's switch, then
the key (or a manager's PIN). Returns the approving manager's id, else None. The reason isn't
asked: the discount itself says what it is."""
from core.access.context import authorize
from services import price_changes
if any(line.discount_pct for line in lines):
authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
price_changes.check(db, sent=False, by_hand=False)
approval = authorize(request, db, user, "ordering.prices.modify", target="pos sale discount")
return approval.approved_by if approval is not None else None
return None
def _check_fiscal(db, products):
@@ -265,14 +337,17 @@ def _check_cash(cash_given, cash_due):
raise XeniaError("pos.payment_invalid", reason="cash_short")
def _items_in(lines, adjs):
def _items_in(lines, adjs, approved_by=None):
"""Resolved lines as orders.add_priced_items takes them (selected_options entries with the
database's prices; a discount as the item's price_adjustment)."""
database's prices; a discount as the item's price_adjustment, recorded as a manual_price event
with "−N %" as its reason, 6F.3)."""
from schemas.order import OrderItemInput, SelectedOptionInput
return [OrderItemInput(
product_id=line.product.id, quantity=line.quantity,
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None,
removed_ingredients=line.removed or None, notes=line.notes, price_adjustment=adj or None, source="counter",
price_reason=f"−{line.discount_pct:g} %" if adj and line.discount_pct else None,
price_approved_by=approved_by if adj else None,
) for line, adj in zip(lines, adjs)]
@@ -407,13 +482,13 @@ def pos_table_items(table_id: int, body: TableItemsBody, request: Request, db: S
elif not _in_zones(db, user, table):
raise XeniaError("pos.table_not_yours", table=_table_name(table))
lines = [pos_cart.resolve_line(db, raw if isinstance(raw, dict) else {}, n) for n, raw in enumerate(body.lines)]
_check_discounts(request, db, user, lines)
approved_by = _check_discounts(request, db, user, lines)
existing = pos_cart.order_cart(order) if order is not None else None
priced = pos_cart.price_lines(db, lines, (order.order_type or "here") if order is not None else "here", existing)
adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
if order is None:
order = orders_api.open_order(OrderCreate(table_id=table_id, order_type="here"), db, user)
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs)), db, user)
added = orders_api.add_priced_items(order.id, AddItemsRequest(items=_items_in(lines, adjs, approved_by)), db, user)
return {"order_id": order.id, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", [])}
@@ -445,7 +520,8 @@ def pos_order_pay(order_id: int, body: OrderPayBody, request: Request, db: Sessi
items = {i.id: i for i in db.query(OrderItem).filter(OrderItem.order_id == order.id, OrderItem.id.in_(wanted)).all()}
if len(items) != len(wanted) or any(i.status not in UNPAID for i in items.values()):
raise XeniaError("pos.items_changed")
_check_fiscal(db, {i.product for i in items.values()})
from services.split_bills import is_part
_check_fiscal(db, {i.product for i in items.values() if not is_part(i)}) # 6F.6: the settled lines were checked
amount = {pay.method: round(sum(_item_total(items[i]) for i in pay.item_ids), 2) for pay in body.payments}
cash_due = amount.get("cash", 0.0)
_check_cash(body.cash_given, cash_due)
+8 -7
View File
@@ -527,12 +527,11 @@ def get_order_price_events(
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
events = (
db.query(PriceEventLog)
.filter(PriceEventLog.order_id == order_id)
.order_by(PriceEventLog.applied_at)
.all()
)
from services import price_changes
q = db.query(PriceEventLog).filter(PriceEventLog.order_id == order_id)
if not price_changes.can_view(user): # prices changed by hand: ordering.prices.view_changes (6F.3)
q = q.filter(PriceEventLog.event_type != price_changes.EVENT)
events = q.order_by(PriceEventLog.applied_at).all()
result = []
for ev in events:
out = PriceEventOut.model_validate(ev)
@@ -541,7 +540,9 @@ def get_order_price_events(
if ev.deal:
out.deal_name = ev.deal.name
if ev.applied_by:
out.applied_by_username = ev.applied_by.username
out.applied_by_username = ev.applied_by.nickname or ev.applied_by.username
if ev.approved_by:
out.approved_by_username = ev.approved_by.nickname or ev.approved_by.username
result.append(out)
return result
+140 -13
View File
@@ -2,7 +2,7 @@ from core.access.queries import holders_filter
from core.errors import XeniaError
from core.modules.entitlements import clamp_start, history_floor, history_since, limit
from core.timeutil import business_date_of, business_date_window, parse_api_datetime, venue_strftime, to_venue, utcnow
from services import tab_books
from services import split_bills, tab_books # split_bills: 6F.6, settled lines count, parts never
import csv
import io
import json
@@ -164,7 +164,7 @@ def shift_orders_summary(
user: User = Depends(require_reports),
):
"""Items sent (added) per waiter — regardless of payment status."""
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
q = db.query(OrderItem).filter(split_bills.sold_filter())
start = end = None # 6.12a: with a business day there is no window (was a crash)
if business_day_id:
q = q.join(Order).filter(Order.business_day_id == business_day_id)
@@ -496,7 +496,7 @@ def printer_totals(
item_ids = []
for item_id in item_ids:
item = db.query(OrderItem).filter(OrderItem.id == item_id).first()
if item and item.status in ("active", "paid"):
if item and split_bills.counts_as_sale(item):
summary[pid]["items"] += item.quantity
val = _item_val(item)
summary[pid]["total"] += val
@@ -565,7 +565,7 @@ def _build_printer_block(printer_id: int, printer_name: str, logs, tables, db, m
item_ids = []
for item_id in item_ids:
item = db.query(OrderItem).filter(OrderItem.id == item_id).first()
if item and item.status in ("active", "paid"):
if item and split_bills.counts_as_sale(item):
items_count += item.quantity
val = _item_val(item)
grand_total += val
@@ -633,7 +633,7 @@ def print_waiter(
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
order_data = []
for o in orders:
active_items = [i for i in o.items if i.status in ("active", "paid")]
active_items = [i for i in o.items if split_bills.counts_as_sale(i)]
total = sum(_item_val(i) for i in active_items)
order_data.append({
"id": o.id,
@@ -648,7 +648,7 @@ def print_waiter(
})
items_count = sum(
i.quantity for o in orders for i in o.items if i.status in ("active", "paid")
i.quantity for o in orders for i in o.items if split_bills.counts_as_sale(i)
)
grand_total = sum(d["total"] for d in order_data)
@@ -778,7 +778,7 @@ def print_products(
period_label, period_is_workday = _analytics_period(body, db)
# Build sold-item summary
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
q = db.query(OrderItem).filter(split_bills.sold_filter())
if body.business_day_id:
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
elif body.from_dt and body.to_dt:
@@ -837,7 +837,7 @@ def print_categories(
period_label, period_is_workday = _analytics_period(body, db)
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
q = db.query(OrderItem).filter(split_bills.sold_filter())
if body.business_day_id:
q = q.join(Order).filter(Order.business_day_id == body.business_day_id)
elif body.from_dt and body.to_dt:
@@ -974,7 +974,7 @@ def product_performance(
from models.product import Product
from models.waste import WasteLog
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
q = db.query(OrderItem).filter(split_bills.sold_filter())
_since = history_since(from_dt, 'reports')
if _since:
q = q.filter(OrderItem.added_at >= _since)
@@ -1337,7 +1337,7 @@ def category_performance(
):
from models.product import Product, Category
q = db.query(OrderItem).filter(OrderItem.status.in_(["active", "paid"]))
q = db.query(OrderItem).filter(split_bills.sold_filter())
_since = history_since(from_dt, 'reports')
if _since:
q = q.filter(OrderItem.added_at >= _since)
@@ -1504,7 +1504,7 @@ def printer_history(
order_total = sum(
_item_val(i)
for i in order.items
if i.status in ("active", "paid")
if split_bills.counts_as_sale(i)
)
if log.success and log.order_id not in seen_order_totals:
seen_order_totals[log.order_id] = order_total
@@ -1713,7 +1713,7 @@ def prep_zones_report(
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
if business_day_id:
q = q.filter(Order.business_day_id == business_day_id)
q = q.filter(OrderItem.status.in_(["active", "paid"]))
q = q.filter(split_bills.sold_filter())
items = q.all()
# Aggregate per zone
@@ -1839,7 +1839,7 @@ def print_prep_zone(
q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt))
if body.business_day_id:
q = q.filter(Order.business_day_id == body.business_day_id)
q = q.filter(OrderItem.status.in_(["active", "paid"]))
q = q.filter(split_bills.sold_filter())
items = q.all()
product_counts: dict[str, dict] = {}
@@ -1872,6 +1872,133 @@ def print_prep_zone(
# Phase 2L — Discount audit report
# ---------------------------------------------------------------------------
@router.get("/moves")
def moves_report(
from_dt: Optional[str] = Query(default=None, alias="from"),
to_dt: Optional[str] = Query(default=None, alias="to"),
business_day_id: Optional[int] = None,
kind: Optional[str] = None,
by: Optional[int] = None,
table_id: Optional[int] = None,
db: Session = Depends(get_db),
user: User = Depends(require_reports),
):
"""Moves between tables and orders (6F.4) in a period or a business day: each move (kind, from /
to table and order, who, the lines with their quantity and value), counts per kind and per
person. `table_id`: moves from or to that table."""
from models.order import OrderMove, OrderItem
from services import moves
q = db.query(OrderMove)
if business_day_id:
q = q.filter(OrderMove.business_day_id == business_day_id)
elif from_dt and to_dt:
q = q.filter(OrderMove.at >= history_since(from_dt, 'reports'), OrderMove.at <= parse_api_datetime(to_dt))
if kind:
q = q.filter(OrderMove.kind == kind)
if by:
q = q.filter(OrderMove.by_user_id == by)
if table_id:
q = q.filter((OrderMove.from_table_id == table_id) | (OrderMove.to_table_id == table_id))
rows = q.order_by(OrderMove.at.desc()).all()
tables, users = moves._names(db)
item_ids = {i.item_id for m in rows for i in m.items}
lines = {i.id: i for i in db.query(OrderItem).filter(OrderItem.id.in_(item_ids)).all()} if item_ids else {}
names = {i.id: i.product_name for i in lines.values()}
out, by_kind, by_person = [], {}, {}
for m in rows:
row = moves.move_out(m, tables, users, names)
row["at"] = _dt(m.at)
row["value"] = round(sum(((lines[i.item_id].unit_price or 0) + (lines[i.item_id].price_adjustment or 0)) * (i.quantity or lines[i.item_id].quantity or 0)
for i in m.items if i.item_id in lines), 2)
out.append(row)
by_kind[m.kind] = by_kind.get(m.kind, 0) + 1
p = by_person.setdefault(m.by_user_id, {"user_id": m.by_user_id, "name": row["by"], "count": 0})
p["count"] += 1
return {"moves": out, "count": len(out), "by_kind": by_kind,
"by_person": sorted(by_person.values(), key=lambda x: -x["count"])}
@router.get("/moves/export")
def moves_export(
from_dt: Optional[str] = Query(default=None, alias="from"),
to_dt: Optional[str] = Query(default=None, alias="to"),
business_day_id: Optional[int] = None,
kind: Optional[str] = None,
by: Optional[int] = None,
table_id: Optional[int] = None,
db: Session = Depends(get_db),
user: User = Depends(require_reports),
):
data = moves_report(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, kind=kind, by=by, table_id=table_id, db=db, user=user)
rows = [{"id": m["id"], "at": m["at"], "kind": m["kind"], "from_table": m["from_table"] or "", "to_table": m["to_table"] or "",
"from_order": m["from_order_id"], "to_order": m["to_order_id"], "by": m["by"] or "",
"lines": "; ".join(f"{i.get('name') or i['item_id']} ×{i['quantity'] if i['quantity'] is not None else '?'}" for i in m["items"]),
"value": m["value"]} for m in data["moves"]]
fields = ["id", "at", "kind", "from_table", "to_table", "from_order", "to_order", "by", "lines", "value"]
return csv_export.response(db, rows, fields, f"moves-{(from_dt or '')[:10]}.csv", times=("at",))
@router.get("/price-changes")
def price_changes_report(
from_dt: Optional[str] = Query(default=None, alias="from"),
to_dt: Optional[str] = Query(default=None, alias="to"),
business_day_id: Optional[int] = None,
applied_by: Optional[int] = None,
db: Session = Depends(get_db),
user: User = Depends(require_reports),
):
"""Prices changed by hand (6F.3) in a period or a business day: each change (the line, before →
after, the difference for its quantity, the stage, who, the approving manager, why, the table),
totals per person. Needs ordering.prices.view_changes besides the reports key."""
from core.access.check import holds
from models.pricing import PriceEventLog
from services import price_changes
if not holds(user, "ordering.prices.view_changes"):
raise XeniaError("access.denied", key="ordering.prices.view_changes")
q = db.query(PriceEventLog).filter(PriceEventLog.event_type == price_changes.EVENT)
if business_day_id:
q = q.join(Order, Order.id == PriceEventLog.order_id).filter(Order.business_day_id == business_day_id)
elif from_dt and to_dt:
q = q.filter(PriceEventLog.applied_at >= history_since(from_dt, 'reports'),
PriceEventLog.applied_at <= parse_api_datetime(to_dt))
if applied_by:
q = q.filter(PriceEventLog.applied_by_user_id == applied_by)
events = q.order_by(PriceEventLog.applied_at.desc()).all()
tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
orders_map = {o.id: o for o in db.query(Order).filter(Order.id.in_({e.order_id for e in events})).all()} if events else {}
rows, by_person, total = [], {}, 0.0
for ev in events:
row = price_changes.event_out(ev, db)
row["at"] = _dt(ev.applied_at)
order = orders_map.get(ev.order_id)
row["table_name"] = tables_map.get(order.table_id) if order is not None and order.table_id else None
row["value"] = round((ev.delta_amount or 0.0) * (ev.quantity or 1.0), 2)
total += row["value"]
p = by_person.setdefault(ev.applied_by_user_id, {"user_id": ev.applied_by_user_id, "name": row["by"], "count": 0, "total_value": 0.0})
p["count"] += 1
p["total_value"] = round(p["total_value"] + row["value"], 2)
rows.append(row)
return {"changes": rows, "total_value": round(total, 2), "count": len(rows),
"by_person": sorted(by_person.values(), key=lambda x: x["total_value"])}
@router.get("/price-changes/export")
def price_changes_export(
from_dt: Optional[str] = Query(default=None, alias="from"),
to_dt: Optional[str] = Query(default=None, alias="to"),
business_day_id: Optional[int] = None,
applied_by: Optional[int] = None,
db: Session = Depends(get_db),
user: User = Depends(require_reports),
):
data = price_changes_report(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, applied_by=applied_by, db=db, user=user)
rows = [{"id": c["id"], "order_id": c["order_id"], "table": c["table_name"] or "", "product": c["product_name"] or "",
"quantity": c["quantity"], "before": c["before"], "after": c["after"], "value": c["value"], "stage": c["stage"] or "",
"by": c["by"] or "", "approved_by": c["approved_by"] or "", "reason": c["reason"] or "", "at": c["at"]} for c in data["changes"]]
fields = ["id", "order_id", "table", "product", "quantity", "before", "after", "value", "stage", "by", "approved_by", "reason", "at"]
return csv_export.response(db, rows, fields, f"price-changes-{(from_dt or '')[:10]}.csv", times=("at",))
@router.get("/discounts")
def discounts_report(
from_dt: Optional[str] = Query(default=None, alias="from"),
File diff suppressed because it is too large Load Diff
+6
View File
@@ -26,6 +26,9 @@ class OrderItemInput(BaseModel):
is_service_item: bool = False # priceless: print-once ephemeral; priced: saved as real item
course_id: Optional[int] = None
source: Optional[str] = None # set by the server (4.8): waiter | counter | qr | online
# a price changed by hand (6F.3), set by the server: the reason and the approving manager
price_reason: Optional[str] = None
price_approved_by: Optional[int] = None
class AddItemsRequest(BaseModel):
@@ -37,6 +40,8 @@ class AddItemsRequest(BaseModel):
class ProductNameOut(BaseModel):
id: int
name: str
one_more_enabled: bool = False # 6F.5: the line shows +1
unit_type: Optional[str] = None
model_config = {"from_attributes": True}
@@ -68,6 +73,7 @@ class OrderItemOut(BaseModel):
source: Optional[str] = None # waiter | counter | qr | online (4.8); None = before 4.8
deal_id: Optional[int] = None
linked_item_id: Optional[int] = None
split_from_id: Optional[int] = None # 6F.4: the line it was cut from
system_key: Optional[str] = None # a line the system added: "delivery_fee" (phase 3S, S.5)
model_config = {"from_attributes": True}
+5
View File
@@ -308,10 +308,15 @@ class PriceEventOut(BaseModel):
conditions_snapshot: Optional[dict]
selected_item_ids: Optional[List[int]]
applied_at: datetime
# manual_price (6F.3)
approved_by_user_id: Optional[int] = None
stage: Optional[str] = None
quantity: Optional[float] = None
# Resolved names (joined at query time)
modifier_name: Optional[str] = None
deal_name: Optional[str] = None
applied_by_username: Optional[str] = None
approved_by_username: Optional[str] = None
model_config = {"from_attributes": True}
+3
View File
@@ -386,6 +386,7 @@ class ProductBase(BaseModel):
cost_breakdown: Optional[List[CostBreakdownItem]] = None
# Quick Add
quick_add_enabled: bool = True
one_more_enabled: bool = False # 6F.5
# Tags
tags: Optional[List[str]] = None
# The EU allergens (plan step 6.3): {key: "contains" | "may_contain"}, core/allergens.py
@@ -437,6 +438,7 @@ class ProductUpdate(BaseModel):
cost_breakdown: Optional[List[CostBreakdownItem]] = None
# Quick Add
quick_add_enabled: Optional[bool] = None
one_more_enabled: Optional[bool] = None # 6F.5
# Tags
tags: Optional[List[str]] = None
allergens: Optional[Dict[str, str]] = None # None = unchanged, {} = none
@@ -510,6 +512,7 @@ class ProductOut(ProductBase):
'cost_simple': data.cost_simple,
'cost_breakdown': parsed,
'quick_add_enabled': getattr(data, 'quick_add_enabled', True),
'one_more_enabled': bool(getattr(data, 'one_more_enabled', False)),
'tags': json.loads(data.tags) if isinstance(getattr(data, 'tags', None), str) else (getattr(data, 'tags', None) or []),
'allergens': _allergens_of(data),
'translations': _menu_tr_of(data),
+2 -1
View File
@@ -43,7 +43,8 @@ def card(db, customer) -> dict:
from models.table import Table
orders = db.query(Order).filter(Order.customer_id == customer.id).order_by(Order.opened_at.desc()).all()
done = [o for o in orders if o.status in ("closed", "paid")]
live = lambda o: [i for i in o.items if i.status in ("active", "paid")] # noqa: E731
from services.split_bills import counts_as_sale
live = lambda o: [i for i in o.items if counts_as_sale(i)] # noqa: E731 (6F.6: settled lines, not parts)
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
return {
"id": customer.id, "name": customer.name, "nickname": customer.nickname, "phone": customer.phone,
+5 -4
View File
@@ -125,13 +125,14 @@ def _in_background(db_factory, model, row_id: int, prepare, timeout_seconds: int
def send_fiscal_receipt_background(items: list[dict], payment_method: str, total: float, db, order_id: int,
db_factory, timeout_seconds: int = 60) -> None:
db_factory, timeout_seconds: int = 60, payments: list[dict] | None = None) -> None:
"""Issue the receipt through the venue's driver in a background thread; order.fiscal_status
becomes success or failed when the device answers (or the wait times out)."""
becomes success or failed when the device answers (or the wait times out). `payments`
[{"method", "amount"}]: a receipt paid in several ways (a split bill's parts, 6F.6)."""
from models.order import Order
driver = driver_for(db)
_in_background(db_factory, Order, order_id, lambda: driver.prepare_receipt(db, items, payment_method, total),
timeout_seconds)
_in_background(db_factory, Order, order_id,
lambda: driver.prepare_receipt(db, items, payment_method, total, payments=payments), timeout_seconds)
def send_credit_note_background(items: list[dict], method: str, total: float, db, refund_id: int, original: dict,
+3 -2
View File
@@ -28,8 +28,9 @@ class FiscalDriver:
# cashier is told to issue the credit note on the machine itself (owner decision 2026-11-15).
credit_notes: bool = False
def prepare_receipt(self, db, items: list[dict], method: str, total: float) -> Send:
"""A sales receipt, ready to send."""
def prepare_receipt(self, db, items: list[dict], method: str, total: float, payments: list[dict] | None = None) -> Send:
"""A sales receipt, ready to send. `payments` [{"method", "amount"}] when it was paid in
several ways (a split bill, 6F.6); else all of it by `method`."""
raise NotImplementedError
def prepare_credit_note(self, db, items: list[dict], method: str, total: float, original: dict | None = None) -> Send:
+12 -4
View File
@@ -62,7 +62,7 @@ def _get_folders(db) -> tuple[str, str]:
return out_folder, in_folder
def _build_command_file(items: list[dict], payment_method: str, total: float, db) -> str:
def _build_command_file(items: list[dict], payment_method: str, total: float, db, payments: list[dict] | None = None) -> str:
"""
Build the fiscal command file content as a string.
@@ -98,7 +98,15 @@ def _build_command_file(items: list[dict], payment_method: str, total: float, db
if msg_line.strip():
lines.append(f"FM|{i}|{msg_line.upper()}")
if payment_method == "card":
if payments and len(payments) > 1:
# Paid in several ways (a split bill, 6F.6; the driver manual's "multiple ways to close"):
# each card amount through the EFT/POS first, then cash closes the rest.
card = [p for p in payments if p.get("method") == "card" and p.get("amount", 0) > 0]
for p in card:
lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{p['amount']:.2f}")
if round(sum(p.get("amount", 0) for p in payments if p not in card), 2) > 0:
lines.append(f"CR|{clerk_id}")
elif (payments[0].get("method") if payments else payment_method) == "card":
total_str = f"{total:.2f}"
lines.append(f"CD|{clerk_id}|{eftpos_id}|1|{total_str}")
else:
@@ -177,11 +185,11 @@ class TxtFileDriver(FiscalDriver):
name = "dTEC100extra (text-file bridge)"
credit_notes = False
def prepare_receipt(self, db, items, method, total):
def prepare_receipt(self, db, items, method, total, payments=None):
out_folder, in_folder = _get_folders(db)
os.makedirs(out_folder, exist_ok=True)
os.makedirs(in_folder, exist_ok=True)
content = _build_command_file(items, method, total, db)
content = _build_command_file(items, method, total, db, payments)
filename = _unique_filename()
return lambda timeout_seconds: _write_and_poll(out_folder, in_folder, content, filename, timeout_seconds)
+133
View File
@@ -0,0 +1,133 @@
"""Moves on the record (owner 2026-11-23, plan step 6F.4).
Every move between tables or orders is an `OrderMove` row with the lines that went
(`OrderMoveItem`: the line and its quantity then):
- `table_transfer`: the whole order went to another (free) table (POST /api/orders/{id}/transfer);
- `items_moved`: chosen lines went to another open order (POST /api/orders/{id}/move-items);
- `orders_merged`: an order was joined into another (POST /api/orders/{id}/merge).
A line keeps its id when it moves, so its path is its own moves. A line cut from another
(`OrderItem.split_from_id`: a split, later a lowered quantity or a split payment) also carries
the moves its parent had **before** the cut, however many times that happened. Combining lines
moves the removed lines' moves to the line that stays (routers/orders.combine_items).
Readers: GET /api/orders/{id}/moves (the order's path and each line's), Reports → Moves
(GET /api/reports/moves). The old OrderAuditLog rows stay as they were.
"""
from __future__ import annotations
KINDS = ("table_transfer", "items_moved", "orders_merged")
def record(db, *, kind: str, source, target, items, user_id: int | None, from_table_id=None, to_table_id=None,
approved_by: int | None = None):
"""One move (flushed with the caller's commit). `source` / `target`: orders; `items`: lines."""
from models.order import OrderMove, OrderMoveItem
assert kind in KINDS, kind
move = OrderMove(
kind=kind, from_order_id=getattr(source, "id", None), to_order_id=getattr(target, "id", None),
from_table_id=from_table_id if from_table_id is not None else getattr(source, "table_id", None),
to_table_id=to_table_id if to_table_id is not None else getattr(target, "table_id", None),
by_user_id=user_id, approved_by_user_id=approved_by,
business_day_id=getattr(target, "business_day_id", None) or getattr(source, "business_day_id", None),
)
move.items = [OrderMoveItem(item_id=i.id, quantity=i.quantity) for i in items]
db.add(move)
return move
def repoint(db, from_ids, to_id: int) -> None:
"""Lines removed by a combine: their moves (and children) now belong to the line kept."""
from models.order import OrderItem, OrderMoveItem
from_ids = [i for i in from_ids if i != to_id]
if not from_ids:
return
for mi in db.query(OrderMoveItem).filter(OrderMoveItem.item_id.in_(from_ids)).all():
taken = db.query(OrderMoveItem).filter(OrderMoveItem.move_id == mi.move_id, OrderMoveItem.item_id == to_id).first()
if taken is None:
db.add(OrderMoveItem(move_id=mi.move_id, item_id=to_id, quantity=mi.quantity))
else:
taken.quantity = (taken.quantity or 0) + (mi.quantity or 0)
db.delete(mi)
db.query(OrderItem).filter(OrderItem.split_from_id.in_(from_ids)).update(
{OrderItem.split_from_id: to_id}, synchronize_session=False)
def _lineage(db, item):
"""[(line id, moves up to when) …]: the line itself (all its moves), then each parent up to the
moment the child was cut from it."""
from models.order import OrderItem
out, seen = [(item.id, None)], {item.id}
child = item
while child.split_from_id and child.split_from_id not in seen:
parent = db.get(OrderItem, child.split_from_id)
if parent is None:
break
out.append((parent.id, child.added_at))
seen.add(parent.id)
child = parent
return out
def item_moves(db, item) -> list:
"""The moves a line went through, oldest first (its parents' before it was cut from them)."""
from models.order import OrderMove, OrderMoveItem
found = {}
for line_id, until in _lineage(db, item):
q = db.query(OrderMove).join(OrderMoveItem, OrderMoveItem.move_id == OrderMove.id).filter(OrderMoveItem.item_id == line_id)
if until is not None:
q = q.filter(OrderMove.at <= until)
for m in q.all():
found[m.id] = m
return sorted(found.values(), key=lambda m: (m.at, m.id))
def order_moves(db, order) -> list:
"""The whole order's path: table transfers and merges into it, and the orders merged into it
(their own transfers too), oldest first."""
from models.order import OrderMove
ids, todo, found = set(), [order.id], {}
while todo:
oid = todo.pop()
if oid in ids:
continue
ids.add(oid)
for m in db.query(OrderMove).filter(OrderMove.to_order_id == oid,
OrderMove.kind.in_(("table_transfer", "orders_merged"))).all():
found[m.id] = m
if m.kind == "orders_merged" and m.from_order_id:
todo.append(m.from_order_id)
return sorted(found.values(), key=lambda m: (m.at, m.id))
def _names(db):
from models.table import Table
from models.user import User
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
users = {u.id: (u.nickname or u.full_name or u.username) for u in db.query(User).all()}
return tables, users
def move_out(m, tables, users, item_names=None) -> dict:
return {
"id": m.id, "kind": m.kind, "at": m.at,
"from_order_id": m.from_order_id, "to_order_id": m.to_order_id,
"from_table_id": m.from_table_id, "to_table_id": m.to_table_id,
"from_table": tables.get(m.from_table_id), "to_table": tables.get(m.to_table_id),
"by_id": m.by_user_id, "by": users.get(m.by_user_id),
"approved_by": users.get(m.approved_by_user_id),
"items": [{"item_id": i.item_id, "quantity": i.quantity,
**({"name": item_names.get(i.item_id)} if item_names is not None else {})} for i in m.items],
}
def for_order(db, order) -> dict:
"""GET /api/orders/{id}/moves: {order: [moves of the whole order], items: {line id: [moves]}}
(only lines that moved)."""
tables, users = _names(db)
per_item = {}
for item in order.items:
ms = item_moves(db, item)
if ms:
per_item[str(item.id)] = [move_out(m, tables, users) for m in ms]
return {"order": [move_out(m, tables, users) for m in order_moves(db, order)], "items": per_item}
+124
View File
@@ -0,0 +1,124 @@
"""Prices changed by hand, on the record (owner 2026-11-23, plan step 6F.3).
Who may change a line's price, in three levels like every permission:
- the venue (setting `orders.price_change`): `off` | `before_sending` (only in the cart, before
the line is sent) | `anytime` (also a line already sent or served; the default, as before 6F.3);
- the keys: `ordering.prices.modify` (in the cart; the counter's % discount too) and
`ordering.prices.modify_sent` (a line already sent), role defaults per venue, changed per person;
both may be approved once by a manager's PIN (D-10);
- `orders.price_change_reason`: when on, a by-hand price needs a reason (the venue's quick
reasons, `orders.price_change_reasons`, or typed).
Every change writes one `PriceEventLog` row, `event_type = "manual_price"`: the line, its unit price
before and after, the change, the quantity, who, the approving manager, the stage
(cart | sent | served) and the reason (`waiter_note`), plus an `OrderAuditLog` `PRICE_CHANGED`.
Rows are never deleted; combining lines moves them to the kept line (orders.combine_items).
Who sees them: `ordering.prices.view_changes` (GET /api/pricing/events/order/{id},
GET /api/orders/{id}/items/{item}/price-changes, Reports → Cancellations, discounts and price changes).
"""
from __future__ import annotations
import json
from core.errors import XeniaError
EVENT = "manual_price"
MODES = ("off", "before_sending", "anytime")
STAGES = ("cart", "sent", "served")
REASON_MAX = 200
def _setting(db, key: str, default: str) -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row is not None and row.value not in (None, "") else default
def mode(db) -> str:
v = _setting(db, "orders.price_change", "anytime")
return v if v in MODES else "anytime"
def reason_required(db) -> bool:
return _setting(db, "orders.price_change_reason", "false") == "true"
def quick_reasons(db) -> list[str]:
try:
v = json.loads(_setting(db, "orders.price_change_reasons", "[]"))
except ValueError:
return []
return [str(x).strip() for x in v if isinstance(x, str) and x.strip()] if isinstance(v, list) else []
def clean_reason(reason) -> str | None:
text = " ".join(str(reason or "").split())[:REASON_MAX]
return text or None
def check(db, *, sent: bool, reason=None, by_hand: bool = True) -> str | None:
"""Refuse a price change the venue doesn't allow (order.price_change_off /
order.price_change_sent_off) or one without its reason (order.price_reason_required, only for
a price typed by hand: the counter's % discount has none). Returns the cleaned reason."""
m = mode(db)
if m == "off":
raise XeniaError("order.price_change_off")
if sent and m != "anytime":
raise XeniaError("order.price_change_sent_off")
text = clean_reason(reason)
if by_hand and text is None and reason_required(db):
raise XeniaError("order.price_reason_required")
return text
def stage_of(item) -> str:
"""Where a line is when its price changes: in the cart (being added), sent, or served."""
if item is None or getattr(item, "id", None) is None:
return "cart"
return "served" if getattr(item, "kds_status", None) == "served" else "sent"
def record(db, *, item, before: float, after: float, user_id: int | None, stage: str,
reason: str | None = None, approved_by: int | None = None, audit: bool = True):
"""One manual_price event for `item` (flushed with the caller's commit) and its audit row."""
from models.order import OrderAuditLog
from models.pricing import PriceEventLog
before, after = round(float(before), 2), round(float(after), 2)
if abs(after - before) < 0.005:
return None
ev = PriceEventLog(
order_id=item.order_id, order_item_id=item.id, event_type=EVENT,
price_before=before, price_after=after, delta_amount=round(after - before, 2),
applied_by_user_id=user_id, approved_by_user_id=approved_by, waiter_note=reason,
stage=stage if stage in STAGES else "cart", quantity=item.quantity,
)
db.add(ev)
if audit:
db.add(OrderAuditLog(order_id=item.order_id, event_type="PRICE_CHANGED", waiter_id=user_id,
item_ids=json.dumps([item.id]),
note=f"{before:.2f} → {after:.2f}" + (f" · {reason}" if reason else "")
+ (f" · approved by user {approved_by}" if approved_by else "")))
return ev
def _name(user) -> str | None:
return (user.nickname or user.full_name or user.username) if user is not None else None
def event_out(ev, db) -> dict:
"""One manual_price event for the apps and the reports."""
item = ev.order_item
return {
"id": ev.id, "order_id": ev.order_id, "item_id": ev.order_item_id,
"product_name": item.product_name if item is not None else None,
"before": ev.price_before, "after": ev.price_after, "delta": ev.delta_amount,
"quantity": ev.quantity, "stage": ev.stage, "reason": ev.waiter_note,
"by_id": ev.applied_by_user_id, "by": _name(ev.applied_by),
"approved_by_id": ev.approved_by_user_id, "approved_by": _name(ev.approved_by),
"at": ev.applied_at,
}
def can_view(user) -> bool:
from core.access.check import holds
return holds(user, "ordering.prices.view_changes")
+30 -3
View File
@@ -7,6 +7,10 @@ in every report, on screen, printed and exported.
- A line's **value** = (unit price + its price change) × quantity, then **minus what was refunded**
of it (services/refunds.py: refunds are per line and quantity, so they come off the line, the
product, the category, the table, the hour and the day they belong to).
- **A split bill** (6F.6, services/split_bills.py): the lines it settled (`split`) are sold like
paid lines; its **part lines** are the money for them, never a sale (left out here; the shifts'
drawers, payment methods and tabs count them). A refund of a part comes off the settled lines
by their share of the bill.
- **Fees** (lines the system adds, `system_key` set: the delivery fee) are counted apart: they are
money taken, but not a product sold. `revenue` everywhere is products only; `fees` is beside it;
`takings` = revenue + fees.
@@ -17,7 +21,7 @@ from __future__ import annotations
from dataclasses import dataclass
SOLD = ("active", "paid", "tabbed")
SOLD = ("active", "paid", "tabbed", "split")
def gross(item, quantity: float | None = None) -> float:
@@ -58,17 +62,40 @@ def lines(db, items) -> list[Line]:
"""Sold lines (see the module doc) with their refunds taken off. A line refunded in full
stays (quantity 0, value 0) so its refund is counted; `sold()` leaves it out of lists."""
from services.refunds import refunded_quantities
sold = [i for i in items if i.status in SOLD]
from services.split_bills import is_part
sold = [i for i in items if i.status in SOLD and not is_part(i)]
back = refunded_quantities(db, [i.id for i in sold if i.status == "paid"])
shares = _split_refunds(db, {i.split_bill_id for i in sold if i.status == "split"})
fees = _fee_products(db) if sold else set()
out = []
for i in sold:
r = min(back.get(i.id, 0.0), i.quantity)
if i.status == "split":
r = i.quantity * shares.get(i.split_bill_id, 0.0)
else:
r = min(back.get(i.id, 0.0), i.quantity)
q = max(i.quantity - r, 0.0)
out.append(Line(item=i, quantity=round(q, 3), value=gross(i, q), refunded=gross(i, r), fee=i.product_id in fees))
return out
def _split_refunds(db, bill_ids) -> dict[int, float]:
"""{split_bill_id: the share of the bill refunded} from its parts' refunds (6F.6)."""
from models.order import OrderItem, SplitBill
from services.refunds import refunded_quantities
ids = {b for b in bill_ids if b is not None}
if not ids:
return {}
parts = db.query(OrderItem).filter(OrderItem.split_bill_id.in_(ids), OrderItem.status == "paid").all()
back = refunded_quantities(db, [p.id for p in parts])
if not back:
return {}
totals = {b.id: b.total for b in db.query(SplitBill).filter(SplitBill.id.in_(ids)).all()}
value: dict[int, float] = {}
for p in parts:
value[p.split_bill_id] = value.get(p.split_bill_id, 0.0) + gross(p, min(back.get(p.id, 0.0), p.quantity))
return {b: min(v / totals[b], 1.0) for b, v in value.items() if totals.get(b)}
@dataclass
class Totals:
revenue: float = 0.0 # products, net of refunds
+104
View File
@@ -0,0 +1,104 @@
"""The badges a menu board can put on a product (owner review 5, 2026-11-21): the venue's own list,
kept in the setting `signage.badges` (JSON), edited under Signage → Message & settings. Each badge
has a key (what boards store), its name in Greek and English, its colours (background, text: None =
white or black, whichever reads) and an icon (a name from ICONS, drawn by @xenia/signage). Its
colours are the defaults: a board may give all its badges one colour of its own.
Until the venue changes it, the list is DEFAULTS (the seven badges boards had before)."""
from __future__ import annotations
import json
import re
from typing import Dict, List, Optional
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
SETTING = "signage.badges"
HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$"
KEY = r"^[a-z0-9][a-z0-9_-]{0,23}$"
# the icons a badge can have (lucide names; @xenia/signage BADGE_ICONS draws the same list)
ICONS = (
"sparkles", "chef-hat", "tag", "star", "flame", "sprout", "leaf", "vegan", "wheat", "wheat-off", "fish", "shrimp", "beef",
"drumstick", "egg", "milk", "nut", "carrot", "salad", "pizza", "hamburger", "sandwich", "soup", "croissant",
"ice-cream-cone", "cake-slice", "coffee", "cup-soda", "wine", "beer", "martini", "glass-water", "citrus", "cherry",
"apple", "heart", "award", "thumbs-up", "clock", "percent", "gift", "crown", "zap", "snowflake",
)
DEFAULTS = [
{"key": "new", "names": {"el": "Νέο", "en": "New"}, "colour": "#22c55e", "text_colour": None, "icon": "sparkles"},
{"key": "chef", "names": {"el": "Πρόταση σεφ", "en": "Chef's pick"}, "colour": "#f59e0b", "text_colour": None, "icon": "chef-hat"},
{"key": "offer", "names": {"el": "Προσφορά", "en": "Offer"}, "colour": "#ef4444", "text_colour": None, "icon": "tag"},
{"key": "popular", "names": {"el": "Δημοφιλές", "en": "Popular"}, "colour": "#f472b6", "text_colour": None, "icon": "star"},
{"key": "spicy", "names": {"el": "Καυτερό", "en": "Spicy"}, "colour": "#dc2626", "text_colour": None, "icon": "flame"},
{"key": "vegetarian", "names": {"el": "Χορτοφαγικό", "en": "Vegetarian"}, "colour": "#16a34a", "text_colour": None, "icon": "sprout"},
{"key": "vegan", "names": {"el": "Vegan", "en": "Vegan"}, "colour": "#15803d", "text_colour": None, "icon": "vegan"},
]
class BadgeDef(BaseModel):
model_config = ConfigDict(extra="forbid")
key: str = Field(pattern=KEY)
names: Dict[str, str] = Field(default_factory=dict)
colour: str = Field(default="#f59e0b", pattern=HEX)
text_colour: Optional[str] = Field(default=None, pattern=HEX)
icon: Optional[str] = None
@field_validator("names")
@classmethod
def _names(cls, v):
out = {k: " ".join(str(x).split())[:24] for k, x in v.items() if k in ("el", "en")}
out = {k: x for k, x in out.items() if x}
if not out:
raise ValueError("a badge has a name")
return out
@field_validator("icon")
@classmethod
def _icon(cls, v):
if v is not None and v not in ICONS:
raise ValueError("an icon of the list")
return v
class BadgeList(BaseModel):
model_config = ConfigDict(extra="forbid")
badges: List[BadgeDef] = Field(default_factory=list, max_length=30)
@model_validator(mode="after")
def _unique(self):
keys = [b.key for b in self.badges]
if len(set(keys)) != len(keys):
raise ValueError("each badge has its own key")
return self
def load(db) -> list[dict]:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == SETTING).first()
if row is None or not row.value:
return [dict(b) for b in DEFAULTS]
try:
return BadgeList(badges=json.loads(row.value)).model_dump()["badges"]
except Exception: # noqa: BLE001 — a broken setting falls back to the defaults
return [dict(b) for b in DEFAULTS]
def save(db, badges: list[BadgeDef]) -> list[dict]:
from models.settings import PosSettings
value = json.dumps([b.model_dump() for b in badges], ensure_ascii=False)
row = db.query(PosSettings).filter(PosSettings.key == SETTING).first()
if row is None:
db.add(PosSettings(key=SETTING, value=value))
else:
row.value = value
return [b.model_dump() for b in badges]
def new_key(name: str, taken: set) -> str:
"""A key for a new badge from its name (the editor makes its own; kept for scripts)."""
base = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:20] or "badge"
key, n = base, 2
while key in taken:
key, n = f"{base}-{n}", n + 1
return key
+24 -8
View File
@@ -34,8 +34,11 @@ def _rank(order: list[int]):
return lambda v: (0, pos[v]) if v in pos else (1, 0)
def resolve(db, content: dict, now=None) -> dict:
"""{"groups": [{"category": {id, name} | None, "items": [...]}], "count": n} for a menu slide."""
def resolve(db, content: dict, now=None, keep_hidden: bool = False) -> dict:
"""{"groups": [{"category": {id, name} | None, "items": [...]}], "count": n} for a menu slide.
keep_hidden (the editor's list, 2026-11-21): products hidden from the board (`exclude_ids`) stay
in the list marked `"hidden": true` (greyed there, shown again with a click); `count` and the
TV leave them out."""
from models.product import Category, Product, ProductCategory
from services import media as media_store
from services.pos_cart import unit_prices
@@ -55,7 +58,8 @@ def resolve(db, content: dict, now=None) -> dict:
ids = in_cats | set(content.get("product_ids") or [])
products = q.filter(Product.id.in_(ids)).all() if ids else []
excluded = set(content.get("exclude_ids") or [])
products = [p for p in products if p.id not in excluded]
if not keep_hidden:
products = [p for p in products if p.id not in excluded]
point = content.get("sales_point")
if point:
@@ -76,29 +80,41 @@ def resolve(db, content: dict, now=None) -> dict:
return (prod_rank(p.id), member_order.get((p.primary_category_id, p.id), p.sort_order or 0), (p.name or "").lower())
prices = dict(zip([p.id for p in products], unit_prices(db, products, point, now=now))) if point and products else {}
badges = {int(k): v for k, v in (content.get("badges") or {}).items() if str(k).isdigit()}
badges = {int(k): ([v] if isinstance(v, str) else list(v or [])) for k, v in (content.get("badges") or {}).items() if str(k).isdigit()}
lang = content.get("language") # 6.4: the board's language; None = the base texts
def text(row, base, field):
return menu_languages.texts(base, menu_languages.of(row), field).get(lang, base) if lang else base
own = content.get("names") or {} # this board's own names (2026-11-21)
own_cats = content.get("category_names") or {}
def named(row, base, mine):
"""(the name shown, the catalogue's name when the board has its own)"""
shown = text(row, base, "name")
return (mine, shown) if mine else (shown, None)
def item(p):
image = media_store.image_of(p.media) if content.get("show_photos") else None
return {"id": p.id, "name": text(p, p.digital_name or p.name, "name"),
name, original = named(p, p.digital_name or p.name, own.get(str(p.id)))
return {"id": p.id, "name": name, **({"original": original} if original and keep_hidden else {}),
"description": text(p, p.digital_description or p.description or None, "description") if content.get("show_descriptions") else None,
"price": round(prices[p.id], 2) if p.id in prices else None,
"available": bool(p.is_available), "image": image["card"] if image else None,
"badge": badges.get(p.id)}
"badges": badges.get(p.id) or [], **({"hidden": True} if p.id in excluded else {})}
if content.get("group_by_category", True):
groups: dict = {}
for p in products:
groups.setdefault(p.primary_category_id, []).append(p)
out = [{"category": {"id": cid, "name": text(by_id[cid], by_id[cid].name, "name")} if cid in by_id else None,
def cat(cid):
name, original = named(by_id[cid], by_id[cid].name, own_cats.get(str(cid)))
return {"id": cid, "name": name, **({"original": original} if original and keep_hidden else {})}
out = [{"category": cat(cid) if cid in by_id else None,
"items": [item(p) for p in sorted(ps, key=prod_key)]}
for cid, ps in sorted(groups.items(), key=lambda kv: cat_key(kv[0]))]
else:
ordered = sorted(products, key=lambda p: (prod_rank(p.id), cat_key(p.primary_category_id), prod_key(p)))
out = [{"category": None, "items": [item(p) for p in ordered]}] if ordered else []
return {"groups": out, "count": len(products)}
return {"groups": out, "count": len([p for p in products if p.id not in excluded])}
+228
View File
@@ -0,0 +1,228 @@
"""Split a bill by amount (owner 2026-11-23, plan 6F.6). One rule for every app:
- The chosen unpaid lines are **settled** at once into a split bill: status `split` (sold, settled by
the bill; `paid_at` / `paid_by` say when and who split, no shift, no payment method), so no
drawer, payment method or person is charged for them.
- `parts` **part lines** appear on the order: the system product `split_part`, named "Split bill
1/3", one each, already printed and served (the kitchen never sees them). They are paid like any
line (cash, card, on a tab, at different times, by different people): they are the money.
- Counting (services/sales.py): the settled lines are the sales (products, categories, costs);
parts are settlement lines, never sales, but money taken (shifts' drawers, payment methods,
tabs, the day's takings), so nothing is counted twice. A refund of a part comes off the settled
lines by their share.
- Locks: settled lines are no longer `active`, so cancelling, moving, combining, re-pricing and
splitting them is refused everywhere; parts can't be moved, re-priced, combined or cancelled one
by one (undo the split instead).
- Undo while no part is paid or on a tab (Q-2): parts cancelled ("split undone"), lines back to
unpaid. Refused once any payment was taken.
- Fiscal (Greece, Q-3): a split is whole lines, so the receipt is the settled lines themselves, as
if paid normally: issued once, when the **last part is paid**, with each method's amount as the
receipt's payments (`receipts_due`). A part on a tab: no receipt from the split (like any line
on a tab) — open point for the accountant (plan 6F.6).
Venue setting `payments.split_amount` (levels include the ones before, Q-1): off | two_equal |
two_custom | multiple_equal (2…`payments.split_max_parts` equal parts). Key
`ordering.payments.split_amount`.
"""
from __future__ import annotations
import json
from core.errors import XeniaError
LEVELS = ("off", "two_equal", "two_custom", "multiple_equal")
PART_KEY = "split_part"
def _setting(db, key: str, default: str) -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row is not None and row.value not in (None, "") else default
def level(db) -> str:
v = _setting(db, "payments.split_amount", "off")
return v if v in LEVELS else "off"
def max_parts(db) -> int:
try:
n = int(_setting(db, "payments.split_max_parts", "10"))
except ValueError:
n = 10
return max(2, min(50, n))
def allowed(lvl: str, mode: str, parts: int, most: int) -> bool:
"""Whether the venue's level allows this split (each level includes the ones before)."""
rank = LEVELS.index(lvl) if lvl in LEVELS else 0
if mode == "custom":
return parts == 2 and rank >= LEVELS.index("two_custom")
if parts == 2:
return rank >= LEVELS.index("two_equal")
return rank >= LEVELS.index("multiple_equal") and 2 < parts <= most
def amounts(total: float, mode: str, parts: int, first: float | None = None) -> list[float]:
"""Each part, to the cent. Equal: the remainder goes on the last part (10.00 / 3 = 3.33 + 3.33
+ 3.34). Custom (two parts): `first` is part 1, part 2 the rest."""
cents = round(total * 100)
if mode == "custom":
a = round((first or 0) * 100)
if not 0 < a < cents:
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
return [a / 100, (cents - a) / 100]
base = cents // parts
return [base / 100] * (parts - 1) + [(cents - base * (parts - 1)) / 100]
def is_part(item) -> bool:
"""A split bill's part line (money for the settled lines), not a sale."""
return getattr(item, "split_bill_id", None) is not None and item.status != "split"
def counts_as_sale(item, statuses=("active", "paid")) -> bool:
"""For the older reports that pick lines by status: a settled line counts, a part never."""
return item.status == "split" or (item.status in statuses and not is_part(item))
def sold_filter(statuses=("active", "paid")):
"""The same as SQL (OrderItem): settled lines, or lines in `statuses` that aren't parts."""
from sqlalchemy import and_, or_
from models.order import OrderItem
return or_(OrderItem.status == "split", and_(OrderItem.status.in_(statuses), OrderItem.split_bill_id.is_(None)))
def refuse_parts(items) -> None:
if any(is_part(i) for i in items):
raise XeniaError("split.part_locked")
def live_bills(db, order_id: int) -> list:
from models.order import SplitBill
return db.query(SplitBill).filter(SplitBill.order_id == order_id, SplitBill.undone_at.is_(None)).order_by(SplitBill.id).all()
def has_unpaid_parts(db, order_id: int) -> bool:
from models.order import OrderItem
return db.query(OrderItem).filter(OrderItem.order_id == order_id, OrderItem.split_bill_id.isnot(None),
OrderItem.status.in_(("active", "ready"))).first() is not None
def create(db, order, items, *, mode: str, parts: int, first: float | None, user) -> object:
"""Settle `items` (unpaid lines of `order`) into a split bill with `parts` part lines.
The caller checked the key; this checks the venue's level, the lines and fiscal."""
from core.i18n import t, venue_language
from core.timeutil import utcnow
from models.order import OrderItem, SplitBill
from services import system_products
from services.sales import gross
if mode not in ("equal", "custom"):
raise XeniaError("validation.choice", field="mode", value=mode)
if not allowed(level(db), mode, parts, max_parts(db)):
raise XeniaError("split.not_allowed")
if not items or any(i.order_id != order.id or i.status not in ("active", "ready") for i in items):
raise XeniaError("split.lines_changed")
refuse_parts(items)
total = round(sum(gross(i) for i in items), 2)
if total < 0.01 * parts:
raise XeniaError("split.amount_invalid", total=f"{total:.2f}")
split = amounts(total, mode, parts, first)
from services.fiscal import is_fiscal_enabled, validate_items_for_fiscal
if is_fiscal_enabled(db):
missing = validate_items_for_fiscal(items, db)
if missing:
raise XeniaError("pos.fiscal_vat_missing", names=", ".join(missing))
now = utcnow()
bill = SplitBill(order_id=order.id, total=total, mode=mode, parts=parts, amounts=json.dumps(split),
created_by=user.id, created_at=now, business_day_id=order.business_day_id)
db.add(bill)
db.flush()
for i in items:
i.status = "split"
i.split_bill_id = bill.id
i.paid_at = now
i.paid_by = user.id
i.payment_method = None
i.paid_in_shift_id = None
product = system_products.get(db, PART_KEY)
lang = venue_language()
for n, amount in enumerate(split, start=1):
db.add(OrderItem(order_id=order.id, product_id=product.id, added_by=user.id, quantity=1, unit_price=amount,
price_adjustment=0.0, status="active", printed=True, kds_status="served", split_bill_id=bill.id,
product_name=t("split.part_name", lang, n=n, of=parts), source=items[0].source))
db.flush()
return bill
def undo(db, order, bill, user) -> list[int]:
"""Undo a split while no part was paid or put on a tab (Q-2). Returns the lines given back."""
from core.timeutil import utcnow
from models.order import OrderItem
if bill.undone_at is not None or bill.order_id != order.id:
raise XeniaError("split.not_found")
rows = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id).all()
parts = [i for i in rows if i.status != "split"]
if any(p.status not in ("active", "ready", "cancelled") for p in parts):
raise XeniaError("split.paid_already")
now = utcnow()
for p in parts:
if p.status != "cancelled":
p.status = "cancelled"
p.cancelled_at = now
p.cancelled_by = user.id
p.cancel_reason = "split undone"
back = []
for i in rows:
if i.status == "split":
i.status = "active"
i.split_bill_id = None
i.paid_at = None
i.paid_by = None
back.append(i.id)
bill.undone_at = now
bill.undone_by = user.id
db.flush()
return back
def receipts_due(db, paid_items) -> list[dict]:
"""After parts were paid: the split bills whose last part is now paid get their fiscal receipt
(marked issued here). [{"bill", "lines", "payments": [{"method", "amount"}]}]."""
from core.timeutil import utcnow
from models.order import OrderItem, SplitBill
ids = {i.split_bill_id for i in paid_items if is_part(i)}
out = []
for bill in db.query(SplitBill).filter(SplitBill.id.in_(ids)).all() if ids else []:
if bill.undone_at is not None or bill.receipt_issued_at is not None:
continue
rows = db.query(OrderItem).filter(OrderItem.split_bill_id == bill.id).order_by(OrderItem.id).all()
parts = [i for i in rows if i.status not in ("split", "cancelled")]
if not parts or any(p.status != "paid" for p in parts):
continue # unpaid, or on a tab: no receipt from the split (open point, plan 6F.6)
by_method: dict[str, float] = {}
for p in parts:
m = p.payment_method or "cash"
by_method[m] = round(by_method.get(m, 0.0) + (p.unit_price or 0.0) * p.quantity, 2)
bill.receipt_issued_at = utcnow()
out.append({"bill": bill, "lines": [i for i in rows if i.status == "split"],
"payments": [{"method": m, "amount": a} for m, a in by_method.items()]})
return out
def bill_out(bill, rows) -> dict:
"""What the apps show: the bill, its settled lines and its parts (with how each was paid)."""
parts = [i for i in rows if i.split_bill_id == bill.id and i.status != "split" and i.status != "cancelled"]
return {
"id": bill.id, "total": bill.total, "mode": bill.mode, "parts": bill.parts,
"amounts": json.loads(bill.amounts or "[]"),
"created_by": bill.created_by,
"created_at": bill.created_at.isoformat() + "Z" if bill.created_at and bill.created_at.tzinfo is None else (bill.created_at.isoformat() if bill.created_at else None),
"line_ids": [i.id for i in rows if i.split_bill_id == bill.id and i.status == "split"],
"part_ids": [p.id for p in parts],
"paid": round(sum((p.unit_price or 0.0) * p.quantity for p in parts if p.status == "paid"), 2),
"can_undo": all(p.status in ("active", "ready") for p in parts),
"receipt_issued": bill.receipt_issued_at is not None,
}
+2 -1
View File
@@ -21,7 +21,8 @@ from __future__ import annotations
from collections import Counter
DELIVERY_FEE = "delivery_fee"
KEYS = (DELIVERY_FEE,)
SPLIT_PART = "split_part" # a split bill's part line (6F.6, services/split_bills.py)
KEYS = (DELIVERY_FEE, SPLIT_PART)
def _usual_vat_group(db):
+29 -9
View File
@@ -6,7 +6,10 @@ editor from a town search). `weather_worker` (a signage module worker) asks Open
key) every 30 minutes while it has internet and keeps the last answer in memory. A forecast older
than 3 hours counts as none: the screens get `weather: null` and hide the widget.
current() → {"place", "temperature", "code", "is_day", "days": [{date, max, min, code}], "units", "at"} | None
current() → {"place", "temperature", "code", "is_day", "feels_like", "humidity", "wind", "wind_dir",
"precipitation", "days": [{date, max, min, code, rain, wind, uv, sunrise, sunset}] (7),
"hours": [{time, temp, code, rain, is_day}] (the next 24), "units", "wind_unit", "at"} | None
(6R.18: everything the detailed weather widget can show; older answers lack some keys)
search(name) → places for the editor's search (name, country, region, latitude, longitude)
"""
from __future__ import annotations
@@ -68,9 +71,12 @@ def _key(where: dict) -> tuple:
async def fetch(where: dict, client: httpx.AsyncClient | None = None) -> dict:
params = {"latitude": where["latitude"], "longitude": where["longitude"], "timezone": "auto", "forecast_days": 3,
"current": "temperature_2m,weather_code,is_day", "daily": "temperature_2m_max,temperature_2m_min,weather_code",
"temperature_unit": where["units"]}
imperial = where["units"] == "fahrenheit"
params = {"latitude": where["latitude"], "longitude": where["longitude"], "timezone": "auto", "forecast_days": 7,
"current": "temperature_2m,weather_code,is_day,apparent_temperature,relative_humidity_2m,wind_speed_10m,wind_direction_10m,precipitation",
"daily": "temperature_2m_max,temperature_2m_min,weather_code,precipitation_probability_max,wind_speed_10m_max,uv_index_max,sunrise,sunset",
"hourly": "temperature_2m,weather_code,precipitation_probability,is_day",
"temperature_unit": where["units"], "wind_speed_unit": "mph" if imperial else "kmh"}
own = client is None
client = client or httpx.AsyncClient(timeout=TIMEOUT_S)
try:
@@ -80,12 +86,26 @@ async def fetch(where: dict, client: httpx.AsyncClient | None = None) -> dict:
finally:
if own:
await client.aclose()
cur, daily = j.get("current") or {}, j.get("daily") or {}
days = [{"date": d, "max": mx, "min": mn, "code": c}
for d, mx, mn, c in zip(daily.get("time", []), daily.get("temperature_2m_max", []),
daily.get("temperature_2m_min", []), daily.get("weather_code", []))]
cur, daily, hourly = j.get("current") or {}, j.get("daily") or {}, j.get("hourly") or {}
col = lambda src, key, n: (src.get(key) or [None] * n)[:n] + [None] * max(0, n - len(src.get(key) or [])) # noqa: E731
n = len(daily.get("time", []))
hm = lambda v: v[11:16] if isinstance(v, str) and len(v) >= 16 else None # noqa: E731 "2026-11-17T07:12" → "07:12"
days = [{"date": d, "max": mx, "min": mn, "code": c, "rain": rp, "wind": wm, "uv": uv, "sunrise": hm(sr), "sunset": hm(ss)}
for d, mx, mn, c, rp, wm, uv, sr, ss in zip(daily.get("time", []), col(daily, "temperature_2m_max", n), col(daily, "temperature_2m_min", n),
col(daily, "weather_code", n), col(daily, "precipitation_probability_max", n),
col(daily, "wind_speed_10m_max", n), col(daily, "uv_index_max", n),
col(daily, "sunrise", n), col(daily, "sunset", n))]
# the next 24 hours from now (the place's own time: Open-Meteo answers in it)
times = hourly.get("time", [])
start = next((i for i, x in enumerate(times) if x >= (cur.get("time") or "")[:13] + ":00"), 0)
m = len(times)
hours = [{"time": hm(t), "temp": tp, "code": c, "rain": rp, "is_day": bool(dy if dy is not None else 1)}
for t, tp, c, rp, dy in list(zip(times, col(hourly, "temperature_2m", m), col(hourly, "weather_code", m),
col(hourly, "precipitation_probability", m), col(hourly, "is_day", m)))[start:start + 24]]
return {"place": where["name"], "temperature": cur.get("temperature_2m"), "code": cur.get("weather_code"),
"is_day": bool(cur.get("is_day", 1)), "days": days, "units": where["units"], "at": cur.get("time")}
"is_day": bool(cur.get("is_day", 1)), "feels_like": cur.get("apparent_temperature"), "humidity": cur.get("relative_humidity_2m"),
"wind": cur.get("wind_speed_10m"), "wind_dir": cur.get("wind_direction_10m"), "precipitation": cur.get("precipitation"),
"days": days, "hours": hours, "units": where["units"], "wind_unit": "mph" if imperial else "km/h", "at": cur.get("time")}
async def refresh(db, client: httpx.AsyncClient | None = None) -> bool:
+118
View File
@@ -0,0 +1,118 @@
"""The venue's identity (6R.14): name, slogan, colours, logos, Wi-Fi and contact saved together,
logos protected in the media library, signage screens told and given it with their venue."""
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers)
from tests.test_signage import screens, sent # noqa: F401 (fixtures)
def test_empty_at_first(client, owner_h):
r = client.get("/api/identity", headers=owner_h)
assert r.status_code == 200
j = r.json()
assert j["colours"] == [] and j["logos"] == {"main": None, "light": None, "dark": None, "icon": None}
assert j["wifi"]["security"] == "WPA" and j["contact"]["phone"] is None
def test_saved_together_and_shown_to_the_screens(client, owner_h, screens, sent, media_dir):
logo = up(client, owner_h, jpeg(400, 200)).json()
body = {"name": " Taverna Xenia ", "slogan": "Since 1987", "colours": [{"name": "Main", "colour": "#1E3A8A"}, {"name": "Olive", "colour": "#556b2f80"}],
"logos": {"main": logo["id"]}, "wifi": {"ssid": "Xenia Guests", "password": "kalimera 2026", "security": "WPA"},
"contact": {"phone": " 2310 123456 ", "instagram": "@xenia"}}
sent.clear()
r = client.put("/api/identity", headers=owner_h, json=body)
assert r.status_code == 200, r.text
j = r.json()
assert j["name"] == "Taverna Xenia" and j["slogan"] == "Since 1987"
assert j["colours"] == [{"name": "Main", "colour": "#1e3a8a"}, {"name": "Olive", "colour": "#556b2f80"}]
assert j["logos"]["main"]["id"] == logo["id"] and j["logos"]["main"]["card"]
assert j["wifi"]["password"] == "kalimera 2026" and j["contact"]["phone"] == "2310 123456"
assert ("signage.changed", sorted([screens[1]["id"], screens[2]["id"]])) in sent
# the venue name is the one every app already reads
assert client.get("/api/settings/", headers=owner_h).json()["venue.name"]["value"] == "Taverna Xenia"
# the screens get it with their venue
venue = client.get("/api/signage/screen", headers=screens[1]["h"]).json()["venue"]
assert venue["name"] == "Taverna Xenia" and venue["identity"]["wifi"]["ssid"] == "Xenia Guests"
assert venue["identity"]["logos"]["main"]["id"] == logo["id"]
# a logo in use can't be deleted
assert err(client.delete(f"/api/media/{logo['id']}", headers=owner_h)) == "media.in_use"
def test_checked(client, owner_h):
assert client.put("/api/identity", headers=owner_h, json={"colours": [{"name": "", "colour": "#000000"}]}).status_code == 422
assert client.put("/api/identity", headers=owner_h, json={"colours": [{"name": "x", "colour": "red"}]}).status_code == 422
assert client.put("/api/identity", headers=owner_h, json={"wifi": {"security": "WPA9"}}).status_code == 422
assert client.put("/api/identity", headers=owner_h, json={"nope": 1}).status_code == 422
assert err(client.put("/api/identity", headers=owner_h, json={"logos": {"main": 99999}})) == "media.not_found"
too_many = [{"name": f"c{i}", "colour": "#000000"} for i in range(13)]
assert client.put("/api/identity", headers=owner_h, json={"colours": too_many}).status_code == 422
def test_opening_hours(client, owner_h, screens, sent):
assert client.get("/api/identity/hours", headers=owner_h).json() == {"days": [[]] * 7, "note": None, "set": False}
days = [[{"from": "18:00", "to": "23:00"}, {"from": "12:00", "to": "15:00"}]] * 5 + [[{"from": "12:00", "to": "01:00"}], []]
sent.clear()
r = client.put("/api/identity/hours", headers=owner_h, json={"days": days, "note": " Closed on holidays "})
assert r.status_code == 200, r.text
j = r.json()
assert j["set"] is True and j["days"][0] == [{"from": "12:00", "to": "15:00"}, {"from": "18:00", "to": "23:00"}]
assert j["days"][6] == [] and j["note"] == "Closed on holidays"
assert ("signage.changed", sorted([screens[1]["id"], screens[2]["id"]])) in sent
assert client.get("/api/signage/screen", headers=screens[1]["h"]).json()["venue"]["hours"]["days"][5] == [{"from": "12:00", "to": "01:00"}]
assert client.put("/api/identity/hours", headers=owner_h, json={"days": [[]] * 6}).status_code == 422
assert client.put("/api/identity/hours", headers=owner_h, json={"days": [[{"from": "25:00", "to": "01:00"}]] + [[]] * 6}).status_code == 422
def test_new_widgets_are_typed(client, owner_h):
from tests.test_signage import playlist, slide
p = playlist(client, owner_h)
widgets = [
{"kind": "shape", "position": "custom", "box": {"x": 10, "y": 10, "w": 20, "h": 20}, "shape": "star", "shape_sides": 5, "fill": "#ff0000", "fill_to": "#0000ff"},
{"kind": "ticker", "position": "bottom-bar", "text": "Fresh fish today " * 10, "ticker_speed": 7},
{"kind": "countdown", "countdown_to": "17:00", "countdown_start": "before", "countdown_before": 120, "countdown_done": "Happy hour!"},
{"kind": "countdown", "countdown_to": "2026-12-31T23:59"},
{"kind": "hours", "hours_style": "today"},
{"kind": "wifi", "wifi_qr": False},
{"kind": "contact", "contact_fields": ["phone", "instagram"]},
]
s = slide(client, owner_h, p["id"], "blank", content={"widgets": widgets})
got = s["content"]["widgets"]
assert [w["kind"] for w in got] == [w["kind"] for w in widgets]
assert got[0]["shape"] == "star" and got[2]["countdown_before"] == 120 and got[6]["contact_fields"] == ["phone", "instagram"]
bad = client.post(f"/api/signage/playlists/{p['id']}/slides", headers=owner_h,
json={"kind": "blank", "content": {"widgets": [{"kind": "countdown", "countdown_to": "5pm"}]}})
assert err(bad) == "signage.content_invalid"
bad = client.post(f"/api/signage/playlists/{p['id']}/slides", headers=owner_h,
json={"kind": "blank", "content": {"widgets": [{"kind": "contact", "contact_fields": ["fax"]}]}})
assert err(bad) == "signage.content_invalid"
def test_reviews_typed_in_by_hand(client, owner_h, screens, sent):
body = {"reviews": [{"name": " Maria K. ", "stars": 5, "text": "Best octopus on the island", "date": "2026-11-01", "source": "Google"},
{"name": "John", "stars": 3, "text": "OK"}]}
sent.clear()
r = client.put("/api/signage/reviews", headers=owner_h, json=body)
assert r.status_code == 200, r.text
got = r.json()["reviews"]
assert got[0]["name"] == "Maria K." and got[0]["text"] == "Best octopus on the island" and got[1]["date"] is None
assert ("signage.changed", sorted([screens[1]["id"], screens[2]["id"]])) in sent
assert client.get("/api/signage/screen", headers=screens[1]["h"]).json()["venue"]["reviews"][0]["stars"] == 5
assert client.get("/api/signage/reviews", headers=owner_h).json()["reviews"][1]["name"] == "John"
assert client.put("/api/signage/reviews", headers=owner_h, json={"reviews": [{"name": "x", "stars": 6, "text": "y"}]}).status_code == 422
assert client.put("/api/signage/reviews", headers=owner_h, json={"reviews": [{"name": "x", "stars": 5, "text": ""}]}).status_code == 422
def test_more_settings_of_widgets(client, owner_h, media_dir):
from tests.test_signage import playlist, slide
logo = up(client, owner_h, jpeg(200, 200)).json()
p = playlist(client, owner_h)
w = {"kind": "date", "opacity": 60, "rotation": -15, "shadow": "glow", "border_width": 4, "border_colour": "#ff0000", "border_radius": 20,
"animation": "pop", "animation_delay": 5, "weight": 300, "highlight": "#ffff0080", "text_effect": "typewriter",
"date_format": "numeric", "date_separator": "."}
q = {"kind": "qr", "media_id": logo["id"], "clock_format": "12", "clock_blink": True}
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [w, q]})
got = s["content"]["widgets"][0]
assert {k: got[k] for k in w} == w
assert s["content"]["widgets"][1]["media_id"] == logo["id"]
for bad in ({"kind": "date", "opacity": 5}, {"kind": "date", "animation": "spin"}, {"kind": "date", "date_separator": "|"}, {"kind": "clock", "weight": 1000}):
r = client.post(f"/api/signage/playlists/{p['id']}/slides", headers=owner_h, json={"kind": "blank", "content": {"widgets": [bad]}})
assert err(r) == "signage.content_invalid", bad
+44
View File
@@ -0,0 +1,44 @@
"""Media folders (6R.16): made, renamed, deleted (files stay), files moved and uploaded into one,
the list filtered; a gallery widget showing a folder gets its files (and the screen their addresses)."""
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers)
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
def test_folders(client, owner_h, media_dir):
f = client.post("/api/media/folders", headers=owner_h, json={"name": " Summer menu "}).json()
assert f["name"] == "Summer menu" and f["count"] == 0
a = up(client, owner_h, jpeg(300, 200)).json()
b = up(client, owner_h, jpeg(300, 200, (9, 9, 9))).json()
assert client.post("/api/media/move", headers=owner_h, json={"ids": [a["id"], b["id"]], "folder_id": f["id"]}).json()["moved"] == 2
got = client.get("/api/media/folders", headers=owner_h).json()
assert got["folders"] == [{"id": f["id"], "name": "Summer menu", "count": 2}]
listed = client.get(f"/api/media?folder={f['id']}", headers=owner_h).json()
assert {i["id"] for i in listed["items"]} == {a["id"], b["id"]} and listed["items"][0]["folder_id"] == f["id"]
assert all(i["folder_id"] is None for i in client.get("/api/media?folder=none", headers=owner_h).json()["items"])
r = client.patch(f"/api/media/{a['id']}", headers=owner_h, json={"folder_id": None})
assert r.status_code == 200 and r.json()["folder_id"] is None and r.json()["name"] == a["name"]
assert client.patch(f"/api/media/folders/{f['id']}", headers=owner_h, json={"name": "Winter"}).json()["name"] == "Winter"
# an upload straight into a folder
c = client.post("/api/media", headers=owner_h, files={"file": ("x.jpg", jpeg(100, 100, (1, 2, 3)), "image/jpeg")}, data={"folder_id": str(f["id"])}).json()
assert c["folder_id"] == f["id"]
assert err(client.post("/api/media/move", headers=owner_h, json={"ids": [a["id"]], "folder_id": 9999})) == "media.folder_unknown"
assert client.delete(f"/api/media/folders/{f['id']}", headers=owner_h).status_code == 204
assert client.get(f"/api/media/{b['id']}", headers=owner_h).json()["folder_id"] is None # the file stays
def test_a_gallery_of_a_folder(client, owner_h, screens, media_dir):
f = client.post("/api/media/folders", headers=owner_h, json={"name": "Dishes"}).json()
pics = [up(client, owner_h, jpeg(400, 300, (i * 40, 10, 10))).json() for i in range(3)]
client.post("/api/media/move", headers=owner_h, json={"ids": [p["id"] for p in pics], "folder_id": f["id"]})
p = playlist(client, owner_h)
slide(client, owner_h, p["id"], "blank", content={"widgets": [
{"kind": "gallery", "position": "custom", "box": {"x": 0, "y": 0, "w": 50, "h": 50}, "gallery_source": "folder", "gallery_folder": f["id"], "gallery_seconds": 4},
{"kind": "gallery", "position": "top-left", "media_ids": [pics[0]["id"]], "gallery_transition": "slide"}]})
client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"playlist_id": p["id"]})
pl = client.get("/api/signage/screen", headers=screens[1]["h"]).json()["playlist"]
s = pl["slides"][0]
assert s["extras"]["0"]["gallery"] == [x["id"] for x in pics]
assert all(str(x["id"]) in pl["media"] for x in pics)
# the pictures in a gallery's own list are protected
assert err(client.delete(f"/api/media/{pics[0]['id']}", headers=owner_h)) == "media.in_use"
+140
View File
@@ -0,0 +1,140 @@
"""Moves on the record (owner 2026-11-23, plan 6F.4, services/moves.py).
A table transfer, lines moved to another order and two orders merged each leave one move with its
lines; a line's path survives being moved three times, being split (the part carries the moves made
before the split, not after) and being combined; the order shows where it came from; Reports →
Moves lists them.
"""
import pytest
from tests.test_waiter_keys import shop # noqa: F401 (fixture)
@pytest.fixture(autouse=True)
def _no_printing(monkeypatch):
import routers.orders as orders
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: [])
@pytest.fixture
def floor(db, shop):
"""Four free tables and the shop's waiter's order put on the first."""
from models.table import Table, TableGroup
g = TableGroup(name="Hall")
db.add(g)
db.flush()
ts = [Table(number=n, group_id=g.id, is_active=True) for n in (1, 2, 3, 4)]
db.add_all(ts)
db.flush()
shop["order"].table_id = ts[0].id
shop["order"].status = "open"
for i in shop["items"]:
i.status = "active"
db.commit()
return ts
def new_order(db, shop, table, n=1):
from models.order import Order, OrderItem
o = Order(opened_by=shop["waiter"].id, table_id=table.id, status="open")
db.add(o)
db.flush()
items = [OrderItem(order_id=o.id, product_id=shop["items"][0].product_id, added_by=shop["waiter"].id, quantity=1, unit_price=4.0)
for _ in range(n)]
db.add_all(items)
db.commit()
return o, items
def test_a_transfer_is_one_move_with_its_lines(client, db, shop, floor):
o = shop["order"]
r = client.post(f"/api/orders/{o.id}/transfer", headers=shop["h"], json={"target_table_id": floor[1].id})
assert r.status_code == 200, r.text
got = client.get(f"/api/orders/{o.id}/moves", headers=shop["h"]).json()
[m] = got["order"]
assert m["kind"] == "table_transfer" and (m["from_table_id"], m["to_table_id"]) == (floor[0].id, floor[1].id)
assert m["from_table"] == "T1" and m["to_table"] == "T2" and m["by_id"] == shop["waiter"].id
assert {i["item_id"] for i in m["items"]} == {i.id for i in shop["items"]}
assert set(got["items"]) == {str(i.id) for i in shop["items"]}
def test_a_line_moved_three_times_shows_every_step(client, db, shop, floor):
o1 = shop["order"]
o2, _ = new_order(db, shop, floor[1])
o3, _ = new_order(db, shop, floor[2])
line = shop["items"][0]
for src, dst in ((o1, o2), (o2, o3), (o3, o1)):
r = client.post(f"/api/orders/{src.id}/move-items", headers=shop["h"], json={"item_ids": [line.id], "target_order_id": dst.id})
assert r.status_code == 200, r.text
path = client.get(f"/api/orders/{o1.id}/moves", headers=shop["h"]).json()["items"][str(line.id)]
assert [(m["from_table"], m["to_table"]) for m in path] == [("T1", "T2"), ("T2", "T3"), ("T3", "T1")]
assert all(m["kind"] == "items_moved" for m in path)
def test_a_split_part_keeps_the_moves_before_the_split_only(client, db, shop, floor):
o1 = shop["order"]
o2, _ = new_order(db, shop, floor[1])
o3, _ = new_order(db, shop, floor[2])
line = shop["items"][0]
line.quantity = 3
line.price_adjustment = -0.5
line.kds_status = "served"
db.commit()
client.post(f"/api/orders/{o1.id}/move-items", headers=shop["h"], json={"item_ids": [line.id], "target_order_id": o2.id})
r = client.post(f"/api/orders/{o2.id}/items/{line.id}/split", headers=shop["h"], json={"quantity": 1})
assert r.status_code == 200, r.text
part = [x for x in r.json() if x["id"] != line.id][0]
assert part["split_from_id"] == line.id
# the part keeps what the line was (its price change, the kitchen state)
from models.order import OrderItem
db.expire_all()
p = db.get(OrderItem, part["id"])
assert p.price_adjustment == -0.5 and p.kds_status == "served"
# the original moves on; the part stays
client.post(f"/api/orders/{o2.id}/move-items", headers=shop["h"], json={"item_ids": [line.id], "target_order_id": o3.id})
part_path = client.get(f"/api/orders/{o2.id}/moves", headers=shop["h"]).json()["items"][str(part["id"])]
assert [(m["from_table"], m["to_table"]) for m in part_path] == [("T1", "T2")]
line_path = client.get(f"/api/orders/{o3.id}/moves", headers=shop["h"]).json()["items"][str(line.id)]
assert [(m["from_table"], m["to_table"]) for m in line_path] == [("T1", "T2"), ("T2", "T3")]
def test_a_merge_brings_the_other_orders_path(client, db, shop, floor):
o1 = shop["order"]
o2, lines2 = new_order(db, shop, floor[1])
client.post(f"/api/orders/{o2.id}/transfer", headers=shop["h"], json={"target_table_id": floor[3].id})
r = client.post(f"/api/orders/{o2.id}/merge", headers=shop["h"], json={"target_order_id": o1.id})
assert r.status_code == 200, r.text
got = client.get(f"/api/orders/{o1.id}/moves", headers=shop["h"]).json()
assert [m["kind"] for m in got["order"]] == ["table_transfer", "orders_merged"]
merged = got["order"][1]
assert (merged["from_order_id"], merged["to_order_id"], merged["from_table"], merged["to_table"]) == (o2.id, o1.id, "T4", "T1")
assert [m["kind"] for m in got["items"][str(lines2[0].id)]] == ["table_transfer", "orders_merged"]
def test_combining_lines_keeps_their_moves(client, db, shop, floor):
o1 = shop["order"]
o2, _ = new_order(db, shop, floor[1])
a, b = shop["items"][0], shop["items"][1]
client.post(f"/api/orders/{o1.id}/move-items", headers=shop["h"], json={"item_ids": [a.id, b.id], "target_order_id": o2.id})
r = client.post(f"/api/orders/{o2.id}/items/combine", headers=shop["h"], json={"item_ids": [a.id, b.id]})
assert r.status_code == 200, r.text
from models.order import OrderMoveItem
db.expire_all()
[mi] = db.query(OrderMoveItem).all()
assert mi.item_id == a.id and mi.quantity == 2
def test_the_moves_report(client, db, shop, floor, make_user, login):
o1 = shop["order"]
o2, _ = new_order(db, shop, floor[1])
client.post(f"/api/orders/{o1.id}/move-items", headers=shop["h"], json={"item_ids": [shop["items"][0].id], "target_order_id": o2.id})
client.post(f"/api/orders/{o2.id}/transfer", headers=shop["h"], json={"target_table_id": floor[2].id})
boss = login(make_user(role="owner"))
rep = client.get("/api/reports/moves", headers=boss).json()
assert rep["count"] == 2 and rep["by_kind"] == {"items_moved": 1, "table_transfer": 1}
moved = next(m for m in rep["moves"] if m["kind"] == "items_moved")
assert moved["value"] == 4.0 and moved["items"][0]["name"] and rep["by_person"][0]["count"] == 2
assert client.get(f"/api/reports/moves?table_id={floor[2].id}", headers=boss).json()["count"] == 1
assert client.get("/api/reports/moves?kind=table_transfer", headers=boss).json()["count"] == 1
csv = client.get("/api/reports/moves/export", headers=boss)
assert csv.status_code == 200 and "items_moved" in csv.text
+123
View File
@@ -0,0 +1,123 @@
"""One more, and a sent line's quantity (owner 2026-11-23, plan 6F.5).
- POST /api/orders/{id}/items/{item}/again: a new line like the old one, priced now, printed as new;
only with the product's one_more_enabled, from active / paid / tabbed lines in pieces.
- POST /api/orders/{id}/items/{item}/quantity: the venue's switch (off | add_only | add_and_remove),
the key ordering.items.change_quantity; up changes the line only (no ticket); down cuts a
cancelled part ("quantity lowered") and prints a cancellation only when asked.
"""
import json
import pytest
from tests.test_live import err
from tests.test_waiter_keys import shop # noqa: F401 (fixture)
@pytest.fixture
def printed(monkeypatch):
"""What went to the kitchen: new lines (route_and_print_sync) and cancellations."""
import routers.orders as orders
got = {"tickets": [], "cancellations": []}
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: (got["tickets"].append(a), [])[1])
monkeypatch.setattr(orders, "print_cancellation_ticket", lambda order_id, ids: got["cancellations"].append(list(ids)))
return got
def setting(db, key, value):
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
if row is None:
db.add(PosSettings(key=key, value=value))
else:
row.value = value
db.commit()
def lines(db, order_id):
from models.order import OrderItem
db.expire_all()
return db.query(OrderItem).filter(OrderItem.order_id == order_id).order_by(OrderItem.id).all()
def test_one_more_needs_the_products_switch(client, db, shop, printed):
o, item = shop["order"], shop["items"][0]
url = f"/api/orders/{o.id}/items/{item.id}/again"
assert err(client.post(url, headers=shop["h"], json={})) == "order.one_more_off"
item.product.one_more_enabled = True
item.notes = "no ice"
item.selected_options = json.dumps([{"id": None, "name": "Sweet", "price_delta": 0.0, "type": "quick"}])
db.commit()
before = len(lines(db, o.id))
r = client.post(url, headers=shop["h"], json={"quantity": 2})
assert r.status_code == 200, r.text
new = lines(db, o.id)[-1]
assert len(lines(db, o.id)) == before + 1 and new.id != item.id
assert (new.product_id, new.quantity, new.notes, new.status) == (item.product_id, 2, "no ice", "active")
assert json.loads(new.selected_options)[0]["name"] == "Sweet" and new.unit_price == 4.0
assert len(printed["tickets"]) == 1 # sent to the kitchen like any new line
# from a paid line too; never from a cancelled one
paid = shop["items"][2]
assert client.post(f"/api/orders/{o.id}/items/{paid.id}/again", headers=shop["h"], json={}).status_code == 200
paid.status = "cancelled"
db.commit()
assert err(client.post(f"/api/orders/{o.id}/items/{paid.id}/again", headers=shop["h"], json={})) == "order.one_more_line"
def test_one_more_needs_ordering_orders_open(client, db, shop, login, printed):
o, item = shop["order"], shop["items"][0]
item.product.one_more_enabled = True
db.commit()
h = login(shop["new_waiter"](remove=("ordering.orders.open",)), client="waiter")
assert err(client.post(f"/api/orders/{o.id}/items/{item.id}/again", headers=h, json={})) == "access.denied"
def test_quantity_follows_the_venue_and_the_key(client, db, shop, login, printed):
o, item = shop["order"], shop["items"][0]
url = f"/api/orders/{o.id}/items/{item.id}/quantity"
assert err(client.post(url, headers=shop["h"], json={"quantity": 3})) == "order.quantity_change_off"
setting(db, "orders.quantity_change", "add_only")
# a waiter without the key: a manager may approve it
assert err(client.post(url, headers=shop["h"], json={"quantity": 3})) == "access.override_possible"
h = login(shop["new_waiter"](add=("ordering.items.change_quantity",)), client="waiter")
r = client.post(url, headers=h, json={"quantity": 3})
assert r.status_code == 200, r.text
assert lines(db, o.id)[0].quantity == 3 and printed["tickets"] == [] and printed["cancellations"] == []
assert err(client.post(url, headers=h, json={"quantity": 2})) == "order.quantity_remove_off"
from models.order import OrderAuditLog
log = db.query(OrderAuditLog).filter(OrderAuditLog.event_type == "QUANTITY_CHANGED").one()
assert log.note.startswith("1 → 3")
def test_lowering_cancels_the_difference_and_asks_about_the_ticket(client, db, shop, login, printed):
o, item = shop["order"], shop["items"][0]
item.quantity = 5
db.commit()
setting(db, "orders.quantity_change", "add_and_remove")
url = f"/api/orders/{o.id}/items/{item.id}/quantity"
# the key, but not the cancel key: a manager's approval for the cancel part
h = login(shop["new_waiter"](add=("ordering.items.change_quantity",), remove=("ordering.orders.cancel",)), client="waiter")
assert err(client.post(url, headers=h, json={"quantity": 3})) == "access.override_possible"
h = login(shop["new_waiter"](add=("ordering.items.change_quantity", "ordering.orders.cancel")), client="waiter")
r = client.post(url, headers=h, json={"quantity": 3, "print_cancellation": False})
assert r.status_code == 200, r.text
part_id = r.json()["cancelled_item_id"]
rows = {i.id: i for i in lines(db, o.id)}
assert rows[item.id].quantity == 3 and rows[item.id].status == "active"
part = rows[part_id]
assert (part.quantity, part.status, part.cancel_reason, part.split_from_id) == (2, "cancelled", "quantity lowered", item.id)
assert printed["cancellations"] == []
r = client.post(url, headers=h, json={"quantity": 2, "print_cancellation": True})
assert printed["cancellations"] == [[r.json()["cancelled_item_id"]]]
def test_only_unpaid_lines_in_pieces(client, db, shop, printed, login):
setting(db, "orders.quantity_change", "add_and_remove")
o = shop["order"]
paid = shop["items"][2]
boss = login(shop["owner"])
assert err(client.post(f"/api/orders/{o.id}/items/{paid.id}/quantity", headers=boss, json={"quantity": 2})) == "order.quantity_line"
item = shop["items"][0]
item.product.unit_type = "kg"
db.commit()
assert err(client.post(f"/api/orders/{o.id}/items/{item.id}/quantity", headers=boss, json={"quantity": 2})) == "order.quantity_line"
+1 -1
View File
@@ -94,7 +94,7 @@ def test_waiter_cancels_after_manager_pin(client, db, venue, login):
def test_token_is_bound_to_its_key(client, db, venue, make_user, login):
v = venue
token = approve(client, v["waiter_h"], "ordering.prices.modify", make_user(role="owner").username).json()["override_token"]
token = approve(client, v["waiter_h"], "ordering.prices.modify_sent", make_user(role="owner").username).json()["override_token"]
# used for another key: refused, and NOT burned
r = cancel(client, v, v["items"][0], token)
assert err(r) == "access.override_invalid"
+1 -1
View File
@@ -189,7 +189,7 @@ def test_fiscal_driver_with_credit_notes_issues_one(client, db, till, menu, on_s
class Machine(FiscalDriver):
key, credit_notes = "test_machine", True
def prepare_receipt(self, db, items, method, total):
def prepare_receipt(self, db, items, method, total, payments=None):
return lambda timeout: {"success": True, "reference": "R1", "reply": None, "error": None}
def prepare_credit_note(self, db, items, method, total, original=None):
+170
View File
@@ -0,0 +1,170 @@
"""Prices changed by hand, on the record (owner 2026-11-23, plan 6F.3, services/price_changes.py).
- The venue's switch `orders.price_change`: off refuses every by-hand price, before_sending refuses
a sent line's, anytime allows both.
- A sent line needs ordering.prices.modify_sent (modify alone is the cart); a manager's PIN is
recorded as the approver.
- `orders.price_change_reason`: a typed price needs a reason; the counter's % discount doesn't.
- Every change is one manual_price event (before → after, quantity, who, stage, reason) and a
PRICE_CHANGED audit row; only holders of ordering.prices.view_changes see them.
"""
import pytest
from conftest import TEST_PIN
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_order_lines import items_of, open_order
from tests.test_pos import burger_line, menu, on_shift, till # noqa: F401 (fixtures)
from tests.test_pos_tables import floor, phone # noqa: F401 (fixtures)
from tests.test_waiter_keys import shop # noqa: F401 (fixture)
@pytest.fixture(autouse=True)
def _no_printing(monkeypatch):
import routers.orders as orders
monkeypatch.setattr(orders, "route_and_print_sync", lambda *a, **k: [])
def setting(db, key, value):
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
if row is None:
db.add(PosSettings(key=key, value=value))
else:
row.value = value
db.commit()
def manual_events(db, order_id=None):
from models.pricing import PriceEventLog
db.expire_all()
q = db.query(PriceEventLog).filter(PriceEventLog.event_type == "manual_price")
if order_id is not None:
q = q.filter(PriceEventLog.order_id == order_id)
return q.order_by(PriceEventLog.id).all()
def test_a_sent_line_changed_by_hand_is_recorded(client, db, shop, login):
o, item = shop["order"], shop["items"][0]
item.kds_status = "served"
db.commit()
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
r = client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h,
json={"price_adjustment": -1.5, "reason": " regular customer "})
assert r.status_code == 200, r.text
[ev] = manual_events(db, o.id)
assert (ev.order_item_id, ev.price_before, ev.price_after, ev.delta_amount) == (item.id, 4.0, 2.5, -1.5)
assert ev.stage == "served" and ev.quantity == 1 and ev.waiter_note == "regular customer" and ev.approved_by_user_id is None
# a second change records from the changed price, the first stays
r = client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": 0})
assert r.status_code == 200
evs = manual_events(db, o.id)
assert [(e.price_before, e.price_after) for e in evs] == [(4.0, 2.5), (2.5, 4.0)]
from models.order import OrderAuditLog
assert db.query(OrderAuditLog).filter(OrderAuditLog.order_id == o.id, OrderAuditLog.event_type == "PRICE_CHANGED").count() == 2
def test_the_venue_switch(client, db, shop, login):
o, item = shop["order"], shop["items"][0]
url = f"/api/orders/{o.id}/items/{item.id}/price-adjust"
boss = login(shop["owner"])
setting(db, "orders.price_change", "before_sending")
assert err(client.patch(url, headers=boss, json={"price_adjustment": -1})) == "order.price_change_sent_off"
setting(db, "orders.price_change", "off")
assert err(client.patch(url, headers=boss, json={"price_adjustment": -1})) == "order.price_change_off"
setting(db, "orders.price_change", "anytime")
assert client.patch(url, headers=boss, json={"price_adjustment": -1}).status_code == 200
assert len(manual_events(db, o.id)) == 1
def test_a_reason_when_the_venue_asks(client, db, shop, login):
o, item = shop["order"], shop["items"][0]
url = f"/api/orders/{o.id}/items/{item.id}/price-adjust"
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
setting(db, "orders.price_change_reason", "true")
assert err(client.patch(url, headers=h, json={"price_adjustment": -1})) == "order.price_reason_required"
assert err(client.patch(url, headers=h, json={"price_adjustment": -1, "reason": " "})) == "order.price_reason_required"
assert client.patch(url, headers=h, json={"price_adjustment": -1, "reason": "Burnt a bit"}).status_code == 200
assert manual_events(db, o.id)[0].waiter_note == "Burnt a bit"
def test_a_managers_pin_is_the_approver(client, db, shop, make_user, login):
o, item = shop["order"], shop["items"][0]
boss = make_user(role="owner")
approved = client.post("/api/access/override", headers=shop["h"],
json={"key": "ordering.prices.modify_sent", "username": boss.username, "pin": TEST_PIN})
assert approved.status_code == 200, approved.text
h = dict(shop["h"], **{"X-Xenia-Override": approved.json()["override_token"]})
assert client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": 1}).status_code == 200
[ev] = manual_events(db, o.id)
assert ev.approved_by_user_id == boss.id and ev.applied_by_user_id == shop["waiter"].id
def test_a_price_typed_in_the_cart(client, db, menu, phone, floor, make_user, login):
oid = open_order(client, phone["h"], floor["t1"])
line = {"product_id": menu["coffee"].id, "quantity": 2, "price_adjustment": -0.5, "price_reason": "Friend of the house"}
from models.user import WaiterZone
w = make_user(role="waiter", add=("ordering.prices.modify",))
db.add(WaiterZone(waiter_id=w.id, group_id=None))
db.commit()
h = login(w, "waiter")
r = client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [line]})
assert r.status_code == 200, r.text
[item] = items_of(db, oid)
[ev] = manual_events(db, oid)
assert ev.order_item_id == item.id and ev.stage == "cart" and ev.quantity == 2
assert (ev.price_before, ev.price_after) == (item.unit_price, item.unit_price - 0.5) and ev.waiter_note == "Friend of the house"
# the venue asks for a reason: a typed price without one is refused, nothing is added
setting(db, "orders.price_change_reason", "true")
assert err(client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [{**line, "price_reason": None}]})) == "order.price_reason_required"
assert len(items_of(db, oid)) == 1
setting(db, "orders.price_change", "off")
assert err(client.post(f"/api/orders/{oid}/items", headers=h, json={"lines": [line]})) == "order.price_change_off"
def test_the_counters_discount_is_recorded_without_a_reason(client, db, menu, pair, make_user):
from core.timeutil import business_date_of, utcnow
from models.business_day import BusinessDay
from models.shift import WaiterShift
from tests.test_live import terminal_login
token, _ = pair("pos_counter", "Till 2")
boss = make_user(role="owner")
h = {"X-Xenia-Device": token, "Authorization": f"Bearer {terminal_login(client, token, boss)}"}
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() or BusinessDay(
status="open", opened_at=utcnow(), business_date=business_date_of(utcnow()), opened_by_id=boss.id)
db.add(day)
db.flush()
db.add(WaiterShift(waiter_id=boss.id, business_day_id=day.id))
db.commit()
setting(db, "orders.price_change_reason", "true")
r = client.post("/api/pos/sales", headers=h, json={"lines": [{"product_id": menu["coffee"].id, "discount_pct": 10}], "payments": [{"method": "card"}]})
assert r.status_code == 201, r.text
[ev] = manual_events(db, r.json()["order_id"])
assert ev.stage == "cart" and ev.waiter_note == "−10 %" and ev.delta_amount < 0
def test_only_holders_see_the_changes(client, db, shop, make_user, login):
o, item = shop["order"], shop["items"][0]
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
client.patch(f"/api/orders/{o.id}/items/{item.id}/price-adjust", headers=h, json={"price_adjustment": -1, "reason": "x"})
seer = login(make_user(role="store_manager"))
blind = login(make_user(role="store_manager", remove=("ordering.prices.view_changes",)))
assert [e["event_type"] for e in client.get(f"/api/pricing/events/order/{o.id}", headers=seer).json()] == ["manual_price"]
assert client.get(f"/api/pricing/events/order/{o.id}", headers=blind).json() == []
got = client.get(f"/api/orders/{o.id}/price-changes", headers=seer).json()
assert len(got) == 1 and got[0]["before"] == 4.0 and got[0]["after"] == 3.0 and got[0]["reason"] == "x" and got[0]["product_name"]
assert client.get(f"/api/orders/{o.id}/price-changes", headers=blind).status_code == 403
rep = client.get(f"/api/reports/price-changes?business_day_id={o.business_day_id}" if o.business_day_id else
"/api/reports/price-changes", headers=seer).json()
assert rep["count"] >= 1 and rep["total_value"] <= -1.0 and rep["by_person"][0]["count"] >= 1
assert client.get("/api/reports/price-changes", headers=blind).status_code == 403
def test_combining_lines_keeps_their_changes(client, db, shop, login):
o, items = shop["order"], shop["items"]
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
for it in items[:2]:
assert client.patch(f"/api/orders/{o.id}/items/{it.id}/price-adjust", headers=h, json={"price_adjustment": -1}).status_code == 200
r = client.post(f"/api/orders/{o.id}/items/combine", headers=h, json={"item_ids": [items[0].id, items[1].id]})
assert r.status_code == 200, r.text
assert {e.order_item_id for e in manual_events(db, o.id)} == {items[0].id}
assert len(manual_events(db, o.id)) == 2
+2 -1
View File
@@ -56,7 +56,8 @@ def test_a_screen_plays_its_playlist_in_order(client, owner_h, screens, sent):
assert [s["transition"] for s in pl["slides"]] == ["fade", "fade", "zoom"] # the playlist's default
assert pl["media"][str(pic["id"])]["url"] == pic["urls"]["full"] and pl["media"][str(vid["id"])]["url"] == vid["urls"]["original"]
assert pl["media"][str(bg["id"])]["kind"] == "image" and pl["slides"][2]["content"]["background"]["dim"] == 40
assert got["screen"] == {"id": screens[1]["id"], "name": "TV 1", "orientation": "landscape", "rotation": 0}
assert got["screen"] == {"id": screens[1]["id"], "name": "TV 1", "orientation": "landscape", "rotation": 0,
"area": {"left": 0, "top": 0, "right": 0, "bottom": 0}, "fit": "keep", "calibrating": False}
assert len(got["version"]) == 16
+16 -3
View File
@@ -77,10 +77,23 @@ 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
{"kind": "date", "position": "top-left", "size": "custom", "box": {"x": 1, "y": 1, "w": 5, "h": 5}},
{"kind": "text", "text": "Big", "position": "custom", "box": {"x": 99, "y": -50, "w": 30, "h": 20}}]})
clock, date, big = s["content"]["widgets"]
# owner review 6: a box may run off the slide (here past the right edge), a strip of it stays on it
assert clock["size"] == "custom" and clock["box"] == {"x": 90, "y": 5, "w": 20, "h": 10} and clock["align"] == "right"
assert big["box"] == {"x": 95, "y": -15, "w": 30, "h": 20}
assert date["size"] == "medium" and date["box"] is None # a corner: no box, a real size
# owner 2026-11-23: a picture made larger than the slide (cut off at its edges); a gallery's title below
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"widgets": [
{"kind": "logo", "position": "custom", "box": {"x": -60, "y": -40, "w": 220, "h": 180}},
{"kind": "gallery", "text": "Our dishes", "title_position": "below", "position": "top-left"}]}})
logo, gallery = r.json()["content"]["widgets"]
assert logo["box"] == {"x": -60, "y": -40, "w": 220, "h": 180}
assert gallery["text"] == "Our dishes" and gallery["title_position"] == "below"
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"widgets": [
{"kind": "logo", "position": "custom", "box": {"x": 0, "y": 0, "w": 401, "h": 10}}]}})
assert err(r) == "signage.content_invalid" # at most four times the slide
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"widgets": [{"kind": "clock", "position": "custom"}]}})
assert err(r) == "signage.content_invalid" # placed by hand needs its box
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"title": "x"}})
+4 -3
View File
@@ -97,7 +97,7 @@ def test_prices_sold_out_badges_photos(client, owner_h, tv, menu, db):
badges={str(menu["souvlaki"].id): "chef"})
_, m = board(client, owner_h, tv, **content)
souv, steak = m["groups"][0]["items"]
assert (souv["price"], souv["badge"], souv["description"], souv["image"]) == (3.5, "chef", "Pork, on a stick", photo["urls"]["card"])
assert (souv["price"], souv["badges"], souv["description"], souv["image"]) == (3.5, ["chef"], "Pork, on a stick", photo["urls"]["card"])
assert steak["available"] is False and steak["price"] == 12.0 and steak["image"] is None
_, m = board(client, owner_h, tv, **content, sold_out="hide")
assert [i["name"] for i in m["groups"][0]["items"]] == ["Souvlaki"]
@@ -136,7 +136,7 @@ def test_menu_settings_are_checked(client, owner_h, tv):
url = f"/api/signage/playlists/{tv['playlist']}/slides"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"sales_point": "moon"}})) == "signage.content_invalid"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"x": "new"}}})) == "signage.content_invalid"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"3": "shiny"}}})) == "signage.content_invalid"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"3": "Shiny!"}}})) == "signage.content_invalid"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"columns": 4}})) == "signage.content_invalid"
@@ -148,4 +148,5 @@ def test_the_editor_previews(client, owner_h, tv, menu):
assert names(draft["menu"]) == [["Grill", ["Steak"]]] and draft["content"]["columns"] == 2
assert err(client.post("/api/signage/preview/menu", headers=owner_h, json={"content": {"columns": 9}})) == "signage.content_invalid"
client.put("/api/signage/message", headers=owner_h, json={"text": "Hello"})
assert client.get("/api/signage/venue", headers=owner_h).json() == {"name": None, "message": "Hello", "weather": None}
v = client.get("/api/signage/venue", headers=owner_h).json()
assert {k: v[k] for k in ("name", "message", "weather")} == {"name": None, "message": "Hello", "weather": None} and len(v["badges"]) == 7
@@ -0,0 +1,73 @@
"""Slide shapes and a screen's picture (6R.13, owner 2026-11-22): custom shapes for playlists and
library slides, a screen's picture area (insets) and fit, calibrating told to that screen only,
the window size a screen reports."""
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
def test_custom_shapes_for_playlists_and_library_slides(client, owner_h):
p = playlist(client, owner_h, aspect="21:9")
assert (p["orientation"], p["aspect"]) == ("landscape", "21:9")
r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "10:16"})
assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", "10:16")
# the plain shapes are landscape / portrait; picking one drops a custom shape
r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "16:9"})
assert (r.json()["orientation"], r.json()["aspect"]) == ("landscape", None)
client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "32:9"})
r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"orientation": "portrait"})
assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", None)
for bad in ("21x9", "9:1", "0:5"):
assert client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": bad}).status_code == 422
dup = client.post(f"/api/signage/playlists/{p['id']}/duplicate", headers=owner_h).json()
assert dup["orientation"] == "portrait"
s = client.post("/api/signage/library", headers=owner_h, json={"name": "Wide", "kind": "text", "aspect": "16:10"}).json()
assert (s["orientation"], s["aspect"]) == ("landscape", "16:10")
r = client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"aspect": None, "orientation": "portrait"})
assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", None)
def test_a_screens_picture_area_and_calibration(client, owner_h, screens, sent):
tv, other = screens[1], screens[2]
p = playlist(client, owner_h, aspect="21:9")
slide(client, owner_h, p["id"], "text", content={"title": "Wide"})
client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"playlist_id": p["id"]})
got = client.get("/api/signage/screen", headers=tv["h"]).json()
assert got["playlist"]["aspect"] == "21:9" and got["screen"]["fit"] == "keep" and got["screen"]["calibrating"] is False
# the TV reports its window; the manager sees it
assert client.post("/api/signage/screen/viewport", headers=tv["h"], json={"width": 2560, "height": 1080, "ratio": 1}).status_code == 200
one = next(s for s in client.get("/api/signage/screens", headers=owner_h).json() if s["id"] == tv["id"])
assert one["viewport"] == {"width": 2560, "height": 1080, "ratio": 1.0} and one["area"] == {"left": 0, "top": 0, "right": 0, "bottom": 0}
# calibrating: only that TV hears it, with its area; every change of the insets follows at once
sent.clear()
r = client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": True})
assert r.json()["calibrating"] is True and sent == [("signage.calibrate", [tv["id"]])]
sent.clear()
r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": 320, "area_right": 320, "fit": "stretch"})
assert r.json()["area"] == {"left": 320, "top": 0, "right": 320, "bottom": 0} and r.json()["fit"] == "stretch"
assert sent[0] == ("signage.calibrate", [tv["id"]]) and ("signage.changed", [tv["id"]]) in sent
scr = client.get("/api/signage/screen", headers=tv["h"]).json()["screen"]
assert scr["area"]["left"] == 320 and scr["calibrating"] is True
sent.clear()
client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": False})
assert sent == [("signage.calibrate", [tv["id"]])]
sent.clear()
client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_top": 5})
assert ("signage.calibrate", [tv["id"]]) not in sent
# limits; not a screen
assert client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": 5000}).status_code == 422
# owner 2026-11-23: an edge may reach past the window the TV reported (its real picture is larger)
r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": -60, "area_top": 0})
assert r.status_code == 200 and r.json()["area"]["left"] == -60
assert client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": -2001}).status_code == 422
assert err(client.post("/api/signage/screens/99999/calibrate", headers=owner_h, json={"on": True})) == "signage.not_a_screen"
# a screen can't calibrate itself or report for another
assert client.post(f"/api/signage/screens/{other['id']}/calibrate", headers=tv["h"], json={"on": True}).status_code in (401, 403)
def test_calibration_ends_by_itself(client, owner_h, screens, monkeypatch):
import routers.signage as sg
tv = screens[1]
client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": True})
assert sg.calibrating(tv["id"]) is True
sg._calibrating[tv["id"]] -= sg.CALIBRATE_S + 1
assert client.get("/api/signage/screen", headers=tv["h"]).json()["screen"]["calibrating"] is False
+191
View File
@@ -0,0 +1,191 @@
"""Signage widgets, owner review 2026-11-21: a text of its own, a menu widget (a board's list in the
widget's place), stacks (parts side by side or one over the other, each with a widget, another
stack one level deep, or a whole library slide), weather for tomorrow / the day after and in three
styles; products hidden from a board stay in the editor's list (greyed), never on the TV."""
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
from tests.test_signage_menu import menu, names # noqa: F401 (fixture + helper)
BOX = {"x": 5, "y": 10, "w": 90, "h": 80}
def stack(*cells, direction="row"):
return {"kind": "stack", "direction": direction, "position": "custom", "box": BOX, "cells": list(cells)}
def keep(client, h, **body):
r = client.post("/api/signage/library", headers=h, json={"name": "Promo", "kind": "text", **body})
assert r.status_code == 201, r.text
return r.json()
def test_text_weather_and_stack_widgets_are_checked(client, owner_h):
p = playlist(client, owner_h)
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [
{"kind": "text", "text": "Happy hour 18-20"},
{"kind": "weather", "weather_from": 5, "weather_days": 3, "weather_style": "icon"},
stack({"share": 30, "widget": {"kind": "clock"}}, {"share": 70, "widget": stack({"share": 50}, {"share": 50}, direction="column")}),
]})
ws = s["content"]["widgets"]
assert ws[0]["text"] == "Happy hour 18-20"
assert ws[1]["weather_from"] == 5 and ws[1]["weather_days"] == 2 and ws[1]["weather_style"] == "icon" # the forecast has 7 days (6R.18)
assert [c["share"] for c in ws[2]["cells"]] == [30, 70] and ws[2]["cells"][1]["widgets"][0]["direction"] == "column"
assert ws[0]["cells"] == [] and ws[0]["board"] is None
url = f"/api/signage/playlists/{p['id']}/slides"
bad = [
stack(), # no parts
stack({"share": 50, "widget": {"kind": "clock"}, "slide_id": 1}), # a widget and a slide
stack({"share": 50, "widget": stack({"share": 50, "widget": stack({"share": 100})})}), # three stacks deep
stack(*[{"share": 10}] * 7), # more than 6 parts
]
for w in bad:
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": [w]}})) == "signage.content_invalid", w
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": [stack({"share": 100, "slide_id": 999})]}})) == "signage.slide_unknown"
def test_a_stack_shows_a_library_slide_and_a_menu_widget(client, owner_h, screens, sent, menu, db):
promo = keep(client, owner_h, content={"title": "Fresh fish", "widgets": [{"kind": "qr", "position": "bottom-right"}]})
p = playlist(client, owner_h, "Split")
tv = screens[1]
client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"playlist_id": p["id"]})
board = {"kind": "menu", "board": {"category_ids": [menu["cats"]["drinks"]], "exclude_ids": [menu["beer"].id], "columns": 1}}
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [
{"kind": "qr", "position": "top-left"},
stack({"share": 25, "widget": board}, {"share": 75, "slide_id": promo["id"]}),
]})
# the screen: extras by widget path (the QR's link, the menu's products, the slide inside the part)
got = client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]
ex = got["extras"]
assert ex["0"]["link"] and got["content"]["widgets"][0]["link"] == ex["0"]["link"]
assert names(ex["1.0.0"]["menu"]) == [] and ex["1.0.0"]["menu"]["count"] == 0 # Beer hidden; Wine: delivery only
inner = ex["1.1"]["slide"]
assert inner["id"] == promo["id"] and inner["kind"] == "text" and inner["content"]["title"] == "Fresh fish"
assert inner["extras"]["0"]["link"] # its own widgets' extras
# the editor: the hidden product stays in the list, marked
ed = client.get(f"/api/signage/playlists/{p['id']}", headers=owner_h).json()["slides"][0]["extras"]["1.0.0"]["menu"]
assert [(i["name"], i.get("hidden", False)) for g in ed["groups"] for i in g["items"]] == [("Beer", True)] and ed["count"] == 0
# a change to the library slide reaches the screens that show it inside a stack
sent.clear()
client.put(f"/api/signage/library/{promo['id']}", headers=owner_h, json={"content": {"title": "Fresh octopus"}})
assert sent == [("signage.changed", [tv["id"]])]
assert client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]["extras"]["1.1"]["slide"]["content"]["title"] == "Fresh octopus"
# products change: a slide with a menu widget is told too
import routers.signage as sg
sent.clear()
sg.menu_changed(db)
assert sent == [("signage.changed", [tv["id"]])]
# the library slide deleted: the part shows nothing, the screen is told
sent.clear()
client.delete(f"/api/signage/library/{promo['id']}", headers=owner_h)
assert sent == [("signage.changed", [tv["id"]])]
assert "1.1" not in client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]["extras"]
assert s["content"]["widgets"][1]["cells"][1]["slide_id"] == promo["id"]
def test_the_editor_previews_any_slide(client, owner_h, menu):
promo = keep(client, owner_h, content={"title": "Inside"})
r = client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "blank", "content": {"widgets": [
stack({"share": 50, "widget": {"kind": "menu", "board": {"product_ids": [menu["steak"].id], "exclude_ids": [menu["steak"].id]}}},
{"share": 50, "slide_id": promo["id"]})]}})
assert r.status_code == 200, r.text
got = r.json()
assert [i.get("hidden") for g in got["extras"]["0.0.0"]["menu"]["groups"] for i in g["items"]] == [True]
assert got["extras"]["0.1"]["slide"]["content"]["title"] == "Inside" and got["menu"] is None and got["media"] == {}
r = client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "menu", "content": {"select": "all", "exclude_ids": [menu["beer"].id]}})
m = r.json()["menu"]
assert "Beer" in [i["name"] for g in m["groups"] for i in g["items"] if i.get("hidden")] and m["count"] == 3
assert err(client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "text", "content": {"widgets": [stack()]}})) == "signage.content_invalid"
def test_a_board_has_its_own_names_and_the_look_of_each_part(client, owner_h, menu):
"""Owner review 3 (2026-11-21): names only for this board (the catalogue keeps its own), the look
of headings, names, prices and the dots, spacing, photos."""
content = {"category_ids": [menu["cats"]["drinks"]], "names": {str(menu["beer"].id): " Craft beer "}, "category_names": {str(menu["cats"]["drinks"]): "Bar"},
"heading_style": {"size": 180, "colour": "#ff0000", "font": "serif", "align": "center", "italic": True},
"price_style": {"align": "right", "bold": False}, "dot_style": {"style": "dashed", "size": 150},
"line_height": 1.4, "letter_spacing": 0.05, "photo_size": 150, "photo_shape": "round"}
r = client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "menu", "content": content})
assert r.status_code == 200, r.text
g = r.json()["menu"]["groups"][0]
assert g["category"] == {"id": menu["cats"]["drinks"], "name": "Bar", "original": "Drinks"}
assert g["items"][0]["name"] == "Craft beer" and g["items"][0]["original"] == "Beer"
p = playlist(client, owner_h)
s = slide(client, owner_h, p["id"], "menu", content=content)
c = s["content"]
assert c["names"] == {str(menu["beer"].id): "Craft beer"} and c["heading_style"]["italic"] and c["item_style"]["bold"]
assert c["price_style"] == {"size": None, "colour": None, "font": None, "bold": False, "italic": False, "underline": False, "align": "right"}
url = f"/api/signage/playlists/{p['id']}/slides"
for bad in ({"names": {"x": "a"}}, {"heading_style": {"size": 20}}, {"dot_style": {"style": "wavy"}}, {"line_height": 9}, {"photo_shape": "star"}):
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": bad})) == "signage.content_invalid", bad
def test_a_part_holds_several_widgets_and_colours_can_be_see_through(client, owner_h, menu):
"""Owner review 4 (2026-11-21): a stack's part holds several widgets (each with its own extras,
by path "stack.part.place"); a part stored with one `widget` still reads; colours #rrggbbaa; a
board's badges have their own text colour."""
p = playlist(client, owner_h)
s = slide(client, owner_h, p["id"], "blank", content={"background": {"colour": "#11182780"}, "widgets": [
stack({"share": 40, "widgets": [{"kind": "clock"}, {"kind": "qr"}, {"kind": "menu", "board": {"product_ids": [menu["steak"].id]}}]},
{"share": 60, "widget": {"kind": "date"}}),
]})
cells = s["content"]["widgets"][0]["cells"]
assert [w["kind"] for w in cells[0]["widgets"]] == ["clock", "qr", "menu"] and [w["kind"] for w in cells[1]["widgets"]] == ["date"]
assert "widget" not in cells[1] and s["content"]["background"]["colour"] == "#11182780"
ex = client.get(f"/api/signage/playlists/{p['id']}", headers=owner_h).json()["slides"][0]["extras"]
assert ex["0.0.1"]["link"] and names(ex["0.0.2"]["menu"]) == [["Grill", ["Steak"]]]
url = f"/api/signage/playlists/{p['id']}/slides"
for bad in (stack({"share": 50, "widgets": [{"kind": "clock"}], "slide_id": 1}),
stack({"share": 50, "widgets": [{"kind": "clock"}] * 7})):
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": [bad]}})) == "signage.content_invalid", bad
m = slide(client, owner_h, p["id"], "menu", content={"accent_colour": "#1e3a8a", "badge_text_colour": "#fde68aCC"})["content"]
assert m["badge_text_colour"] == "#fde68aCC" and m["accent_colour"] == "#1e3a8a"
for bad in ({"badge_text_colour": "#fff"}, {"text_colour": "#12345"}):
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": bad})) == "signage.content_invalid", bad
def test_the_venues_badges_and_a_widgets_own_look(client, owner_h, menu, screens):
"""Owner review 5 (2026-11-21): the venue's badges (names, colours, icons) edited in one place and
sent with the venue; a product with several badges; a widget's own look; a board's list placed
up or down."""
got = client.get("/api/signage/badges", headers=owner_h).json()
assert [b["key"] for b in got["badges"]][:3] == ["new", "chef", "offer"] and "flame" in got["icons"]
mine = got["badges"][:2] + [{"key": "gluten-free", "names": {"el": "Χωρίς γλουτένη", "en": "Gluten free"}, "colour": "#0ea5e9", "text_colour": "#ffffff", "icon": "wheat-off"}]
r = client.put("/api/signage/badges", headers=owner_h, json={"badges": mine})
assert r.status_code == 200, r.text and [b["key"] for b in r.json()["badges"]] == ["new", "chef", "gluten-free"]
for bad in ([{"key": "x", "names": {}}], [{"key": "x", "names": {"en": "X"}, "icon": "unicorn"}],
[{"key": "x", "names": {"en": "X"}}, {"key": "x", "names": {"en": "Y"}}]):
assert err(client.put("/api/signage/badges", headers=owner_h, json={"badges": bad})) == "signage.content_invalid", bad
assert client.get("/api/signage/venue", headers=owner_h).json()["badges"][2]["icon"] == "wheat-off"
p = playlist(client, owner_h)
sid = str(menu["steak"].id)
s = slide(client, owner_h, p["id"], "menu", content={"product_ids": [menu["steak"].id], "badges": {sid: ["chef", "gluten-free"]},
"board_valign": "middle", "badge_colour": "#000000", "widgets": [
{"kind": "qr", "qr_colour": "#1e3a8a", "qr_background": "#fde68a", "colour": "#ff0000", "bold": False, "italic": True, "font": "serif", "text_size": 150,
"background_colour": "#00000080"},
stack({"share": 100, "widgets": [{"kind": "clock", "vertical": "bottom", "align": "right"},
{"kind": "date", "position": "custom", "box": {"x": 10, "y": 10, "w": 50, "h": 40}}]})]})
c = s["content"]
assert c["badges"] == {sid: ["chef", "gluten-free"]} and c["board_valign"] == "middle" and c["badge_colour"] == "#000000"
q = c["widgets"][0]
assert (q["qr_colour"], q["qr_background"], q["bold"], q["italic"], q["text_size"], q["font"]) == ("#1e3a8a", "#fde68a", False, True, 150, "serif")
part = c["widgets"][1]["cells"][0]["widgets"]
assert part[0]["vertical"] == "bottom" and part[1]["box"] == {"x": 10, "y": 10, "w": 50, "h": 40}
url = f"/api/signage/playlists/{p['id']}/slides"
for bad in ({"badges": {sid: ["a", "b", "c", "d", "e"]}}, {"board_valign": "centre"}, {"widgets": [{"kind": "clock", "text_size": 400}]}):
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": bad})) == "signage.content_invalid", bad
def test_how_many_widgets_a_slide_may_hold_is_the_venues(client, owner_h):
"""Owner review 6 (2026-11-21): 10 widgets a slide (recommended), more when the venue allows them
(Signage → Message & settings → Performance), never over 50; a menu with pages may now turn them
every second."""
assert client.get("/api/signage/performance", headers=owner_h).json() == {"max_widgets": 10, "recommended": 10, "cap": 50}
p = playlist(client, owner_h)
url = f"/api/signage/playlists/{p['id']}/slides"
eleven = [{"kind": "clock"}] * 11
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": eleven}})) == "signage.too_many_widgets"
assert client.put("/api/signage/performance", headers=owner_h, json={"max_widgets": 12}).json()["max_widgets"] == 12
assert client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": eleven}}).status_code == 201
assert err(client.put("/api/signage/performance", headers=owner_h, json={"max_widgets": 51})) is not None
s = slide(client, owner_h, p["id"], "menu", content={"page_seconds": 1}, duration_s=1)
assert s["content"]["page_seconds"] == 1 and s["duration_s"] == 1
@@ -104,6 +104,8 @@ def test_the_weather_shows_with_internet_and_hides_without(client, owner_h, tv,
assert ("signage.changed", [tv["id"]]) in sent
w = client.get("/api/signage/screen", headers=tv["h"]).json()["venue"]["weather"]
assert w["place"] == "Kalavryta" and w["code"] == 2 and [d["max"] for d in w["days"]] == [19.0, 16.5] and w["units"] == "celsius"
# 6R.18: an answer without the detailed fields still reads (they are None)
assert w["feels_like"] is None and w["days"][0]["sunrise"] is None and w["hours"] == [] and w["wind_unit"] == "km/h"
# the internet goes: the last forecast stays while it is fresh, then the widget hides
internet["up"] = False
sent.clear()
@@ -128,3 +130,28 @@ def test_who_may(client, make_user, login):
waiter = login(make_user(role="waiter"))
assert client.put("/api/signage/message", headers=waiter, json={"text": "x"}).status_code == 403
assert client.get("/api/signage/weather", headers=waiter).status_code == 403
def test_the_detailed_weather(monkeypatch):
"""6R.18: humidity, feels like, wind, rain chance, sunrise / sunset, UV and the next 24 hours."""
import asyncio
import httpx
from services import weather
hours = [f"2026-11-17T{h:02d}:00" for h in range(24)] + [f"2026-11-18T{h:02d}:00" for h in range(24)]
answer = {"current": {"time": "2026-11-17T12:15", "temperature_2m": 17.4, "weather_code": 2, "is_day": 1, "apparent_temperature": 15.9,
"relative_humidity_2m": 62, "wind_speed_10m": 12.3, "wind_direction_10m": 200, "precipitation": 0},
"daily": {"time": ["2026-11-17", "2026-11-18"], "temperature_2m_max": [19.0, 16.5], "temperature_2m_min": [9.1, 8.0],
"weather_code": [2, 61], "precipitation_probability_max": [10, 80], "wind_speed_10m_max": [20, 35], "uv_index_max": [3.2, 1.0],
"sunrise": ["2026-11-17T07:12", "2026-11-18T07:13"], "sunset": ["2026-11-17T17:08", "2026-11-18T17:07"]},
"hourly": {"time": hours, "temperature_2m": list(range(48)), "weather_code": [0] * 48, "precipitation_probability": [5] * 48, "is_day": [1] * 48}}
seen = {}
def handler(req):
seen.update(dict(req.url.params))
return httpx.Response(200, json=answer)
c = httpx.AsyncClient(transport=httpx.MockTransport(handler))
w = asyncio.run(weather.fetch({"name": "X", "latitude": 1, "longitude": 2, "units": "fahrenheit"}, c))
assert seen["forecast_days"] == "7" and seen["wind_speed_unit"] == "mph" and "hourly" in seen
assert w["feels_like"] == 15.9 and w["humidity"] == 62 and w["wind"] == 12.3 and w["wind_unit"] == "mph"
assert w["days"][1] == {"date": "2026-11-18", "max": 16.5, "min": 8.0, "code": 61, "rain": 80, "wind": 35, "uv": 1.0, "sunrise": "07:13", "sunset": "17:07"}
assert len(w["hours"]) == 24 and w["hours"][0]["time"] == "12:00" and w["hours"][0]["temp"] == 12 and w["hours"][-1]["time"] == "11:00"
+237
View File
@@ -0,0 +1,237 @@
"""Split the bill by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py).
- POST /api/orders/{id}/split-bills settles the chosen unpaid lines (status split) and adds part
lines (the system product split_part), paid like any line; the venue's level and the key decide.
- Undo while no part is paid; parts can't be cancelled, moved or re-priced on their own.
- Counting: the settled lines are the sales, the parts are the money (drawers), never both.
- Fiscal: one receipt with the settled lines, when the last part is paid, with each method's amount.
- The counter: a quick sale split and paid at once (Q-4).
"""
import json
import pytest
from tests.test_live import err, owner_h, pair, terminal_login # noqa: F401 (fixtures)
from tests.test_pos import burger_line, drawer_printer, menu, on_shift, sale, till # noqa: F401 (fixtures)
from tests.test_pos_refunds import fiscal_on, refund, shift_of, wait_for
def setting(db, key, value):
from models.settings import PosSettings
row = db.get(PosSettings, key)
if row is None:
db.add(PosSettings(key=key, value=value))
else:
row.value = value
db.commit()
@pytest.fixture
def table_order(db, till, menu, on_shift):
"""The cashier's order with a 10.00 burger and a 5.00 (two coffees at 2.50), nothing paid."""
from models.order import Order, OrderItem, OrderWaiter
o = Order(opened_by=till["cashier"].id, order_type="here", status="open", business_day_id=on_shift.business_day_id)
db.add(o)
db.flush()
db.add(OrderWaiter(order_id=o.id, waiter_id=till["cashier"].id))
items = [OrderItem(order_id=o.id, product_id=menu["burger"].id, added_by=till["cashier"].id, quantity=1, unit_price=10.0,
printed=True, kds_status="preparing", unit_cost=3.5),
OrderItem(order_id=o.id, product_id=menu["coffee"].id, added_by=till["cashier"].id, quantity=2, unit_price=2.5,
printed=True)]
db.add_all(items)
db.commit()
return {"order": o, "items": items}
def split(client, till, order_id, ids, **body):
return client.post(f"/api/orders/{order_id}/split-bills", headers=till["h"], json={"item_ids": ids, **body})
def rows(db, order_id):
from models.order import OrderItem
db.expire_all()
return db.query(OrderItem).filter(OrderItem.order_id == order_id).order_by(OrderItem.id).all()
def pay(client, till, order_id, method, ids):
return client.post(f"/api/pos/orders/{order_id}/pay", headers=till["h"], json={"payments": [{"method": method, "item_ids": ids}]})
def test_amounts_and_levels():
from services.split_bills import allowed, amounts
assert amounts(10.0, "equal", 3) == [3.33, 3.33, 3.34]
assert amounts(15.0, "equal", 2) == [7.5, 7.5]
assert amounts(15.0, "custom", 2, 4.5) == [4.5, 10.5]
assert sum(amounts(17.21, "equal", 7)) == pytest.approx(17.21)
# each level includes the ones before; multiple ways are equal parts only (Q-1)
assert not allowed("off", "equal", 2, 10)
assert allowed("two_equal", "equal", 2, 10) and not allowed("two_equal", "custom", 2, 10)
assert allowed("two_custom", "custom", 2, 10) and not allowed("two_custom", "equal", 3, 10)
assert allowed("multiple_equal", "equal", 10, 10) and not allowed("multiple_equal", "equal", 11, 10)
assert allowed("multiple_equal", "custom", 2, 10) and not allowed("multiple_equal", "custom", 3, 10)
def test_split_30_70_paid_cash_and_card(client, db, till, table_order):
"""10 + 5 into 4.50 + 10.50: the lines settled, two parts paid apart; the drawer counts the
parts, the sales count the lines, never both."""
from services import sales
o, items = table_order["order"], table_order["items"]
ids = [i.id for i in items]
assert err(split(client, till, o.id, ids, mode="custom", first_amount=4.5)) == "split.not_allowed" # off by default
setting(db, "payments.split_amount", "two_custom")
r = split(client, till, o.id, ids, mode="custom", first_amount=4.5)
assert r.status_code == 200, r.text
bill = r.json()
assert (bill["total"], bill["amounts"], bill["parts"], bill["can_undo"]) == (15.0, [4.5, 10.5], 2, True)
lines = rows(db, o.id)
settled = [i for i in lines if i.status == "split"]
parts = [i for i in lines if i.split_bill_id and i.status != "split"]
assert {i.id for i in settled} == set(ids) and all(i.paid_in_shift_id is None and i.payment_method is None for i in settled)
assert [(p.product_name, p.unit_price, p.status, p.printed, p.kds_status) for p in parts] == [
("Split bill 1/2", 4.5, "active", True, "served"), ("Split bill 2/2", 10.5, "active", True, "served")]
assert parts[0].product.system_key == "split_part"
# the settled burger is still cooking: the kitchen state is untouched
assert next(i for i in settled if i.unit_price == 10.0).kds_status == "preparing"
got = client.get(f"/api/orders/{o.id}", headers=till["h"]).json()
assert got["split_bills"][0]["part_ids"] == [p.id for p in parts]
assert pay(client, till, o.id, "cash", [parts[0].id]).status_code == 200
# undo refused once a part is paid (Q-2)
assert err(client.post(f"/api/orders/{o.id}/split-bills/{bill['id']}/undo", headers=till["h"])) == "split.paid_already"
r = pay(client, till, o.id, "card", [parts[1].id])
assert r.status_code == 200 and r.json()["status"] in ("paid", "closed"), r.text
s = shift_of(client, till)
assert (s["cash_sales"], s["card_sales"]) == (4.5, 10.5)
money = sales.totals(sales.lines(db, rows(db, o.id))).out()
assert (money["revenue"], money["fees"], money["takings"], money["total_cost"]) == (15.0, 0.0, 15.0, 3.5)
assert {p["product_name"] for p in sales.products(db, rows(db, o.id)).values()} == {"Burger", "Freddo"}
def test_equal_parts_levels_and_the_key(client, db, till, table_order, login, make_user):
o, items = table_order["order"], table_order["items"]
ids = [i.id for i in items]
setting(db, "payments.split_amount", "two_equal")
assert err(split(client, till, o.id, ids, parts=3)) == "split.not_allowed"
assert err(split(client, till, o.id, ids, mode="custom", first_amount=5)) == "split.not_allowed"
setting(db, "payments.split_amount", "multiple_equal")
setting(db, "payments.split_max_parts", "4")
assert err(split(client, till, o.id, ids, parts=5)) == "split.not_allowed"
# the key: someone without it is refused (a manager could approve it, D-10)
from models.user import WaiterZone
w = make_user(role="waiter", remove=("ordering.payments.split_amount",))
db.add(WaiterZone(waiter_id=w.id, group_id=None))
db.commit()
r = client.post(f"/api/orders/{o.id}/split-bills", headers=login(w, client="waiter"), json={"item_ids": ids, "parts": 3})
assert err(r) in ("access.denied", "access.override_possible")
r = split(client, till, o.id, ids, parts=4)
assert r.status_code == 200 and r.json()["amounts"] == [3.75, 3.75, 3.75, 3.75]
# the same lines can't be split twice
assert err(split(client, till, o.id, ids, parts=2)) == "split.lines_changed"
def test_locks_close_and_undo(client, db, till, table_order):
from models.order import OrderAuditLog
o, items = table_order["order"], table_order["items"]
setting(db, "payments.split_amount", "multiple_equal")
bill = split(client, till, o.id, [i.id for i in items], parts=3).json()
assert bill["amounts"] == [5.0, 5.0, 5.0]
part = bill["part_ids"][0]
h = till["h"]
assert err(client.delete(f"/api/orders/{o.id}/items/{part}", headers=h)) in ("split.part_locked", "access.override_possible")
assert err(client.patch(f"/api/orders/{o.id}/items/{part}/price-adjust", headers=h, json={"price_adjustment": -1})) == "split.part_locked"
assert err(client.post(f"/api/orders/{o.id}/items/combine", headers=h, json={"item_ids": bill["part_ids"][:2]})) == "split.part_locked"
assert err(client.patch(f"/api/orders/{o.id}/items/{items[0].id}/price-adjust", headers=h, json={"price_adjustment": -1})) == "order.item_not_active"
setting(db, "orders.close_with_unpaid", "true")
assert err(client.post(f"/api/orders/{o.id}/close", headers=h)) == "split.parts_unpaid" # never written off
# undo: the parts cancelled, the lines unpaid again
r = client.post(f"/api/orders/{o.id}/split-bills/{bill['id']}/undo", headers=h)
assert r.status_code == 200, r.text
lines = rows(db, o.id)
assert [i.status for i in lines if i.id in (items[0].id, items[1].id)] == ["active", "active"]
assert all(i.split_bill_id is None and i.paid_at is None for i in lines if i.id in (items[0].id, items[1].id))
assert [(i.status, i.cancel_reason) for i in lines if i.id in bill["part_ids"]] == [("cancelled", "split undone")] * 3
assert client.get(f"/api/orders/{o.id}", headers=h).json()["split_bills"] == []
events = [a.event_type for a in db.query(OrderAuditLog).filter(OrderAuditLog.order_id == o.id).order_by(OrderAuditLog.id)]
assert events[-2:] == ["SPLIT_CREATED", "SPLIT_UNDONE"]
def test_the_fiscal_receipt_is_the_lines_when_the_last_part_is_paid(client, db, till, menu, table_order, tmp_path, monkeypatch):
from services import fiscal
from services.fiscal.base import FiscalDriver
issued = []
class Machine(FiscalDriver):
key = "test_machine"
def prepare_receipt(self, db, items, method, total, payments=None):
issued.append((items, method, total, payments))
return lambda timeout: {"success": True, "reference": "R1", "reply": None, "error": None}
monkeypatch.setitem(fiscal.DRIVERS, "test_machine", Machine())
monkeypatch.setattr(fiscal, "_set_status", lambda *a: None)
fiscal_on(db, tmp_path)
setting(db, "fiscal.type", "test_machine")
o, items = table_order["order"], table_order["items"]
setting(db, "payments.split_amount", "two_custom")
assert err(split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5)) == "pos.fiscal_vat_missing"
menu["burger"].fiscal_vat_group_id = 1
menu["coffee"].fiscal_vat_group_id = 2
db.commit()
bill = split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5).json()
r = pay(client, till, o.id, "cash", [bill["part_ids"][0]])
assert r.status_code == 200 and r.json()["fiscal"] is None and issued == [] # part 1: no receipt yet
r = pay(client, till, o.id, "card", [bill["part_ids"][1]])
assert r.status_code == 200 and r.json()["fiscal"] == "pending"
assert wait_for(lambda: issued)
lines, _method, total, payments = issued[0]
assert sorted((x["name"], x["qty"], x["unit_price"], x["vat_group_id"]) for x in lines) == [("Burger", 1, 10.0, 1), ("Freddo", 2, 2.5, 2)]
assert total == 15.0 and sorted((p["method"], p["amount"]) for p in payments) == [("card", 10.5), ("cash", 4.5)]
assert sum(x["qty"] * x["unit_price"] for x in lines) == pytest.approx(sum(p["amount"] for p in payments))
assert len(issued) == 1
def test_the_text_file_closes_with_card_then_cash(db, tmp_path):
from services.fiscal.txt_file import _build_command_file
fiscal_on(db, tmp_path)
out = _build_command_file([{"name": "Burger", "qty": 1, "unit_price": 10.0, "vat_group_id": 1}], "cash", 10.0, db,
payments=[{"method": "cash", "amount": 4.5}, {"method": "card", "amount": 5.5}])
assert out.split("\r\n")[-3:] == ["CD|2|1|1|5.50", "CR|2", ""]
out = _build_command_file([{"name": "Burger", "qty": 1, "unit_price": 10.0, "vat_group_id": 1}], "cash", 10.0, db,
payments=[{"method": "card", "amount": 10.0}])
assert out.split("\r\n")[-2:] == ["CD|2|1|1|10.00", ""]
def test_a_refunded_part_comes_off_the_settled_lines(client, db, till, table_order, drawer_printer):
from services import sales
o, items = table_order["order"], table_order["items"]
setting(db, "payments.split_amount", "two_custom")
bill = split(client, till, o.id, [i.id for i in items], mode="custom", first_amount=4.5).json()
assert pay(client, till, o.id, "cash", bill["part_ids"]).status_code == 200
r = refund(client, till, o.id, [{"item_id": bill["part_ids"][0], "quantity": 1}], reason="Overcharged")
assert r.status_code == 201, r.text
money = sales.totals(sales.lines(db, rows(db, o.id))).out()
assert (money["revenue"], money["refunded"]) == (10.5, 4.5)
assert shift_of(client, till)["cash_refunds"] == 4.5
def test_a_quick_sale_split_and_paid_at_once(client, db, till, menu, on_shift, drawer_printer):
"""Q-4: the counter splits a quick sale into equal parts, each paid its own way now."""
from models.order import Order
setting(db, "payments.split_amount", "multiple_equal")
lines = [{"product_id": menu["coffee"].id, "quantity": 3}, burger_line(menu)]
r = sale(client, till, lines, [], split={"mode": "equal", "parts": 3, "methods": ["cash", "card", "cash"]}, cash_given=20)
assert r.status_code == 201, r.text
body = r.json()
assert body["total"] == 19.0 and body["split"]["amounts"] == [6.33, 6.33, 6.34]
assert sorted((p["method"], p["amount"]) for p in body["payments"]) == [("card", 6.33), ("cash", 12.67)]
assert body["change"] == 7.33
db.expire_all()
assert db.get(Order, body["order_id"]).status in ("paid", "closed")
s = shift_of(client, till)
assert (s["cash_sales"], s["card_sales"]) == (12.67, 6.33)
# off at this venue → refused before anything is written
setting(db, "payments.split_amount", "two_equal")
n = db.query(Order).count()
r = sale(client, till, lines, [], split={"mode": "equal", "parts": 3, "methods": ["cash", "card", "cash"]})
assert err(r) == "split.not_allowed" and db.query(Order).count() == n
+10
View File
@@ -8,3 +8,13 @@ def test_venue_theme_reaches_bootstrap(client, make_user, login):
assert client.get("/api/platform/bootstrap").json()["venue"]["theme"] == "blue"
r = client.put("/api/settings/venue.theme", headers=owner, json={"value": "neon"})
assert r.status_code in (400, 422)
def test_the_identity_as_the_staff_apps_colour(client, make_user, login):
"""6R.20: venue.theme "identity" = the first colour of the venue's identity; bootstrap carries it and the logos."""
owner = login(make_user(role="owner"))
assert client.get("/api/platform/bootstrap").json()["venue"]["identity"]["colour"] is None
client.put("/api/identity", headers=owner, json={"colours": [{"name": "Main", "colour": "#1E3A8A"}], "slogan": "Since 1987"})
assert client.put("/api/settings/venue.theme", headers=owner, json={"value": "identity"}).status_code == 200
v = client.get("/api/platform/bootstrap").json()["venue"]
assert v["theme"] == "identity" and v["identity"]["colour"] == "#1e3a8a" and v["identity"]["slogan"] == "Since 1987" and v["identity"]["logo"] is None
+3
View File
@@ -98,10 +98,13 @@ def test_revert_payment_is_a_key_a_manager_can_approve(client, db, shop):
def test_price_change_needs_only_the_key_no_venue_switch(client, shop, login):
"""A sent line's price: ordering.prices.modify_sent since 6F.3 (modify alone is for the cart)."""
o, item = shop["order"], shop["items"][0]
url = f"/api/orders/{o.id}/items/{item.id}/price-adjust"
assert err(client.patch(url, headers=shop["h"], json={"price_adjustment": -1})) == "access.override_possible"
h = login(shop["new_waiter"](add=("ordering.prices.modify",)), client="waiter")
assert err(client.patch(url, headers=h, json={"price_adjustment": -1})) == "access.override_possible"
h = login(shop["new_waiter"](add=("ordering.prices.modify_sent",)), client="waiter")
r = client.patch(url, headers=h, json={"price_adjustment": -1})
assert r.status_code == 200, r.text
+4 -1
View File
@@ -6,6 +6,7 @@ import { lazy, Suspense } from 'react'
import { useQuery } from '@tanstack/react-query'
import { BrowserRouter, Routes, Route, Navigate, Outlet } from 'react-router-dom'
import { AccessProvider } from '@xenia/access'
import { VenueIdentity } from './shell/VenueIdentity'
import { createI18n } from '@xenia/i18n'
import { Spinner } from '@xenia/ui'
import useAuthStore from './store/authStore'
@@ -57,6 +58,7 @@ import PrepZonesPage from './pages/reports/prepzones/PrepZonesReport'
import ExpensesReportPage from './pages/reports/expenses/ExpensesReport'
import TechnicalPage from './pages/reports/technical/TechnicalReport'
import MiscPage from './pages/reports/misc/MiscReport'
import MovesPage from './pages/reports/moves/MovesReport'
// Other
import { AppsPage, IntegrationsPage } from './pages/platform/ModulesPage'
@@ -110,7 +112,7 @@ function ManagerRoot() {
return (
<AccessProvider client={client} token={token} i18n={i18n} loading={<Loading />}>
<AuthRehydrator>
<Outlet />
<VenueIdentity><Outlet /></VenueIdentity>
</AuthRehydrator>
</AccessProvider>
)
@@ -171,6 +173,7 @@ export default function App() {
<Route path="reports/expenses" element={<ExpensesReportPage />} />
<Route path="reports/technical" element={<TechnicalPage />} />
<Route path="reports/misc" element={<MiscPage />} />
<Route path="reports/moves" element={<MovesPage />} />
{/* ── Apps & Settings ── */}
<Route path="apps" element={<AppsPage />} />
@@ -5,7 +5,7 @@
import { useSearchParams } from 'react-router-dom'
import { useCan, useModule } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { Page, Tabs } from '@xenia/ui'
import { Columns, Page, Tabs } from '@xenia/ui'
import PrintingSettings from '../printing/PrintingSettings'
import CustomerDisplaySettings from './sections/CustomerDisplaySettings'
import DevelopmentSettings from './sections/DevelopmentSettings'
@@ -16,12 +16,14 @@ import SecuritySettings from './sections/SecuritySettings'
import SystemSettings from './sections/SystemSettings'
import TableColours from './sections/TableColours'
import VenueSettings from './sections/VenueSettings'
import IdentitySettings from './sections/IdentitySettings'
const TABS = {
'app-info': () => <SystemSettings />,
venue: () => <VenueSettings />,
venue: () => <Columns><VenueSettings /></Columns>,
identity: () => <IdentitySettings />,
'customer-display': () => <CustomerDisplaySettings />,
'menu-tablets': () => <MenuTabletSettings />,
'menu-tablets': () => <Columns><MenuTabletSettings /></Columns>,
security: () => <SecuritySettings />,
operation: () => <OperationSettings />,
colours: () => <TableColours />,
@@ -47,8 +49,8 @@ export default function SettingsPage() {
const active = tabs.includes(params.get('tab')) ? params.get('tab') : tabs[0]
const Tab = TABS[active]
return (
// settings are forms: the page's form width, centred (the page rule, 2026-11-20)
<Page testId="settings-page" width="form" aria-label={t('settings.title')}
// full width like every page (6F.0, owner 2026-11-23); each tab's cards sit in <Columns>
<Page testId="settings-page" aria-label={t('settings.title')}
top={<Tabs size="lg" value={active} onChange={id => setParams({ tab: id }, { replace: true })}
tabs={tabs.map(id => ({ id, label: t(`settings.tabs.${id}`), testId: `settings-tab-${id}` }))} />}>
<Tab />
@@ -138,6 +138,12 @@ export default function CustomerDisplaySettings() {
<option value="light">{t('display.themes.light')}</option>
</Select>
</Field>
<Field label={t('display.brand')} hint={t('display.brandHint')}>
<Select value={form.brand || 'own'} onChange={e => set('brand', e.target.value)} data-testid="display-brand">
<option value="own">{t('display.brands.own')}</option>
<option value="identity">{t('display.brands.identity')}</option>
</Select>
</Field>
{shows('slides') && (
<Field label={t('display.slideSeconds')}>
<Input inputMode="numeric" value={String(form.slide_seconds)} data-testid="display-slide-seconds"
@@ -1,7 +1,7 @@
// Settings → Development (plan step 6.14a; was the v1 DevelopmentTab): for testing only. Printing
// "spoof": every print job is dropped silently and the apps behave as if it printed.
import { useTranslation } from '@xenia/i18n'
import { Spinner, Switch } from '@xenia/ui'
import { Columns, Spinner, Switch } from '@xenia/ui'
import { SettingRow, SettingsCard } from './SettingsCard'
import { useSettings } from './useSettings'
@@ -11,13 +11,13 @@ export default function DevelopmentSettings() {
if (s.loading) return <div className="py-8 flex justify-center"><Spinner /></div>
const spoof = s.get('dev.spoof_printing', 'false') === 'true'
return (
<div className="grid gap-5" data-testid="settings-development">
<p className="rounded-card bg-danger-soft text-danger-ink p-3 text-label" role="note">{t('settings.dev.warning')}</p>
<Columns testId="settings-development">
<p className="x-columns__wide rounded-card bg-danger-soft text-danger-ink p-3 text-label" role="note">{t('settings.dev.warning')}</p>
<SettingsCard title={t('settings.dev.title')}>
<SettingRow label={t('settings.dev.spoof')} hint={t('settings.dev.spoofHint')} warning={spoof ? t('settings.dev.spoofOn') : undefined}>
<Switch checked={spoof} disabled={s.saving} onChange={v => s.save('dev.spoof_printing', v)} aria-label={t('settings.dev.spoof')} data-testid="setting-dev.spoof_printing" />
</SettingRow>
</SettingsCard>
</div>
</Columns>
)
}
@@ -9,7 +9,7 @@ import toast from 'react-hot-toast'
import { CheckCircle2, Plus, Trash2, XCircle } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Field, IconButton, Input, Select, Spinner, Switch } from '@xenia/ui'
import { Button, Columns, Field, IconButton, Input, Select, Spinner, Switch } from '@xenia/ui'
import client from '../../../api/client'
import { SettingRow, SettingsCard } from './SettingsCard'
import { cleanVatGroups, endLines, readJson } from './settingsLogic'
@@ -21,9 +21,9 @@ export default function FiscalSettings() {
if (s.loading) return <div className="py-8 flex justify-center"><Spinner /></div>
const on = s.get('fiscal.enabled', 'false') === 'true'
return (
<div className="grid gap-5" data-testid="settings-fiscal">
<Columns testId="settings-fiscal">
<SettingsCard title={t('settings.fiscal.title')} description={t('settings.fiscal.intro')}>
<SettingRow label={t('settings.fiscal.enabled')} hint={t('settings.fiscal.enabledHint')}
<SettingRow label={t('settings.fiscal.enabled')} hint={t('settings.fiscal.enabledHint')} tip={t('settings.fiscal.enabledTip')}
warning={on ? t('settings.fiscal.onWarning') : undefined}>
<Switch checked={on} disabled={s.saving} onChange={v => s.save('fiscal.enabled', v)} aria-label={t('settings.fiscal.enabled')} data-testid="setting-fiscal.enabled" />
</SettingRow>
@@ -37,7 +37,7 @@ export default function FiscalSettings() {
<Folders s={s} />
<EndMessage s={s} />
<VatGroups s={s} />
</div>
</Columns>
)
}
@@ -0,0 +1,146 @@
// Settings → Identity (6R.14, owner 2026-11-22): the venue's name and slogan, its colours (named),
// logos, guest Wi-Fi and contact details, edited together and saved at once (PUT /api/identity).
// Signage offers the colours first in every colour field and its widgets read the rest; the other
// apps follow it (6R.20) unless they have their own look.
import { useMemo, useState } from 'react'
import toast from 'react-hot-toast'
import { useQueryClient } from '@tanstack/react-query'
import { QRCodeSVG } from 'qrcode.react'
import { Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useCan } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { Button, ColourField, Columns, Dropdown, Field, IconButton, Input, Spinner, Switch } from '@xenia/ui'
import { wifiQr } from '@xenia/signage/logic'
import client from '../../../api/client'
import MediaField from '../../media/MediaField'
import { IDENTITY_KEY, useIdentity } from '../../../shell/useIdentity'
import { CONTACT, CONTACT_MAX, identityBody, LOGOS, MAX_COLOURS, newColour } from './identityLogic'
import { SettingsCard } from './SettingsCard'
export default function IdentitySettings() {
const { data } = useIdentity()
if (!data) return <div className="py-8 flex justify-center"><Spinner /></div>
return <IdentityForm saved={data} key={JSON.stringify(identityBody(data))} />
}
function IdentityForm({ saved }) {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const canEdit = useCan('core.settings.manage')
const [d, setD] = useState(() => structuredClone(saved))
const [busy, setBusy] = useState(false)
const dirty = useMemo(() => JSON.stringify(identityBody(d)) !== JSON.stringify(identityBody(saved)), [d, saved])
const set = patch => setD(x => ({ ...x, ...patch }))
const setIn = (part, patch) => setD(x => ({ ...x, [part]: { ...(x[part] || {}), ...patch } }))
const colours = d.colours || []
const setColour = (i, patch) => set({ colours: colours.map((c, j) => (j === i ? { ...c, ...patch } : c)) })
const bad = colours.some(c => !(c.name || '').trim())
const save = async () => {
setBusy(true)
try {
const { data: out } = await client.put('/api/identity', identityBody(d))
qc.setQueryData(IDENTITY_KEY, out)
qc.invalidateQueries({ queryKey: ['pos-settings'] })
toast.success(t('identity.saved'))
} catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false)
}
const wifi = d.wifi || {}
const qr = wifiQr(wifi)
return (
<Columns testId="settings-identity">
<div className="x-columns__wide flex flex-wrap items-center gap-3">
<p className="text-label text-ink-2 flex-1 min-w-[16rem]">{t('identity.intro')}</p>
{dirty && <span className="text-label text-ink-3">{t('identity.unsaved')}</span>}
<Button variant="secondary" disabled={!dirty || busy} onClick={() => setD(structuredClone(saved))}>{t('identity.undo')}</Button>
<Button loading={busy} disabled={!canEdit || !dirty || bad} onClick={save} data-testid="identity-save">{t('identity.save')}</Button>
</div>
<SettingsCard title={t('identity.name.title')} testId="identity-name">
<div className="p-5 grid gap-4 sm:grid-cols-2">
<Field label={t('identity.name.name')} hint={t('identity.name.nameHint')}>
<Input value={d.name || ''} maxLength={80} onChange={e => set({ name: e.target.value })} data-testid="identity-name-input" />
</Field>
<Field label={t('identity.name.slogan')} hint={t('identity.name.sloganHint')}>
<Input value={d.slogan || ''} maxLength={120} onChange={e => set({ slogan: e.target.value })} data-testid="identity-slogan" />
</Field>
</div>
</SettingsCard>
<SettingsCard title={t('identity.colours.title')} description={t('identity.colours.hint')} testId="identity-colours">
<div className="p-5 grid gap-3">
{colours.length === 0 && <p className="text-label text-ink-3">{t('identity.colours.none')}</p>}
{colours.map((c, i) => (
<div key={i} className="grid gap-3 grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] items-end" data-testid="identity-colour">
<Field label={t('identity.colours.name')} error={!(c.name || '').trim() ? ' ' : undefined}>
<Input value={c.name || ''} maxLength={40} onChange={e => setColour(i, { name: e.target.value })} data-testid="identity-colour-name" />
</Field>
<ColourField label={t('identity.colours.colour')} value={c.colour} onChange={v => setColour(i, { colour: v })} testId={`identity-colour-${i}`} />
<IconButton tone="danger" label={t('identity.colours.remove', { name: c.name || i + 1 })} onClick={() => set({ colours: colours.filter((_, j) => j !== i) })}>
<Trash2 size={16} />
</IconButton>
</div>
))}
<div className="flex items-center gap-3">
<Button variant="secondary" icon={<Plus size={16} />} disabled={colours.length >= MAX_COLOURS} data-testid="identity-colour-add"
onClick={() => set({ colours: [...colours, newColour(colours.length, t('identity.colours.newName', { n: colours.length + 1 }))] })}>
{t('identity.colours.add')}
</Button>
{colours.length >= MAX_COLOURS && <span className="text-caption text-ink-3">{t('identity.colours.max')}</span>}
</div>
</div>
</SettingsCard>
<SettingsCard title={t('identity.logos.title')} description={t('identity.logos.hint')} testId="identity-logos">
<div className="p-5 grid gap-5 sm:grid-cols-2">
{LOGOS.map(k => (
<MediaField key={k} label={t(`identity.logos.${k}`)} value={d.logos?.[k] || null} nameAfter={d.name}
onChange={img => setIn('logos', { [k]: img })} testid={`identity-logo-${k}`} />
))}
</div>
</SettingsCard>
<SettingsCard title={t('identity.wifi.title')} description={t('identity.wifi.hint')} testId="identity-wifi">
<div className="p-5 grid gap-5 md:grid-cols-[minmax(0,1fr)_auto]">
<div className="grid gap-4 sm:grid-cols-2 content-start">
<Field label={t('identity.wifi.ssid')}>
<Input value={wifi.ssid || ''} maxLength={32} onChange={e => setIn('wifi', { ssid: e.target.value })} data-testid="identity-wifi-ssid" />
</Field>
<Field label={t('identity.wifi.password')}>
<Input value={wifi.password || ''} maxLength={63} disabled={wifi.security === 'nopass'} onChange={e => setIn('wifi', { password: e.target.value })} data-testid="identity-wifi-password" />
</Field>
<Field label={t('identity.wifi.security')}>
<Dropdown value={wifi.security || 'WPA'} onChange={v => setIn('wifi', { security: v })} data-testid="identity-wifi-security"
options={['WPA', 'WEP', 'nopass'].map(v => ({ value: v, label: t(`identity.wifi.securities.${v}`) }))} />
</Field>
<Field label={t('identity.wifi.note')} hint={t('identity.wifi.noteHint')}>
<Input value={wifi.note || ''} maxLength={120} onChange={e => setIn('wifi', { note: e.target.value })} />
</Field>
<div className="sm:col-span-2">
<Switch checked={!!wifi.hidden} onChange={v => setIn('wifi', { hidden: v })} label={t('identity.wifi.hidden')} description={t('identity.wifi.hiddenHint')} />
</div>
</div>
{qr && (
<figure className="grid justify-items-center gap-2 content-start" data-testid="identity-wifi-qr" data-qr={qr}>
<div className="rounded-control bg-surface p-2 border border-line"><QRCodeSVG value={qr} size={136} /></div>
<figcaption className="text-caption text-ink-2">{t('identity.wifi.preview')}</figcaption>
</figure>
)}
</div>
</SettingsCard>
<SettingsCard title={t('identity.contact.title')} description={t('identity.contact.hint')} testId="identity-contact">
<div className="p-5 grid gap-4 sm:grid-cols-2">
{CONTACT.map(k => (
<Field key={k} label={t(`identity.contact.${k}`)} className={k === 'address' ? 'sm:col-span-2' : undefined}>
<Input value={d.contact?.[k] || ''} maxLength={CONTACT_MAX[k] || 200}
onChange={e => setIn('contact', { [k]: e.target.value })} data-testid={`identity-contact-${k}`} />
</Field>
))}
</div>
</SettingsCard>
</Columns>
)
}
@@ -4,14 +4,14 @@
// table flags, quick messages to the staff, and sending the digital menu to the cloud now.
// Each part shows only with its app on. Dropped from v1: "automatic store schedule" (its switches
// were kept in the browser only and nothing ever read them).
import { useState } from 'react'
import { useId, useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { ArrowDown, ArrowUp, Plus, RefreshCw, Trash2 } from 'lucide-react'
import { useModule } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, IconButton, Input, Spinner, Switch } from '@xenia/ui'
import { Button, Columns, IconButton, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui'
import client from '../../../api/client'
import QuickMessages from './QuickMessages'
import RolePermissions from './RolePermissions'
@@ -26,19 +26,19 @@ export default function OperationSettings() {
const chat = useModule('chat')
const qrMenu = useModule('connect_menu')
return (
<div className="grid gap-5" data-testid="settings-operation">
<Columns testId="settings-operation">
<RolePermissions />
{ordering && <OrderingSettings />}
{ordering && <TableFlags />}
{chat && <QuickMessages />}
{qrMenu && <MenuSync />}
</div>
</Columns>
)
}
function Toggle({ s, k, fallback = 'false', label, hint }) {
function Toggle({ s, k, fallback = 'false', label, hint, tip }) {
return (
<SettingRow label={label} hint={hint}>
<SettingRow label={label} hint={hint} tip={tip}>
<Switch checked={s.get(k, fallback) === 'true'} disabled={s.saving} onChange={v => s.save(k, v)} aria-label={label} data-testid={`setting-${k}`} />
</SettingRow>
)
@@ -51,24 +51,94 @@ function OrderingSettings() {
const o = k => t(`settings.ops.${k}`)
return (<>
<SettingsCard title={o('staffTitle')} description={o('staffIntro')} testId="settings-staff">
<Toggle s={s} k="shifts.waiter_self_start" fallback="true" label={o('selfStart')} hint={o('selfStartHint')} />
<Toggle s={s} k="shifts.waiter_self_end" fallback="true" label={o('selfEnd')} hint={o('selfEndHint')} />
<Toggle s={s} k="shifts.hide_revenue_from_waiters" label={o('hideTakings')} hint={o('hideTakingsHint')} />
<Toggle s={s} k="shifts.waiter_self_start" fallback="true" label={o('selfStart')} hint={o('selfStartHint')} tip={o('selfStartTip')} />
<Toggle s={s} k="shifts.waiter_self_end" fallback="true" label={o('selfEnd')} hint={o('selfEndHint')} tip={o('selfEndTip')} />
<Toggle s={s} k="shifts.hide_revenue_from_waiters" label={o('hideTakings')} hint={o('hideTakingsHint')} tip={o('hideTakingsTip')} />
</SettingsCard>
<SettingsCard title={o('paymentsTitle')} testId="settings-payments">
<Toggle s={s} k="payments.card_enabled" label={o('card')} hint={o('cardHint')} />
<Toggle s={s} k="payments.card_enabled" label={o('card')} hint={o('cardHint')} tip={o('cardTip')} />
</SettingsCard>
<SettingsCard title={o('ordersTitle')} description={o('ordersIntro')} testId="settings-orders">
<Toggle s={s} k="orders.auto_close_on_full_payment" label={o('autoClose')} hint={o('autoCloseHint')} />
<Toggle s={s} k="orders.close_with_unpaid" label={t('settings.operation.closeUnpaid')} hint={t('settings.operation.closeUnpaidHint')} />
<Toggle s={s} k="orders.bypass_kds_serve" label={o('bypassKds')} hint={o('bypassKdsHint')} />
<Toggle s={s} k="orders.courses_enabled" label={o('courses')} hint={o('coursesHint')} />
<Toggle s={s} k="orders.auto_close_on_full_payment" label={o('autoClose')} hint={o('autoCloseHint')} tip={o('autoCloseTip')} />
<Toggle s={s} k="orders.close_with_unpaid" label={t('settings.operation.closeUnpaid')} hint={t('settings.operation.closeUnpaidHint')} tip={t('settings.operation.closeUnpaidTip')} />
<Toggle s={s} k="orders.bypass_kds_serve" label={o('bypassKds')} hint={o('bypassKdsHint')} tip={o('bypassKdsTip')} />
<Toggle s={s} k="orders.courses_enabled" label={o('courses')} hint={o('coursesHint')} tip={o('coursesTip')} />
{s.get('orders.courses_enabled') === 'true' && <Courses s={s} />}
<QuickNotes s={s} />
<TextList s={s} k="orders.quick_notes" title={o('quickNotes')} hint={o('quickNotesHint')} tip={o('quickNotesTip')}
itemLabel={o('quickNote')} placeholder={o('newQuickNote')} testId="settings-quick-notes" newTestId="quick-note" />
</SettingsCard>
<PriceChangeSettings s={s} />
<QuantitySettings s={s} />
<SplitSettings s={s} />
</>)
}
/** Splitting a bill by amount (6F.6), each level with the ones before. Who may:
* ordering.payments.split_amount ("What each role may do", a person's permissions). */
function SplitSettings({ s }) {
const { t } = useTranslation('manager')
const q = k => t(`settings.split.${k}`)
const id = useId()
const maxId = useId()
const level = s.get('payments.split_amount', 'off')
return (
<SettingsCard title={q('title')} description={q('intro')} testId="settings-split">
<SettingRow label={q('when')} hint={q('whenHint')} tip={q('whenTip')} htmlFor={id}>
<Select id={id} value={level} disabled={s.saving} data-testid="setting-payments.split_amount"
onChange={e => s.save('payments.split_amount', e.target.value)}
options={['off', 'two_equal', 'two_custom', 'multiple_equal'].map(v => ({ value: v, label: q(`levels.${v}`) }))} />
</SettingRow>
{level === 'multiple_equal' && (
<SettingRow label={q('max')} hint={q('maxHint')} htmlFor={maxId}>
<Select id={maxId} value={String(s.get('payments.split_max_parts', '10'))} disabled={s.saving} data-testid="setting-payments.split_max_parts"
onChange={e => s.save('payments.split_max_parts', e.target.value)}
options={[3, 4, 5, 6, 8, 10, 12, 15, 20].map(n => ({ value: String(n), label: String(n) }))} />
</SettingRow>
)}
</SettingsCard>
)
}
/** A sent line's quantity changed without a new ticket (6F.5). Who may: ordering.items.change_quantity;
* lowering also needs ordering.orders.cancel ("What each role may do", a person's permissions). */
function QuantitySettings({ s }) {
const { t } = useTranslation('manager')
const q = k => t(`settings.quantity.${k}`)
const id = useId()
return (
<SettingsCard title={q('title')} description={q('intro')} testId="settings-quantity">
<SettingRow label={q('when')} hint={q('whenHint')} tip={q('whenTip')} htmlFor={id}>
<Select id={id} value={s.get('orders.quantity_change', 'off')} disabled={s.saving} data-testid="setting-orders.quantity_change"
onChange={e => s.save('orders.quantity_change', e.target.value)}
options={['off', 'add_only', 'add_and_remove'].map(v => ({ value: v, label: q(`modes.${v}`) }))} />
</SettingRow>
</SettingsCard>
)
}
/** Prices changed by hand (6F.3): the venue's switch, the reason, the quick reasons. Who may: the
* keys ordering.prices.modify / modify_sent ("What each role may do", a person's permissions). */
function PriceChangeSettings({ s }) {
const { t } = useTranslation('manager')
const p = k => t(`settings.prices.${k}`)
const id = useId()
const reasonOn = s.get('orders.price_change_reason', 'false') === 'true'
return (
<SettingsCard title={p('title')} description={p('intro')} testId="settings-price-changes">
<SettingRow label={p('when')} hint={p('whenHint')} tip={p('whenTip')} htmlFor={id}>
<Select id={id} value={s.get('orders.price_change', 'anytime')} disabled={s.saving} data-testid="setting-orders.price_change"
onChange={e => s.save('orders.price_change', e.target.value)}
options={['off', 'before_sending', 'anytime'].map(v => ({ value: v, label: p(`modes.${v}`) }))} />
</SettingRow>
{s.get('orders.price_change', 'anytime') !== 'off' && (<>
<Toggle s={s} k="orders.price_change_reason" label={p('reason')} hint={p('reasonHint')} tip={p('reasonTip')} />
{reasonOn && <TextList s={s} k="orders.price_change_reasons" title={p('reasons')} hint={p('reasonsHint')}
itemLabel={p('reasonItem')} placeholder={p('newReason')} testId="settings-price-reasons" newTestId="price-reason" />}
</>)}
</SettingsCard>
)
}
/** orders.courses: [{ id, name, color }] in the order they are served. */
function Courses({ s }) {
const { t } = useTranslation('manager')
@@ -94,29 +164,30 @@ function Courses({ s }) {
)
}
/** orders.quick_notes: the notes a waiter can add to a line with one tap. */
function QuickNotes({ s }) {
/** A JSON list of short texts in a setting (orders.quick_notes: notes a waiter adds to a line with
* one tap; orders.price_change_reasons: quick reasons for a price changed by hand, 6F.3). */
function TextList({ s, k, title, hint, tip, itemLabel, placeholder, testId, newTestId }) {
const { t } = useTranslation('manager')
const notes = readJson(s.get('orders.quick_notes', '[]'), [])
const notes = readJson(s.get(k, '[]'), [])
const [typed, setTyped] = useState('')
const [edits, setEdits] = useState({})
const save = next => s.save('orders.quick_notes', JSON.stringify(cleanNotes(next)))
const save = next => s.save(k, JSON.stringify(cleanNotes(next)))
const add = () => { if (typed.trim()) { save([...notes, typed]); setTyped('') } }
return (
<div className="px-5 py-3 grid gap-2" data-testid="settings-quick-notes">
<span className="text-body font-medium text-ink">{t('settings.ops.quickNotes')}</span>
<span className="text-label text-ink-2 -mt-1">{t('settings.ops.quickNotesHint')}</span>
<div className="px-5 py-3 grid gap-2" data-testid={testId}>
<span className="flex items-center gap-1 text-body font-medium text-ink">{title}{tip && <InfoTip>{tip}</InfoTip>}</span>
<span className="text-label text-ink-2 -mt-1">{hint}</span>
{notes.map((n, i) => (
<div key={`${i}-${n}`} className="flex items-center gap-2">
<Input value={edits[i] ?? n} aria-label={t('settings.ops.quickNote')} onChange={e => setEdits(x => ({ ...x, [i]: e.target.value }))}
<Input value={edits[i] ?? n} aria-label={itemLabel} onChange={e => setEdits(x => ({ ...x, [i]: e.target.value }))}
onBlur={() => { if (edits[i] != null && edits[i] !== n) save(notes.map((x, j) => (j === i ? edits[i] : x))); setEdits({}) }} />
<IconButton size="sm" variant="ghost" label={t('settings.ops.remove', { name: n })} onClick={() => save(notes.filter((_, j) => j !== i))}><Trash2 size={14} /></IconButton>
</div>
))}
<div className="flex items-center gap-2">
<Input value={typed} placeholder={t('settings.ops.newQuickNote')} aria-label={t('settings.ops.newQuickNote')} onChange={e => setTyped(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') add() }} data-testid="quick-note-new" />
<Button size="sm" variant="secondary" icon={<Plus size={14} />} disabled={!typed.trim()} onClick={add} data-testid="quick-note-add">{t('settings.ops.add')}</Button>
<Input value={typed} placeholder={placeholder} aria-label={placeholder} onChange={e => setTyped(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') add() }} data-testid={`${newTestId}-new`} />
<Button size="sm" variant="secondary" icon={<Plus size={14} />} disabled={!typed.trim()} onClick={add} data-testid={`${newTestId}-add`}>{t('settings.ops.add')}</Button>
</div>
</div>
)
@@ -8,7 +8,7 @@ import toast from 'react-hot-toast'
import { Copy, RefreshCw } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, IconButton, Select, Spinner, Switch } from '@xenia/ui'
import { Button, Columns, IconButton, Select, Spinner, Switch } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { Pill } from '../../overview/parts'
@@ -19,11 +19,11 @@ import { useSettings } from './useSettings'
export default function SecuritySettings() {
return (
<div className="grid gap-5" data-testid="settings-security">
<Columns testId="settings-security">
<SignInSettings />
<IdleSettings />
<RecoveryCodes />
</div>
</Columns>
)
}
@@ -39,7 +39,7 @@ function IdleSettings() {
const options = current => [...new Set([...IDLE_STEPS, current])].sort((a, b) => a - b).map(v => ({ value: String(v), label: span(v) }))
return (
<SettingsCard title={t('settings.security.idleTitle')} description={t('settings.security.idleIntro')} testId="settings-idle">
<SettingRow label={t('settings.security.lock')} hint={t('settings.security.lockHint')}>
<SettingRow label={t('settings.security.lock')} hint={t('settings.security.lockHint')} tip={t('settings.security.lockTip')}>
<Switch checked={lock} disabled={s.saving} onChange={v => s.save('security.auto_lock', v)} aria-label={t('settings.security.lock')} data-testid="setting-security.auto_lock" />
</SettingRow>
{lock && (
@@ -25,7 +25,7 @@ export function SettingRow({ label, hint, tip, children, warning, htmlFor }) {
</div>
{hint && <p className="text-label text-ink-2 mt-0.5">{hint}</p>}
</div>
<div className="sm:w-64 shrink-0">{children}</div>
<div className="sm:w-64 shrink-0 flex sm:justify-end [&>*]:max-w-full [&>.x-select]:w-full [&>.x-dropdown]:w-full [&>.x-input]:w-full">{children}</div>
</div>
{warning && <p className="mt-2 rounded-control bg-warning-soft text-warning-ink text-label px-3 py-2" role="note">{warning}</p>}
</div>
@@ -46,23 +46,23 @@ export default function SignInSettings() {
<SettingRow label={t('settings.signIn.autofill')} hint={t('settings.signIn.autofillHint')}>
{toggle('security.autofill_username', 'true', t('settings.signIn.autofill'))}
</SettingRow>
<SettingRow label={t('settings.signIn.waiter')} htmlFor={idWaiter}
<SettingRow label={t('settings.signIn.waiter')} htmlFor={idWaiter} tip={t('settings.signIn.waiterTip')}
warning={waiterMode === 'tap' ? t('settings.signIn.waiterTapWarning') : undefined}>
{select('auth.waiter_login_mode', 'pin', opts(['pin', 'password', 'tap'], 'settings.mode'), idWaiter)}
</SettingRow>
<SettingRow label={t('settings.signIn.requireUsername')} hint={t('settings.signIn.requireUsernameHint')}>
<SettingRow label={t('settings.signIn.requireUsername')} hint={t('settings.signIn.requireUsernameHint')} tip={t('settings.signIn.requireUsernameTip')}>
{toggle('auth.waiter_require_username', 'false', t('settings.signIn.requireUsername'))}
</SettingRow>
<SettingRow label={t('settings.signIn.device')} htmlFor={idDevice} hint={t('settings.signIn.deviceHint')}>
<SettingRow label={t('settings.signIn.device')} htmlFor={idDevice} hint={t('settings.signIn.deviceHint')} tip={t('settings.signIn.deviceTip')}>
{select('auth.default_login_mode', 'pin', opts(['pin', 'password', 'tap', 'none'], 'settings.mode'), idDevice)}
</SettingRow>
<SettingRow label={t('settings.signIn.singleManager')} htmlFor={idSingleManager} tip={t('settings.signIn.singleTip')}>
{select('auth.single_session_manager', 'off', opts(SESSION_RULES, 'settings.session'), idSingleManager)}
</SettingRow>
<SettingRow label={t('settings.signIn.singleWaiter')} htmlFor={idSingleWaiter}>
<SettingRow label={t('settings.signIn.singleWaiter')} htmlFor={idSingleWaiter} tip={t('settings.signIn.singleTip')}>
{select('auth.single_session_waiter', 'off', opts(SESSION_RULES, 'settings.session'), idSingleWaiter)}
</SettingRow>
<SettingRow label={t('settings.signIn.idle')} htmlFor={idIdle} hint={t('settings.signIn.idleHint')}>
<SettingRow label={t('settings.signIn.idle')} htmlFor={idIdle} hint={t('settings.signIn.idleHint')} tip={t('settings.signIn.idleTip')}>
{select('auth.idle_days', '14', idleOptions, idIdle)}
</SettingRow>
</SettingsCard>
@@ -10,7 +10,7 @@ import { Lock, LockOpen, QrCode as QrIcon, RefreshCw } from 'lucide-react'
import { useAccess } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Input, Spinner } from '@xenia/ui'
import { Button, Columns, Dialog, Input, Spinner } from '@xenia/ui'
import { QrCode } from '@xenia/ui/qr'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
@@ -43,7 +43,7 @@ export default function SystemSettings() {
const counts = ['categories', 'products', 'tables', 'table_groups', 'managers', 'waiters']
return (
<div className="grid gap-5" data-testid="settings-system">
<Columns testId="settings-system">
<SettingsCard title={t('settings.system.title')}>
<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">
@@ -106,7 +106,7 @@ export default function SystemSettings() {
</div>
</Dialog>
)}
</div>
</Columns>
)
}
@@ -132,7 +132,7 @@ function LanAccess({ status, onQr }) {
</Button>
</div>
)}
<SettingRow label={t('settings.lan.address')} hint={!ip ? t('settings.lan.unknown') : info && info.detection !== 'ok' && editing == null ? t(`settings.lan.detection.${info.detection}`, { defaultValue: '' }) : undefined}>
<SettingRow label={t('settings.lan.address')} tip={t('settings.lan.addressTip')} hint={!ip ? t('settings.lan.unknown') : info && info.detection !== 'ok' && editing == null ? t(`settings.lan.detection.${info.detection}`, { defaultValue: '' }) : undefined}>
{editing != null ? (
<span className="grid gap-2">
<Input value={editing} autoFocus className="font-mono" placeholder={info?.detected || '192.168.1.50'} onChange={e => setEditing(e.target.value)}
@@ -6,7 +6,7 @@
import { useEffect, useState } from 'react'
import { RotateCcw } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Spinner, Switch } from '@xenia/ui'
import { Button, Dialog, Field, Input, Slider, Spinner, Switch } from '@xenia/ui'
import { SettingsCard } from './SettingsCard'
import { buildColour, mergeColours, parseColour, readJson, setSlot } from './settingsLogic'
import { useSettings } from './useSettings'
@@ -137,9 +137,7 @@ function ColourDialog({ slot, value, title, onClose, onSave }) {
<Input value={hex} spellCheck={false} className="font-mono" onChange={e => setHex(e.target.value.trim())} data-testid="colour-hex" />
</span>
</Field>
<Field label={`${t('settings.colours.opacity')} · ${Math.round(alpha * 100)}%`}>
<input type="range" min={0} max={1} step={0.01} value={alpha} onChange={e => setAlpha(Number(e.target.value))} className="w-full accent-accent" />
</Field>
<Slider label={t('settings.colours.opacity')} value={Math.round(alpha * 100)} min={0} max={100} suffix="%" onChange={v => setAlpha(v / 100)} />
<Field label={t('settings.colours.quick')}>
<span className="flex flex-wrap gap-1.5">
{(QUICK_SWATCHES[slot] ?? []).map(c => (
@@ -1,22 +1,25 @@
// Venue language and time zone (plan step 2.6f, D-11, D-12): venue.language is the
// language of staff without their own choice and of printed tickets/reports; venue.timezone
// is the zone every time is shown in (applies at once); venue.theme is the staff apps' accent
// colour (plan step 4.6: the waiter's phones). All reload bootstrap after saving.
// colour (plan step 4.6: the waiter's phones; 6R.20: "The venue's identity" = its first colour, for
// the phones and every screen of the terminal). All reload bootstrap after saving.
import { useId, useMemo } from 'react'
import { useAccess } from '@xenia/access'
import { LANGUAGE_NAMES, useTranslation, useFormat } from '@xenia/i18n'
import { Select, Spinner } from '@xenia/ui'
import { SettingRow, SettingsCard } from './SettingsCard'
import { useSettings } from './useSettings'
import { useIdentity } from '../../../shell/useIdentity'
import { timeZones } from './timeZones'
const VENUE_THEMES = ['amber', 'teal', 'blue', 'violet', 'rose'] // packages/ui tokens.css data-venue-theme
const VENUE_THEMES = ['amber', 'teal', 'blue', 'violet', 'rose', 'identity'] // packages/ui tokens.css data-venue-theme; identity: venueAccent.js
export default function VenueSettings() {
const { t } = useTranslation('manager')
const f = useFormat()
const { languages } = useAccess()
const s = useSettings()
const { data: identity } = useIdentity()
const langId = useId()
const tzId = useId()
const themeId = useId()
@@ -26,18 +29,19 @@ export default function VenueSettings() {
return (
<SettingsCard title={t('settings.venue.title')} testId="settings-venue">
<SettingRow label={t('settings.venue.language')} htmlFor={langId} hint={t('settings.venue.languageHint')}>
<SettingRow label={t('settings.venue.language')} htmlFor={langId} hint={t('settings.venue.languageHint')} tip={t('settings.venue.languageTip')}>
<Select id={langId} value={s.get('venue.language', 'en')} disabled={s.saving} data-testid="setting-venue.language"
onChange={e => s.save('venue.language', e.target.value)}
options={(languages || ['en', 'el']).map(l => ({ value: l, label: LANGUAGE_NAMES[l] || l }))} />
</SettingRow>
<SettingRow label={t('settings.venue.timezone')} htmlFor={tzId}
<SettingRow label={t('settings.venue.timezone')} htmlFor={tzId} tip={t('settings.venue.timezoneTip')}
hint={t('settings.venue.timezoneHint', { time: f.formatTime(new Date()) })}>
<Select id={tzId} value={tz} disabled={s.saving} data-testid="setting-venue.timezone"
onChange={e => s.save('venue.timezone', e.target.value)}
options={zones.map(z => ({ value: z, label: z.replace(/_/g, ' ') }))} />
</SettingRow>
<SettingRow label={t('settings.venue.theme')} htmlFor={themeId} hint={t('settings.venue.themeHint')}>
<SettingRow label={t('settings.venue.theme')} htmlFor={themeId} hint={t('settings.venue.themeHint')}
warning={s.get('venue.theme') === 'identity' && !identity?.colours?.length ? t('settings.venue.identityNoColour') : undefined}>
<Select id={themeId} value={s.get('venue.theme', 'amber')} disabled={s.saving} data-testid="setting-venue.theme"
onChange={e => s.save('venue.theme', e.target.value)}
options={VENUE_THEMES.map(v => ({ value: v, label: t(`settings.venue.themes.${v}`) }))} />
@@ -0,0 +1,20 @@
// The identity form's pure helpers (6R.14), unit-tested in tests/identity.test.mjs. The new
// colours' defaults are data (the venue's own colours), so this file is in the colour guard's DATA.
export const LOGOS = ['main', 'light', 'dark', 'icon']
export const CONTACT = ['phone', 'phone2', 'email', 'address', 'website', 'google', 'facebook', 'instagram', 'tiktok', 'tripadvisor', 'whatsapp', 'viber']
export const CONTACT_MAX = { phone: 40, phone2: 40, whatsapp: 40, viber: 40, email: 120, google: 300 } // else 200 (routers/identity.py)
export const MAX_COLOURS = 12
/** A new colour: the first a deep blue, the next ones white (the owner changes them). */
export const newColour = (n, name) => ({ name, colour: n === 0 ? '#1e3a8a' : '#ffffff' })
/** The identity as PUT /api/identity takes it (logos as media ids, empty texts as null). */
export function identityBody(d) {
return {
name: (d.name || '').trim(), slogan: (d.slogan || '').trim() || null,
colours: (d.colours || []).map(c => ({ name: (c.name || '').trim(), colour: c.colour })),
logos: Object.fromEntries(LOGOS.map(k => [k, d.logos?.[k]?.id ?? null])),
wifi: { ssid: d.wifi?.ssid || null, password: d.wifi?.password || null, security: d.wifi?.security || 'WPA', hidden: !!d.wifi?.hidden, note: d.wifi?.note || null },
contact: Object.fromEntries(CONTACT.map(k => [k, (d.contact?.[k] || '').trim() || null])),
}
}
@@ -23,7 +23,7 @@ import {
nearestEdge, outlineOf, removeCorner, resizeBox, toPlan,
} from '@xenia/floorplan'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Dropdown, Field, IconButton, Input, Segmented, Stepper, Switch, cx } from '@xenia/ui'
import { Button, Dialog, Dropdown, Field, IconButton, Input, Segmented, Slider, Stepper, Switch, cx } from '@xenia/ui'
import MediaField from '../media/MediaField'
import * as api from './floorApi'
import { WALL_THICKNESS, addItem, addable, cellOf, find, fitOutline, layoutBody, layoutOf, nudge, placeTable, planBody, remove, resizeCells, rotate, sameLayout, toCells, update } from './editorLogic'
@@ -329,9 +329,8 @@ export default function FloorEditor({ plan: saved, data, groups, onSaved, onDele
</div>
<MediaField value={form.background} onChange={img => setF('background', img)} label={t('floor.background')} testid="floor-background" />
{form.background && (
<label className="grid gap-1 text-label text-ink-2">{t('floor.backgroundOpacity', { value: Math.round((form.background_opacity ?? 0.6) * 100) })}
<input type="range" min="0.1" max="1" step="0.05" value={form.background_opacity ?? 0.6} onChange={e => setF('background_opacity', Number(e.target.value))} />
</label>
<Slider label={t('floor.backgroundOpacityLabel')} value={Math.round((form.background_opacity ?? 0.6) * 100)} min={10} max={100} step={5} suffix="%"
onChange={v => setF('background_opacity', v / 100)} />
)}
<Button size="sm" variant="ghost" icon={<Trash2 size={16} />} onClick={() => setDeleting(true)} className="justify-self-start text-danger-ink">{t('floor.delete')}</Button>
</Panel>
@@ -6,11 +6,11 @@ import toast from 'react-hot-toast'
import { Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Spinner, cx } from '@xenia/ui'
import { deleteMedia, getMedia, renameMedia } from './mediaApi'
import { Button, Dialog, Dropdown, Field, Input, Spinner, cx } from '@xenia/ui'
import { deleteMedia, getMedia, renameMedia, setFolder } from './mediaApi'
import { duration, fileSize, preparing, resolution, VARIANT_ORDER, videoState } from './mediaLogic'
export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {
export default function MediaDetails({ id, onClose, onChanged, onDeleted, folders = [] }) {
const { t } = useTranslation('manager')
const { formatDateTime, formatNumber } = useFormat()
const [item, setItem] = useState(null)
@@ -43,6 +43,10 @@ export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {
catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false)
}
const fileIn = async folderId => {
try { const m = await setFolder(id, folderId); setItem(it => ({ ...it, ...m })); onChanged?.(m); toast.success(t('media.folders.moved')) }
catch (err) { toast.error(errorMessage(err, t)) }
}
const remove = async () => {
setBusy(true)
try { await deleteMedia(id); toast.success(t('media.deleted')); onDeleted?.(id); onClose() }
@@ -93,6 +97,11 @@ export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {
<p className="text-caption text-ink-3">{t(item.builtin ? 'media.builtinHint' : 'media.displayNameHint')}</p>
</div>
<Field label={t('media.folders.folder')} className="max-w-sm">
<Dropdown value={item.folder_id ?? ''} onChange={v => fileIn(v === '' ? null : Number(v))} data-testid="media-folder-pick"
options={[{ value: '', label: t('media.folders.none') }, ...folders.map(f => ({ value: f.id, label: f.name }))]} />
</Field>
<dl className="grid gap-x-4 gap-y-1 text-label" style={{ gridTemplateColumns: 'max-content 1fr' }}>
{rows.map(([k, v]) => <div key={k} className="contents"><dt className="text-ink-3">{k}</dt><dd className="text-ink break-all">{v}</dd></div>)}
</dl>
@@ -0,0 +1,57 @@
// The media library's folders (6R.16, owner 2026-11-22): only a grouping in the database, the files
// stay where they are. The bar picks what the page shows (everything, the files in no folder, a
// folder) and where uploads go; a folder is made, renamed or deleted here (its files stay, in no folder).
import { useState } from 'react'
import toast from 'react-hot-toast'
import { FolderPlus, Pencil, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, FilterChip, IconButton, Input, useConfirm } from '@xenia/ui'
import { createFolder, deleteFolder, renameFolder } from './mediaApi'
/** value: '' (all) | 'none' | a folder id as a string. */
export default function MediaFolders({ folders, none, total, value, onChange, onChanged }) {
const { t } = useTranslation('manager')
const [naming, setNaming] = useState(null) // { id?, name }
const [confirm, confirmDialog] = useConfirm()
const current = folders?.find(f => String(f.id) === value)
const save = async () => {
try {
const f = naming.id ? await renameFolder(naming.id, naming.name.trim()) : await createFolder(naming.name.trim())
setNaming(null)
await onChanged?.()
onChange(String(f.id))
} catch (err) { toast.error(errorMessage(err, t)) }
}
const remove = async () => {
if (!await confirm({ title: t('media.folders.deleteTitle', { name: current.name }), body: t('media.folders.deleteBody'), confirmLabel: t('media.delete'), tone: 'danger', testId: 'media-folder-delete-confirm' })) return
try { await deleteFolder(current.id); onChange(''); await onChanged?.() } catch (err) { toast.error(errorMessage(err, t)) }
}
return (
<div className="flex flex-wrap items-center gap-1.5" data-testid="media-folders" role="toolbar" aria-label={t('media.folders.title')}>
<FilterChip pressed={value === ''} count={total} onClick={() => onChange('')} data-testid="media-folder-all">{t('media.folders.all')}</FilterChip>
<FilterChip pressed={value === 'none'} count={none} onClick={() => onChange('none')} data-testid="media-folder-none">{t('media.folders.none')}</FilterChip>
{(folders || []).map(f => (
<FilterChip key={f.id} pressed={value === String(f.id)} count={f.count} onClick={() => onChange(String(f.id))} data-testid="media-folder" data-name={f.name}>{f.name}</FilterChip>
))}
<Button size="sm" variant="ghost" icon={<FolderPlus size={15} />} onClick={() => setNaming({ name: '' })} data-testid="media-folder-new">{t('media.folders.new')}</Button>
{current && <>
<IconButton size="sm" label={t('media.folders.rename')} onClick={() => setNaming({ id: current.id, name: current.name })} data-testid="media-folder-rename"><Pencil size={15} /></IconButton>
<IconButton size="sm" tone="danger" label={t('media.folders.delete')} onClick={remove} data-testid="media-folder-delete"><Trash2 size={15} /></IconButton>
</>}
{naming && (
<Dialog open size="sm" title={t(naming.id ? 'media.folders.rename' : 'media.folders.new')} onClose={() => setNaming(null)}
footer={<>
<Button variant="secondary" onClick={() => setNaming(null)}>{t('fees.cancel')}</Button>
<Button disabled={!naming.name.trim()} onClick={save} data-testid="media-folder-save">{t('fees.save')}</Button>
</>}>
<Field label={t('media.folders.name')}>
<Input value={naming.name} autoFocus maxLength={60} onChange={e => setNaming(n => ({ ...n, name: e.target.value }))}
onKeyDown={e => { if (e.key === 'Enter' && naming.name.trim()) save() }} data-testid="media-folder-name" />
</Field>
</Dialog>
)}
{confirmDialog}
</div>
)
}
@@ -2,13 +2,15 @@
// library. Batch upload (pick many files or drop them on the page) to use later anywhere that
// takes media (products, categories; the customer display and signage next). The backend names
// and stores the files; here people see a display name, the details and the sizes made.
// Backend: /api/media (routers/media.py).
// Folders (6R.16): the bar under the toolbar picks a folder (uploads go into it); a file's folder is
// changed in its details. Backend: /api/media (routers/media.py).
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Upload } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, EmptyState, Input, Page, Select, Spinner, cx } from '@xenia/ui'
import { listMedia } from './mediaApi'
import { listFolders, listMedia } from './mediaApi'
import MediaFolders from './MediaFolders'
import { ACCEPT, preparing } from './mediaLogic'
import MediaDetails from './MediaDetails'
import { MediaGrid, UploadQueue } from './MediaParts'
@@ -24,13 +26,17 @@ export default function MediaPage() {
const [error, setError] = useState(null)
const [open, setOpen] = useState(null)
const [dragging, setDragging] = useState(false)
const [folder, setFolder] = useState('') // '' all | 'none' | a folder id
const [folders, setFolders] = useState(null) // { folders, none }
const loadFolders = useCallback(async () => { try { setFolders(await listFolders()) } catch { /* the bar waits */ } }, [])
useEffect(() => { loadFolders() }, [loadFolders])
const input = useRef(null)
useEffect(() => { const h = setTimeout(() => setSearch(q.trim()), 250); return () => clearTimeout(h) }, [q])
const load = useCallback(async () => {
try { setPage(await listMedia({ kind, q: search, collection })); setError(null) } catch (err) { setError(errorMessage(err, t)) }
}, [kind, search, collection, t])
try { setPage(await listMedia({ kind, q: search, collection, folder })); setError(null) } catch (err) { setError(errorMessage(err, t)) }
}, [kind, search, collection, folder, t])
useEffect(() => { load() }, [load])
// Videos are prepared for screens in the background (5.4e): read the list again while any is.
const busy = preparing(page?.items)
@@ -45,16 +51,18 @@ export default function MediaPage() {
setPage(p => (p && !p.items.some(x => x.id === item.id) ? { ...p, items: [item, ...p.items], total: p.total + 1 } : p))
}, []))
const wasBusy = useRef(false)
useEffect(() => { if (wasBusy.current && !summary.busy) load(); wasBusy.current = summary.busy }, [summary.busy, load])
useEffect(() => { if (wasBusy.current && !summary.busy) { load(); loadFolders() } wasBusy.current = summary.busy }, [summary.busy, load, loadFolders])
const onDrop = e => {
e.preventDefault(); setDragging(false)
if (e.dataTransfer.files?.length) add(e.dataTransfer.files)
if (e.dataTransfer.files?.length) add(e.dataTransfer.files, upTo)
}
const kinds = useMemo(() => [
{ value: '', label: t('media.kinds.all') }, { value: 'image', label: t('media.kinds.images') }, { value: 'video', label: t('media.kinds.videos') },
], [t])
const closeDetails = useCallback(() => setOpen(null), [])
const upTo = /^\d+$/.test(folder) ? Number(folder) : null // uploads go into the folder shown
const allCount = folders ? folders.none + folders.folders.reduce((n, f) => n + f.count, 0) : undefined
return (
<Page className={cx(dragging && 'outline-2 outline-dashed outline-accent -outline-offset-8')}
@@ -70,7 +78,7 @@ export default function MediaPage() {
<div className="flex flex-wrap gap-2 items-center">
<Button icon={<Upload size={16} />} onClick={() => input.current?.click()} data-testid="media-upload">{t('media.upload')}</Button>
<input ref={input} type="file" multiple accept={ACCEPT} className="sr-only" data-testid="media-file-input"
onChange={e => { if (e.target.files?.length) add(e.target.files); e.target.value = '' }} />
onChange={e => { if (e.target.files?.length) add(e.target.files, upTo); e.target.value = '' }} />
<span className="text-label text-ink-3 hidden md:inline">{t('media.dropHint')}</span>
<div className="flex gap-2 ml-auto w-full sm:w-auto">
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('media.search')} aria-label={t('media.search')}
@@ -81,6 +89,8 @@ export default function MediaPage() {
</div>
</div>
<MediaFolders folders={folders?.folders} none={folders?.none} total={allCount} value={folder} onChange={setFolder} onChanged={loadFolders} />
<UploadQueue queue={queue} summary={summary} onClear={clear} />
{error ? <EmptyState title={error} />
@@ -92,8 +102,8 @@ export default function MediaPage() {
{page.total > page.items.length && <p className="text-label text-ink-3">{t('media.more', { shown: page.items.length, total: page.total })}</p>}
</>}
{open && <MediaDetails id={open} onClose={closeDetails}
onChanged={m => setPage(p => p && { ...p, items: p.items.map(x => (x.id === m.id ? { ...x, ...m } : x)) })}
{open && <MediaDetails id={open} onClose={closeDetails} folders={folders?.folders || []}
onChanged={m => { setPage(p => p && { ...p, items: p.items.map(x => (x.id === m.id ? { ...x, ...m } : x)) }); loadFolders() }}
onDeleted={id => setPage(p => p && { ...p, items: p.items.filter(x => x.id !== id), total: p.total - 1 })} />}
</Page>
)
@@ -6,7 +6,7 @@ import { Upload } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Input, Select, Spinner } from '@xenia/ui'
import { listMedia } from './mediaApi'
import { listFolders, listMedia } from './mediaApi'
import { ACCEPT } from './mediaLogic'
import { MediaGrid, UploadQueue } from './MediaParts'
import { useUploadQueue } from './mediaHooks'
@@ -22,13 +22,16 @@ export default function MediaPicker({ open, onClose, onPick, onPickMany, multipl
const [chosen, setChosen] = useState([]) // multiple: the items picked so far, in order
const toggle = item => setChosen(c => (c.some(x => x.id === item.id) ? c.filter(x => x.id !== item.id) : [...c, item]))
const [folder, setFolder] = useState('') // 6R.16: '' all | 'none' | a folder id
const [folders, setFolders] = useState([])
useEffect(() => { if (open) listFolders().then(r => setFolders(r.folders)).catch(() => {}) }, [open])
useEffect(() => { const h = setTimeout(() => setSearch(q.trim()), 250); return () => clearTimeout(h) }, [q])
useEffect(() => {
if (!open) return
let live = true
listMedia({ kind, q: search, collection }).then(p => { if (live) { setPage(p); setError(null) } }).catch(err => live && setError(errorMessage(err, t)))
listMedia({ kind, q: search, collection, folder }).then(p => { if (live) { setPage(p); setError(null) } }).catch(err => live && setError(errorMessage(err, t)))
return () => { live = false }
}, [open, kind, search, collection, t])
}, [open, kind, search, collection, folder, t])
const { queue, add, clear, summary } = useUploadQueue(useCallback(item => {
setPage(p => (p && !p.items.some(x => x.id === item.id) ? { ...p, items: [item, ...p.items], total: p.total + 1 } : p))
@@ -49,9 +52,13 @@ export default function MediaPicker({ open, onClose, onPick, onPickMany, multipl
className="flex-1 min-w-[10rem]" data-testid="media-picker-search" />
<Select value={collection} onChange={e => setCollection(e.target.value)} aria-label={t('media.collection')} data-testid="media-picker-collection"
options={[{ value: '', label: t('media.collections.all') }, { value: 'own', label: t('media.collections.own') }, { value: 'builtin', label: t('media.collections.builtin') }]} />
{folders.length > 0 && (
<Select value={folder} onChange={e => setFolder(e.target.value)} aria-label={t('media.folders.folder')} data-testid="media-picker-folder"
options={[{ value: '', label: t('media.folders.all') }, { value: 'none', label: t('media.folders.none') }, ...folders.map(f => ({ value: String(f.id), label: f.name }))]} />
)}
<Button variant="secondary" icon={<Upload size={16} />} onClick={() => input.current?.click()} disabled={summary.busy}>{t('media.uploadNew')}</Button>
<input ref={input} type="file" accept={kind === 'image' ? ACCEPT.split(',').filter(a => a.startsWith('image/')).join(',') : ACCEPT}
className="sr-only" data-testid="media-picker-file" multiple={multiple} onChange={e => { if (e.target.files?.length) add(multiple ? e.target.files : [e.target.files[0]]); e.target.value = '' }} />
className="sr-only" data-testid="media-picker-file" multiple={multiple} onChange={e => { if (e.target.files?.length) add(multiple ? e.target.files : [e.target.files[0]], /^\d+$/.test(folder) ? Number(folder) : null); e.target.value = '' }} />
</div>
<UploadQueue queue={queue} summary={summary} onClear={clear} />
{error ? <EmptyState title={error} />
+12 -3
View File
@@ -1,16 +1,17 @@
// The media library's API (backend: local_backend/routers/media.py, plan steps 5.1 / 5.2).
import client from '../../api/client'
export const listMedia = ({ kind, q, collection, limit = 500 } = {}) =>
client.get('/api/media', { params: { kind: kind || undefined, q: q || undefined, collection: collection || undefined, limit } }).then(r => r.data)
export const listMedia = ({ kind, q, collection, folder, limit = 500 } = {}) =>
client.get('/api/media', { params: { kind: kind || undefined, q: q || undefined, collection: collection || undefined, folder: folder || undefined, limit } }).then(r => r.data)
export const getMedia = id => client.get(`/api/media/${id}`).then(r => r.data)
/** Upload one file → the library item (`existing: true` when the same file was already there). */
export function uploadMedia(file, { name, onProgress } = {}) {
export function uploadMedia(file, { name, folderId, onProgress } = {}) {
const fd = new FormData()
fd.append('file', file)
if (name) fd.append('name', name)
if (folderId) fd.append('folder_id', String(folderId))
return client.post('/api/media', fd, {
onUploadProgress: e => { if (onProgress && e.total) onProgress(Math.round((e.loaded / e.total) * 100)) },
}).then(r => r.data)
@@ -19,3 +20,11 @@ export function uploadMedia(file, { name, onProgress } = {}) {
export const renameMedia = (id, name) => client.patch(`/api/media/${id}`, { name }).then(r => r.data)
export const deleteMedia = id => client.delete(`/api/media/${id}`)
// folders (6R.16): only a grouping in the database; the files stay where they are
export const listFolders = () => client.get('/api/media/folders').then(r => r.data)
export const createFolder = name => client.post('/api/media/folders', { name }).then(r => r.data)
export const renameFolder = (id, name) => client.patch(`/api/media/folders/${id}`, { name }).then(r => r.data)
export const deleteFolder = id => client.delete(`/api/media/folders/${id}`)
export const moveMedia = (ids, folderId) => client.post('/api/media/move', { ids, folder_id: folderId ?? null }).then(r => r.data)
export const setFolder = (id, folderId) => client.patch(`/api/media/${id}`, { folder_id: folderId ?? null }).then(r => r.data)
@@ -27,8 +27,8 @@ export function useUploadQueue(onDone) {
useEffect(() => { done.current = onDone })
const counter = useRef(0)
const add = useCallback(files => {
const list = queueFrom(files, counter.current)
const add = useCallback((files, folderId = null) => {
const list = queueFrom(files, counter.current).map(x => ({ ...x, folderId }))
counter.current += list.length
setQueue(q => [...q, ...list])
}, [])
@@ -41,7 +41,7 @@ export function useUploadQueue(onDone) {
running.current = true
const set = patch => setQueue(q => q.map(x => (x.key === next.key ? { ...x, ...patch } : x)))
set({ status: 'uploading' })
uploadMedia(next.file, { onProgress: progress => set({ progress }) })
uploadMedia(next.file, { folderId: next.folderId, onProgress: progress => set({ progress }) })
.then(item => { set({ status: item.existing ? 'existing' : 'added', progress: 100, item }); done.current?.(item, !!item.existing) })
.catch(err => set({ status: 'failed', error: errorMessage(err, t) }))
.finally(() => { running.current = false; setQueue(q => [...q]) })
@@ -2,11 +2,12 @@
// evaluated by the backend's engine (local_backend/services/fees.py, the same file the cloud
// runs); this file only turns forms into request bodies and rules into readable lines.
// Pure: unit-tested in Node (tests/fees.test.mjs).
import { parseNumber } from '@xenia/i18n/number'
export const ACTIONS = ['set', 'add', 'percent', 'free', 'minimum']
export const DAYS = [0, 1, 2, 3, 4, 5, 6] // Monday = 0
const num = v => (v === '' || v == null ? null : Number(String(v).replace(',', '.')))
const num = v => (v === '' || v == null ? null : (parseNumber(String(v)) ?? NaN))
/** Postcodes typed with commas, semicolons or new lines → a tidy list without duplicates. */
export function parsePostcodes(text) {
@@ -4,7 +4,7 @@
import { useFormat, useTranslation } from '@xenia/i18n'
import { EmptyState, cx } from '@xenia/ui'
import { Pill } from '../overview/parts'
import { nameOf } from './orderLogic'
import { nameOf, pathText } from './orderLogic'
const EVENT_TONE = { PAYMENT: 'success', PAYMENT_OFFLINE: 'success', ORDER_CLOSED: 'neutral', ORDER_CANCELLED: 'danger', ITEM_CANCELLED: 'danger' }
const ids = raw => { try { return raw ? JSON.parse(raw) : [] } catch { return [] } }
@@ -59,6 +59,8 @@ export function PriceEventList({ events }) {
<span className="flex flex-wrap gap-x-3">
{(ev.modifier_name || ev.deal_name) && <span className="font-semibold">{ev.modifier_name || ev.deal_name}</span>}
{ev.applied_by_username && <span className="text-ink-3">{t('orders.history.by', { name: ev.applied_by_username })}</span>}
{ev.approved_by_username && <span className="text-ink-3">{t('orders.history.approvedBy', { name: ev.approved_by_username })}</span>}
{ev.stage && <span className="text-ink-3">{t(`orders.history.stage.${ev.stage}`)}</span>}
{ev.delta_amount != null && (
<span className={cx('font-semibold tabular-nums', ev.delta_amount < 0 ? 'text-success-ink' : 'text-danger-ink')}>
{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}
@@ -74,3 +76,44 @@ export function PriceEventList({ events }) {
</ul>
)
}
/** The order's moves (6F.4): the whole order's path (table transfers, tables joined into it), then
* each moved line's own path, however many moves. */
export function MoveList({ moves, order }) {
const { t } = useTranslation('manager')
const { formatDateTime, formatNumber } = useFormat()
const byId = new Map(order.items.map(i => [i.id, i]))
const lines = Object.entries(moves.items ?? {}).map(([id, ms]) => [byId.get(Number(id)), ms]).filter(([i]) => i)
if (!moves.order?.length && !lines.length) return <EmptyState compact title={t('orders.moves.none')} />
const row = (m, itemId) => {
const mine = itemId != null ? m.items.find(i => i.item_id === itemId) : null
return (
<li key={`${itemId ?? 'o'}-${m.id}`} className="px-4 py-2 flex items-start gap-3" data-testid="order-move">
<Pill tone="info">{t(`orders.moves.kind.${m.kind}`)}</Pill>
<span className="flex-1 min-w-0 text-label text-ink">
<span className="font-semibold">{m.from_table || '—'} → {m.to_table || '—'}</span>
{m.by && <span className="ml-2 text-ink-3">{t('orders.history.by', { name: m.by })}</span>}
{mine?.quantity != null && <span className="ml-2 text-ink-3">×{formatNumber(mine.quantity, { maxDecimals: 3 })}</span>}
{itemId == null && <span className="ml-2 text-ink-3">{t('orders.moves.lines', { count: m.items.length })}</span>}
</span>
<span className="text-caption text-ink-3 shrink-0">{formatDateTime(m.at, 'datetimeShort')}</span>
</li>
)
}
return (
<div className="divide-y divide-line" data-testid="order-moves">
{moves.order?.length > 0 && (
<section>
<h3 className="px-4 pt-3 pb-1 text-label font-semibold text-ink-2">{t('orders.moves.wholeOrder', { path: pathText(moves.order) })}</h3>
<ul className="divide-y divide-line">{moves.order.map(m => row(m))}</ul>
</section>
)}
{lines.map(([item, ms]) => (
<section key={item.id}>
<h3 className="px-4 pt-3 pb-1 text-label font-semibold text-ink-2">{nameOf(item)} · {pathText(ms)}</h3>
<ul className="divide-y divide-line">{ms.map(m => row(m, item.id))}</ul>
</section>
))}
</div>
)
}
@@ -8,16 +8,16 @@ import toast from 'react-hot-toast'
import { Ban, CreditCard, Percent, Printer, Receipt } from 'lucide-react'
import { useCan, useModule } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, cx } from '@xenia/ui'
import client from '../../api/client'
import { Pill } from '../overview/parts'
import { lineAmount, lineDetails, nameOf, selectable, selectedAmount, shownLines, toggleSelected, unitOf } from './orderLogic'
import { lineAmount, lineDetails, nameOf, pathText, selectable, selectedAmount, shownLines, toggleSelected, unitOf } from './orderLogic'
const STATUS_TONE = { paid: 'success', cancelled: 'danger', tabbed: 'info', closed: 'warning' }
const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink' }
const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink', manual_price: 'text-warning-ink' }
export default function OrderLines({ order, open, priceEvents, onPay, onChanged }) {
export default function OrderLines({ order, open, priceEvents, moves = {}, onPay, onChanged }) {
const { t } = useTranslation('manager')
const { formatMoney, formatTime } = useFormat()
const canDiscount = useCan('pricing.discounts.apply')
@@ -70,6 +70,11 @@ export default function OrderLines({ order, open, priceEvents, onPay, onChanged
{d.choices.length > 0 && <div className="text-caption text-ink-2">{d.choices.join(', ')}</div>}
{d.removed.length > 0 && <div className="text-caption text-ink-2">{t('orders.lines.without', { list: d.removed.join(', ') })}</div>}
{d.note && <div className="text-caption text-warning-ink">{d.note}</div>}
{moves[item.id]?.length > 0 && (
<div className="text-caption text-info-ink" data-testid="line-moved">
↪ {t('orders.moves.linePath', { path: pathText(moves[item.id]) })}
</div>
)}
<div className="text-caption text-ink-3">
{t('orders.lines.added', { time: formatTime(item.added_at), name: item.added_by_name ?? '' })}
{item.paid_by_name && ` · ${t('orders.lines.paidBy', { name: item.paid_by_name })}`}
@@ -79,6 +84,12 @@ export default function OrderLines({ order, open, priceEvents, onPay, onChanged
<span aria-hidden="true">↳</span>
<span>{ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}</span>
{ev.delta_amount != null && <span className="font-semibold">{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}</span>}
{ev.event_type === 'manual_price' && (
<span className="text-ink-3" data-testid="line-price-change">
{formatMoney(ev.price_before)} → {formatMoney(ev.price_after)}
{ev.applied_by_username && ` · ${ev.applied_by_username}`}{ev.waiter_note && ` · ${ev.waiter_note}`}
</span>
)}
</div>
))}
</div>
@@ -123,7 +134,7 @@ function DiscountDialog({ orderId, itemIds, amount, onClose, onDone }) {
const { formatMoney } = useFormat()
const [pct, setPct] = useState('10')
const [note, setNote] = useState('')
const value = Number(String(pct).replace(',', '.'))
const value = parseNumber(String(pct)) ?? NaN
const ok = value > 0 && value <= 100
const apply = useMutation({
mutationFn: () => client.post(`/api/orders/${orderId}/items/discount`, { item_ids: itemIds, discount_percent: value, note: note.trim() || null }),
@@ -21,12 +21,14 @@ import OrderLines from './OrderLines'
import OrderPeople from './OrderPeople'
import PayDialog from './PayDialog'
import PrintProblemsCard from './PrintProblemsCard'
import { AuditList, PriceEventList } from './OrderHistory'
import { closeStep, totals, unpaidIds, venueRules } from './orderLogic'
import { AuditList, MoveList, PriceEventList } from './OrderHistory'
import { closeStep, isSplitPart, totals, unpaidIds, venueRules } from './orderLogic'
import { SplitBillsCard } from './SplitAmount'
import { useCan } from '@xenia/access'
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded', 'kds_order_updated', 'kds_item_updated']
const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
const TABS = ['order', 'prices', 'history']
const TABS = ['order', 'prices', 'moves', 'history']
export default function OrderPage() {
const { orderId } = useParams()
@@ -78,6 +80,7 @@ function OrderView({ orderId }) {
const venue = useVenue()
const [tab, setTab] = useState('order')
const [paying, setPaying] = useState(null) // { ids, amount, thenClose, after }
const maySplit = useCan('ordering.payments.split_amount') // 6F.6
const [confirm, setConfirm] = useState(null) // 'close' | 'writeOff' | 'cancel'
const [printerId, setPrinterId] = useState('')
@@ -90,9 +93,14 @@ function OrderView({ orderId }) {
queryKey: ['price-events', orderId], queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data), events: ['order_updated'],
})
const { data: moves = { order: [], items: {} } } = useLiveQuery({ // 6F.4
queryKey: ['order-moves', orderId], queryFn: () => client.get(`/api/orders/${orderId}/moves`).then(r => r.data), events: ['order_updated'],
})
const refresh = () => {
qc.invalidateQueries({ queryKey: ['order', orderId] })
qc.invalidateQueries({ queryKey: ['price-events', orderId] })
qc.invalidateQueries({ queryKey: ['order-moves', orderId] })
qc.invalidateQueries({ queryKey: ['orders-active'] })
}
const onError = err => toast.error(errorMessage(err, t))
@@ -151,11 +159,12 @@ function OrderView({ orderId }) {
</div>
<PrintProblemsCard orderId={order.id} />
<SplitBillsCard order={order} canUndo={maySplit} onChanged={refresh} />
{tab === 'order' && (
<div className={cx('grid gap-4 items-start', editable && 'lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]')}>
<div className="grid gap-4 min-w-0">
<OrderLines order={order} open={editable} priceEvents={priceEvents} onChanged={refresh}
<OrderLines order={order} open={editable} priceEvents={priceEvents} moves={moves.items} onChanged={refresh}
onPay={(ids, amount, after) => setPaying({ ids, amount, after })} />
<OrderPeople order={order} open={editable} staff={staff} onChanged={refresh} />
</div>
@@ -163,9 +172,13 @@ function OrderView({ orderId }) {
</div>
)}
{tab === 'prices' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><PriceEventList events={priceEvents} /></section>}
{tab === 'moves' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><MoveList moves={moves} order={order} /></section>}
{tab === 'history' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><AuditList order={order} /></section>}
{paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose}
split={venue.split.on && maySplit && !paying.thenClose && !order.items.some(i => paying.ids.includes(i.id) && isSplitPart(i))
? { choices: venue.split, customerCount: order.customer_count } : null}
onSplit={() => { toast.success(t('orders.split.done')); paying.after?.(); setPaying(null); refresh() }}
onClose={() => setPaying(null)}
onDone={() => { toast.success(paying.thenClose ? t('orders.closed') : t('orders.pay.done')); paying.after?.(); setPaying(null); refresh() }} />}
@@ -3,17 +3,20 @@
// "instant-pay close": the rest is paid and the order closed in one go, for venues that don't
// close with unpaid items (orders.close_with_unpaid, 4.8).
import { useState } from 'react'
import { Banknote, CreditCard } from 'lucide-react'
import { Banknote, CreditCard, Divide } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog } from '@xenia/ui'
import client from '../../api/client'
import { SplitAmountForm } from './SplitAmount'
export default function PayDialog({ orderId, itemIds, amount, card = true, thenClose = false, onClose, onDone }) {
/** `split` ({ choices, customerCount }, 6F.6): offers "Split the amount" instead of paying now. */
export default function PayDialog({ orderId, itemIds, amount, card = true, thenClose = false, split = null, onSplit, onClose, onDone }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const [busy, setBusy] = useState(null)
const [error, setError] = useState(null)
const [splitting, setSplitting] = useState(false)
async function pay(method) {
setBusy(method)
@@ -44,6 +47,13 @@ export default function PayDialog({ orderId, itemIds, amount, card = true, thenC
</Button>
</div>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
{split && !splitting && (
<Button variant="ghost" icon={<Divide size={18} />} disabled={!!busy} onClick={() => setSplitting(true)} data-testid="pay-split">{t('orders.split.button')}</Button>
)}
{split && splitting && (
<SplitAmountForm orderId={orderId} itemIds={itemIds} amount={amount} choices={split.choices} customerCount={split.customerCount}
onCancel={() => setSplitting(false)} onDone={onSplit} />
)}
</div>
</Dialog>
)
@@ -0,0 +1,113 @@
// Splitting a bill by amount in the manager (plan 6F.6), as the phones and the counter do: the chosen
// lines are settled into a split bill and cut into equal parts (pre-filled from the customers) or, for
// two parts, any amounts; each part is then paid like any line. Undo while no part is paid.
import { useState } from 'react'
import { Minus, Plus, Undo2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { defaultParts, splitAmounts } from '@xenia/ordering/split'
import { Button, IconButton, Input } from '@xenia/ui'
import toast from 'react-hot-toast'
import client from '../../api/client'
/** The part of the pay dialog that splits instead of paying (choices from splitChoices()). */
export function SplitAmountForm({ orderId, itemIds, amount, choices, customerCount, onDone, onCancel }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const [parts, setParts] = useState(() => defaultParts(customerCount, choices.maxParts))
const [mode, setMode] = useState('equal')
const [first, setFirst] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState(null)
const uneven = mode === 'custom' && parts === 2
const typed = first.trim() ? parseNumber(first, { decimals: 2, allowNegative: false }) : null
const amounts = splitAmounts(amount, uneven ? 'custom' : 'equal', parts, typed)
const step = d => { setParts(p => Math.max(2, Math.min(choices.maxParts, p + d))); setMode('equal') }
async function split() {
setBusy(true)
setError(null)
try {
await client.post(`/api/orders/${orderId}/split-bills`, uneven
? { item_ids: itemIds, mode: 'custom', parts: 2, first_amount: amounts[0] }
: { item_ids: itemIds, mode: 'equal', parts })
onDone()
} catch (err) {
setError(errorMessage(err, t))
} finally { setBusy(false) }
}
return (
<div className="grid gap-3 border-t border-line pt-3" data-testid="split-form">
{choices.maxParts > 2 && (
<div className="flex items-center justify-center gap-4">
<IconButton label={t('orders.split.fewer')} variant="secondary" disabled={parts <= 2} onClick={() => step(-1)}><Minus size={18} /></IconButton>
<span className="text-display font-semibold min-w-16 text-center tabular-nums" data-testid="split-parts">{parts}</span>
<IconButton label={t('orders.split.more')} variant="secondary" disabled={parts >= choices.maxParts} onClick={() => step(1)} data-testid="split-more"><Plus size={18} /></IconButton>
</div>
)}
{choices.custom && parts === 2 && (
<div className="grid grid-cols-2 gap-2">
{['equal', 'custom'].map(m => (
<Button key={m} size="sm" variant={mode === m ? 'primary' : 'secondary'} aria-pressed={mode === m} onClick={() => setMode(m)} data-testid={`split-${m}`}>
{t(`orders.split.${m}`)}
</Button>
))}
</div>
)}
{uneven && (
<label className="grid gap-1 text-label text-ink-2">
{t('orders.split.first')}
<Input inputMode="decimal" value={first} onChange={e => setFirst(e.target.value)} placeholder={formatMoney(Math.round(amount * 50) / 100)} data-testid="split-first" />
</label>
)}
{amounts ? (
<ul className="grid gap-0.5 text-body" data-testid="split-preview">
{amounts.map((a, i) => (
<li key={i} className="flex justify-between"><span>{t('orders.split.part', { n: i + 1, of: amounts.length })}</span><span className="tabular-nums font-medium">{formatMoney(a)}</span></li>
))}
</ul>
) : <p className="text-label text-danger-ink">{t('orders.split.invalid')}</p>}
<p className="text-caption text-ink-2">{t('orders.split.hint')}</p>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
<div className="flex justify-end gap-2">
<Button variant="secondary" onClick={onCancel} disabled={busy}>{t('orders.back')}</Button>
<Button loading={busy} disabled={!amounts} onClick={split} data-testid="split-confirm">{t('orders.split.confirm', { count: amounts?.length ?? parts })}</Button>
</div>
</div>
)
}
/** The order's split bills: parts, paid so far, and Undo while nothing is paid. */
export function SplitBillsCard({ order, canUndo, onChanged }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
const [busy, setBusy] = useState(null)
const bills = order.split_bills ?? []
if (!bills.length) return null
async function undo(bill) {
setBusy(bill.id)
try {
await client.post(`/api/orders/${order.id}/split-bills/${bill.id}/undo`)
toast.success(t('orders.split.undone'))
onChanged()
} catch (err) {
toast.error(errorMessage(err, t))
} finally { setBusy(null) }
}
return (
<section className="rounded-card border border-line bg-surface shadow-raised p-3 grid gap-2" data-testid="split-bills">
{bills.map(b => (
<div key={b.id} className="flex flex-wrap items-center gap-3" data-testid="split-bill">
<span className="flex-1 min-w-0">
<span className="block text-body font-medium text-ink">{t('orders.split.bill', { count: b.parts, total: formatMoney(b.total) })}</span>
<span className="block text-label text-ink-2">{t('orders.split.paid', { paid: formatMoney(b.paid), due: formatMoney(Math.max(0, b.total - b.paid)) })}</span>
</span>
{canUndo && b.can_undo && (
<Button size="sm" variant="secondary" icon={<Undo2 size={16} />} loading={busy === b.id} onClick={() => undo(b)} data-testid="split-undo">{t('orders.split.undo')}</Button>
)}
</div>
))}
</section>
)
}
@@ -3,6 +3,8 @@
// items needs the venue's "close with unpaid items" (orders.close_with_unpaid, 4.8), otherwise
// the rest is paid first.
import { splitChoices, splitLevel, splitMax } from '@xenia/ordering/split'
export const OPEN_STATUSES = ['open', 'partially_paid', 'paid']
export const isOpen = order => !!order && OPEN_STATUSES.includes(order.status)
@@ -59,9 +61,13 @@ export function closeStep(order, closeWithUnpaid) {
/** The venue's settings rows (GET /api/settings/) → the two that matter here. */
export function venueRules(settings) {
const v = key => settings?.[key]?.value
return { closeWithUnpaid: v('orders.close_with_unpaid') === 'true', card: v('payments.card_enabled') !== 'false' }
return { closeWithUnpaid: v('orders.close_with_unpaid') === 'true', card: v('payments.card_enabled') !== 'false',
split: splitChoices(splitLevel(settings), splitMax(settings)) } // 6F.6
}
/** A split bill's part line (6F.6): paid on its own, never split again. */
export const isSplitPart = item => item?.split_bill_id != null && item.status !== 'split'
/** The cart's lines as the server takes them, plus the order's note (POST /api/orders/{id}/items). */
export function sendBody(cart, note) {
return { lines: cart.map(c => c.line), order_note: note?.trim() || null }
@@ -104,3 +110,11 @@ export function flagsByTable(defs = [], assignments = []) {
/** Where a table's card goes: its order, or a new order at that table. */
export const cardTarget = card => (card.order ? `/orders/${card.order.id}` : `/orders/new?table=${card.table.id}`)
/** "T2 → T5 → T7": the tables a moved order or line went through (6F.4; '—' for no table). */
export function pathText(moves) {
if (!moves?.length) return ''
const stops = [moves[0].from_table || '—']
for (const m of moves) stops.push(m.to_table || '—')
return stops.join(' → ')
}
@@ -9,7 +9,7 @@ import toast from 'react-hot-toast'
import { CalendarDays, Check, Pencil, Phone, Plus, Armchair, UserCheck, Users, X } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Spinner, Textarea } from '@xenia/ui'
import { Button, Dialog, Dropdown, EmptyState, Field, IconButton, Input, Spinner, Textarea } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { BOOKING_OFFSETS, bookingBody, offsetFrom, tableName, tablesByZone, venueWallClock } from './overviewLogic'
@@ -168,14 +168,9 @@ export function BookingDialog({ tables, initial, onClose, onSaved }) {
))}
</div>
<Field label={t('overview.bookings.table')}>
<Select value={form.table_id ?? ''} onChange={e => set('table_id', e.target.value ? Number(e.target.value) : null)}>
<option value="">{t('overview.bookings.noTable')}</option>
{zones.map(z => (
<optgroup key={z.zone} label={z.zone}>
{z.tables.map(tb => <option key={tb.id} value={tb.id}>{tableName(tb)}</option>)}
</optgroup>
))}
</Select>
<Dropdown value={form.table_id != null ? String(form.table_id) : ''} onChange={v => set('table_id', v ? Number(v) : null)}
options={[{ value: '', label: t('overview.bookings.noTable') },
...zones.flatMap(z => z.tables.map(tb => ({ value: String(tb.id), label: tableName(tb), hint: z.zone })))]} />
</Field>
<div className="grid grid-cols-2 gap-3">
<Field label={t('overview.bookings.phone')}><Input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} /></Field>
@@ -8,7 +8,7 @@ import toast from 'react-hot-toast'
import { ArrowRight, Printer, X } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Select, Spinner, cx } from '@xenia/ui'
import { Button, Dialog, Dropdown, EmptyState, IconButton, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { lineTotal, orderTotal } from './overviewLogic'
@@ -99,7 +99,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
<span className="flex-1" />
{printers.length > 0 && (
<span className="flex items-center gap-2">
<Select size="sm" value={printerId} onChange={e => setPrinterId(e.target.value)} aria-label={t('overview.order.printer')}
<Dropdown size="sm" value={printerId} onChange={setPrinterId} aria-label={t('overview.order.printer')}
placeholder={t('overview.order.printer')} options={printers.map(p => ({ value: String(p.id), label: p.name }))} />
<Button size="sm" variant="secondary" icon={<Printer size={16} />} disabled={!printerId} loading={print.isPending}
onClick={() => print.mutate(Number(printerId))}>{t('overview.order.print')}</Button>
@@ -142,7 +142,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
{evs.map((ev, i) => (
<div key={i} className={cx('flex items-center gap-2 pl-4 text-caption', EVENT_TONE[ev.event_type])}>
<span aria-hidden="true">↳</span>
<span className="flex-1">{ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}</span>
<span className="flex-1">{ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}{ev.event_type === 'manual_price' && ev.waiter_note ? ` · ${ev.waiter_note}` : ''}</span>
{ev.delta_amount != null && <span className="font-semibold">{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}</span>}
{ev.price_after != null && <span className="text-ink-3">→ {formatMoney(ev.price_after)}</span>}
</div>
@@ -9,7 +9,7 @@ import { useContext, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import toast from 'react-hot-toast'
import { BarChart3, Eye, EyeOff, Lock, Play, Power } from 'lucide-react'
import { BarChart3, Eye, EyeOff, Lock, Play, Power, Tv } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useCan, useModule } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n'
@@ -27,6 +27,7 @@ import { usePrintProblems } from '../orders/usePrintProblems'
import ShiftDialog from './ShiftDialog'
import ShiftsCard from './ShiftsCard'
import TablesCard from './TablesCard'
import MessageOfTheDay from '../signage/MessageOfTheDay'
import { dayKpis, dayOrders, hourBuckets, orderPairs, tableCards } from './overviewLogic'
import { Card, HourBars, Money, Pill } from './parts'
import { SOLID } from './tones'
@@ -48,6 +49,8 @@ export default function OverviewPage() {
const notesOn = useCan('notes.use') && notesModule // what /api/notes checks (6.13b)
const bookingsOn = useModule('reservations')
const chatOn = useModule('chat')
const signageModule = useModule('signage')
const messageOn = useCan('signage.manage') && signageModule // the TVs' message of the day (owner review 5)
const [hidden, setHidden] = useState(readPrivacy)
const [order, setOrder] = useState(null) // { id, table }
@@ -175,6 +178,14 @@ export default function OverviewPage() {
</Card>
</div>
<div className="grid gap-5 min-w-0">
{messageOn && (
<Card title={<span className="flex items-center gap-2"><Tv size={18} className="text-ink-3" aria-hidden="true" />{t('overview.tvMessage.title')}</span>} testId="overview-message">
<div className="p-card grid gap-2">
<p className="text-label text-ink-3">{t('overview.tvMessage.hint')}</p>
<MessageOfTheDay testId="overview-message-input" />
</div>
</Card>
)}
{notesOn && <NotesCard />}
{bookingsOn && <BookingsCard tables={tables} onNew={() => setNewBooking(true)} />}
{chatOn && <MessagesCard staff={staff} tables={tables} />}
@@ -5,7 +5,7 @@
// expected (short / over / even), then "End the shift".
import { useState } from 'react'
import { useTranslation, useFormat, parseNumber } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Spinner, Textarea, cx } from '@xenia/ui'
import { Button, Dialog, Field, InfoTip, Input, Spinner, Textarea, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { ITEM_KINDS, cashCheck, hourBuckets, itemKind, itemShown, quickAmounts, shiftCounts, shiftMoney, shiftPairs } from './overviewLogic'
@@ -127,7 +127,7 @@ export default function ShiftDialog({ shift, mode, onClose, onConfirm, busy }) {
{closing && step === 2 && (
<div className="grid gap-3">
<h3 className="text-title font-semibold text-ink">{t('overview.shift.handover')}</h3>
<Field label={t('overview.shift.counted')} hint={t('overview.shift.countedHint')}>
<Field label={t('overview.shift.counted')} info={<InfoTip>{t('overview.shift.countedTip')}</InfoTip>} hint={t('overview.shift.countedHint')}>
<Input inputMode="decimal" autoFocus value={counted} onChange={e => setCounted(e.target.value)}
placeholder={String(money.expected.toFixed(2))} data-testid="shift-counted" />
</Field>
@@ -6,7 +6,7 @@ import toast from 'react-hot-toast'
import { BarChart3, Coffee, MessageSquare, Plus } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, cx } from '@xenia/ui'
import { Button, Dialog, Dropdown, EmptyState, Field, IconButton, Input, cx } from '@xenia/ui'
import { Avatar, Card, Money, Pill } from './parts'
import { useDuration } from './hooks'
@@ -75,7 +75,7 @@ function StartShiftDialog({ waiters, onClose, onStart }) {
</>}>
<div className="grid gap-3">
<Field label={t('overview.shifts.waiter')} error={error && !waiterId ? error : undefined}>
<Select value={waiterId} onChange={e => { setWaiterId(e.target.value); setError(null) }} placeholder={t('overview.shifts.pick')}
<Dropdown value={waiterId} onChange={v => { setWaiterId(v); setError(null) }} placeholder={t('overview.shifts.pick')}
options={waiters.map(w => ({ value: String(w.id), label: w.full_name || w.username }))} data-testid="shift-start-waiter" />
</Field>
<Field label={t('overview.shifts.startCash')} hint={t('overview.shifts.startCashHint')} error={error && waiterId ? error : undefined}>
@@ -5,7 +5,7 @@
// Used by the pair and edit dialogs of DevicesPage.
import { useEffect, useState } from 'react'
import { useTranslation } from '@xenia/i18n'
import { Field, Input, Select, Switch } from '@xenia/ui'
import { ColourField, Field, Input, Select, Switch } from '@xenia/ui'
import client from '../../api/client'
import { configGroups, configValue, refOptions } from './devicesLogic'
@@ -64,10 +64,7 @@ export default function DeviceConfigFields({ appKey, fields = [], value, onChang
}
if (f.type === 'color') {
return (
<Field key={f.key} label={label} hint={hint}>
<input type="color" value={v || '#000000'} onChange={e => set(f, e.target.value)} data-config={f.key}
className="h-10 w-16 rounded-control border border-line bg-surface cursor-pointer" />
</Field>
<ColourField key={f.key} label={label} hint={hint} value={v || '#000000'} onChange={c => set(f, c)} opacity={false} testId={`config-${f.key}`} />
)
}
return (
@@ -0,0 +1,18 @@
// Which devices run the apps (2026-11-21): modern browsers run everything; older ones (a TV's built-in
// browser from 2021–2023) get the compatibility layer (terminal/vite.config.js, terminal/src/compat.js);
// older still, a blank page. Shown in the "Pair a device" dialog and on Signage → Screens.
import { useTranslation } from '@xenia/i18n'
import { Notice } from '@xenia/ui'
import { MonitorSmartphone } from 'lucide-react'
export function DeviceSupport({ className }) {
const { t } = useTranslation('manager')
return (
<Notice tone="info" icon={<MonitorSmartphone size={16} />} title={t('devices.support.title')} className={className} data-testid="device-support"
items={[
{ tone: 'success', label: t('devices.support.bestLabel'), text: t('devices.support.best') },
{ tone: 'warning', label: t('devices.support.compatLabel'), text: t('devices.support.compat') },
{ tone: 'danger', label: t('devices.support.oldLabel'), text: t('devices.support.old') },
]} />
)
}
@@ -12,9 +12,10 @@ import { useCallback, useEffect, useMemo, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import toast from 'react-hot-toast'
import { MonitorSmartphone, Plus } from 'lucide-react'
import { DeviceSupport } from './DeviceSupport'
import { errorMessage, parseError } from '@xenia/api'
import { useTranslation, useFormat } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, Page, Select, Spinner } from '@xenia/ui'
import { Button, Dialog, EmptyState, Field, InfoTip, Input, Page, Select, Spinner } from '@xenia/ui'
import client from '../../api/client'
import DeviceConfigFields from './DeviceConfigFields'
import { configInitial, deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode } from './devicesLogic'
@@ -244,6 +245,7 @@ function PairDialog({ apps, usage, devices, appName, limitLabel, initialApp, onC
<Input value={code} onChange={e => setCode(normalizeCode(e.target.value))} autoComplete="off" spellCheck={false}
className="font-mono tracking-[0.3em] text-center uppercase" autoFocus />
</Field>
<DeviceSupport />
<Field label={t('devices.form.app')} error={full ? t('devices.form.full', { label: limitLabel(appKey), max: usage[appKey].max }) : undefined}>
<Select value={appKey} onChange={e => {
const next = e.target.value
@@ -256,7 +258,7 @@ function PairDialog({ apps, usage, devices, appName, limitLabel, initialApp, onC
<Input value={name} onChange={e => setName(e.target.value)} placeholder={t('devices.form.namePlaceholder')} maxLength={60} />
</Field>
{modes && (
<Field label={t('devices.form.signIn')}>
<Field label={t('devices.form.signIn')} info={<InfoTip>{t('devices.form.signInTip')}</InfoTip>}>
<Select value={mode} onChange={e => setMode(e.target.value)} options={modes} />
</Field>
)}
@@ -302,7 +304,7 @@ function EditDialog({ device, apps, devices, onClose, onSave }) {
<Input value={name} onChange={e => setName(e.target.value)} maxLength={60} />
</Field>
{modes && (
<Field label={t('devices.form.signIn')}>
<Field label={t('devices.form.signIn')} info={<InfoTip>{t('devices.form.signInTip')}</InfoTip>}>
<Select value={mode} onChange={e => setMode(e.target.value)} options={modes} />
</Field>
)}
@@ -9,7 +9,7 @@ import toast from 'react-hot-toast'
import { Plus } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, Select, Spinner, Switch } from '@xenia/ui'
import { Button, DecimalInput, Dialog, EmptyState, Field, Input, Select, Spinner, Switch } from '@xenia/ui'
import { useLiveQuery } from '../../live/useLiveQuery'
import * as api from './pricingApi'
import { ColourPicker, ConditionList, Missing, PickSeveral, RuleCard, Segmented, TabHead, TagPicker, TargetList } from './PricingParts'
@@ -145,8 +145,8 @@ function DealDialog({ deal, catalog, rules, busy, onClose, onSave }) {
)}
{['set_price', 'add_amount', 'add_percent'].includes(a) && (
<Field label={t(`pricing.actions.valueLabel.${a === 'set_price' ? 'set' : a}`)} hint={a !== 'set_price' ? t('pricing.actions.minusHint') : undefined}>
<Input type="number" step={a === 'add_percent' ? 1 : 0.1} className="w-36" value={Number.isFinite(f.action_value) ? f.action_value : ''}
onChange={e => set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} />
<DecimalInput allowNegative decimals={2} suffix={a === 'add_percent' ? '%' : '€'} className="w-36" value={f.action_value}
onChange={v => set('action_value', v ?? NaN)} />
</Field>
)}
<ColourPicker value={f.color} onChange={v => set('color', v)} label={t('pricing.colour')} />
@@ -12,7 +12,7 @@ import toast from 'react-hot-toast'
import { Layers, Plus } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui'
import { Button, DecimalInput, Dialog, EmptyState, Field, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui'
import { useLiveQuery } from '../../live/useLiveQuery'
import * as api from './pricingApi'
import { ColourPicker, ConditionList, Missing, RuleCard, Segmented, TabHead, TargetList } from './PricingParts'
@@ -147,8 +147,8 @@ function RuleDialog({ rule, catalog, busy, onClose, onSave }) {
options={MODIFIER_ACTIONS.map(v => ({ value: v, label: t(`pricing.actions.${v}`) }))} />
<div className="grid sm:grid-cols-2 gap-3">
<Field label={t(`pricing.actions.valueLabel.${f.action_type}`)} hint={f.action_type !== 'set' ? t('pricing.actions.minusHint') : undefined}>
<Input type="number" step={f.action_type === 'add_percent' ? 1 : 0.1} value={Number.isFinite(f.action_value) ? f.action_value : ''}
onChange={e => set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} data-testid="pricing-rule-value" />
<DecimalInput allowNegative decimals={2} suffix={f.action_type === 'add_percent' ? '%' : '€'} value={f.action_value}
onChange={v => set('action_value', v ?? NaN)} data-testid="pricing-rule-value" />
</Field>
{f.action_type === 'add_percent' && (
<Field label={t('pricing.rules.rounding')}>
@@ -4,7 +4,7 @@ import { useState } from 'react'
import { ArrowDown, ArrowUp, Check, Pencil, Plus, Power, Trash2, X } from 'lucide-react'
import { SALES_POINTS, normalizeSalesPoints } from '@xenia/access'
import { latin, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dropdown, IconButton, Input, Select, cx } from '@xenia/ui'
import { Button, Dropdown, IconButton, Input, MoneyInput, Select, cx } from '@xenia/ui'
import { COLOURS } from './useCatalog'
import { OLD_PLACEHOLDERS, WEEKDAYS, blankCondition, conditionComplete, toggleIn } from './pricingLogic'
@@ -202,7 +202,13 @@ function ConditionFields({ cond, onChange, catalog }) {
case 'specific_date': return <DateList value={p.dates ?? []} onChange={v => set('dates', v)} />
case 'day_of_week': return <DayPicker value={p.days ?? []} onChange={v => set('days', v)} />
case 'min_item_quantity': return <label className="flex items-center gap-2 text-label text-ink-2">{num('min', 1, 1)}{t('pricing.condition.ofTheDish')}</label>
case 'min_order_value': return <label className="flex items-center gap-2 text-label text-ink-2">{num('min', 0, 0.5)}{t('pricing.condition.orderTotal')}</label>
case 'min_order_value': return (
<label className="flex items-center gap-2 text-label text-ink-2">
<MoneyInput size="sm" className="w-32" value={p.min ?? null} aria-label={t('pricing.condition.fields.min_order_value')}
onChange={v => set('min', Number.isFinite(v) ? v : null)} />
{t('pricing.condition.orderTotal')}
</label>
)
case 'min_category_qty': return (
<div className="flex flex-wrap items-center gap-2">
{num('min', 1, 1)}

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