Compare commits

..
82 Commits
Author SHA1 Message Date
bonaminandClaude Opus 5.5 0840247768 feat: staff apps show the menu in the reader's language (plan 6R.L)
The waiters' phones and the counter show categories, products and every
choice (quick options, extras and sub-choices, preferences, shared sets,
ingredients, groups) in the signed-in person's language, falling back to
the stored text. Display only: carts, lines, tickets and the kitchen keep
the venue's text (ids, sub-choices by stored name). In the venue's own
language nothing changes.

- @xenia/access: menuText / useMenuText (mt, mt.choice, mt.line, mt.matches)
- /api/pos/menu carries translations for products, categories and choices
- shared ProductDialog takes a text() prop (the counter passes useMenuText)
- search finds a product by its name in any language (counter, waiter)
- waiter: useMenuNames for sent lines; picker, drawer, cart, summary,
  table lines, quantity / price history, favourites setup
- counter: categories, cards, dialog, cart lines, table lines, payment rows
- tests: access menuText, ordering search, test_pos per-language,
  e2e waiter.mjs and terminal.mjs 6R.L blocks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 20:18:10 +02:00
bonaminandClaude Opus 5.5 f107deca8c docs(docs): pack README for phase 6F (split bills and the settlement-line rule in sales.py, moves, price changes, the day loop, sign-in)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:14:47 +02:00
bonaminandClaude Opus 5.5 096bd53dbd feat(backend,manager): the business day opens and closes by itself (opening hours, a time, or only an alert)
- services/day_auto.py: a minute loop (venue time, offline) opens the day when the opening
  hours start (or at business_day.auto_open_time) and closes it when they end (or at
  auto_close_time); 'alert' only tells the managers. Offsets before / after, one day across
  the break or one per span, spans past midnight belong to the day they start, a day closed
  by hand isn't reopened in the same span, a restart catches up the open (until the business
  date changes for 'time') and alerts a missed close instead of doing it late.
- The close runs only when no order of the day is unclosed (Q-10): otherwise a sticky alert
  and a new try every 15 minutes. A locked / expired license turns the open into an alert.
- Sticky notifications: notifications.resolved_at + core.notifications.resolve(); the
  alerts resolve when the day opens / closes (by hand or by itself).
- services/business_days.py: the one open / close path (the routes and the loop); days opened
  or closed by the system have no opener / closer and opened_auto / closed_auto (Alembic 0052).
- Manager: Settings -> Operation "Opening and closing the day"; the bell's action buttons
  ("Open now", "Go to the overview"); Reports -> Days marks days opened / closed by itself.

Plan platform-v2 6F.8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:17:15 +02:00
bonaminandClaude Opus 5.5 7706bf2470 feat(backend,waiter,terminal,manager): sign-in: ask before signing a waiter's other phone out, usernames on paired screens
- auth.single_session_waiter gains 'ask', the new default (Alembic 0051 moves venues on 'off'
  to it): a second phone gets auth.session_elsewhere {device, since}; Continue retries with
  replace=true and the first phone is signed out at once (live session.ended, reason
  "replaced") and says why on its sign-in page. Only phones count (terminal sessions are
  their own client). refuse_new / end_old unchanged.
- auth.session_ended now carries the reason; the waiter app keeps it until the next sign-in.
- The waiter app sends queued offline ops on every (re)connection, so an order queued on a
  phone that was signed out by another goes out after the next sign-in there (e2e checked).
- auth.terminal_require_username (venue) + Device.require_username (per device, wins):
  GET /api/devices/me/users lists nobody, the screen asks for a username then PIN/password,
  a picked user_id is refused (auth.username_required), "tap" falls back to PIN.
- Manager: Sign-in settings (ask, the new switch), the device dialog's usernames choice.

Plan platform-v2 6F.7.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 11:23:29 +02:00
bonaminandClaude Opus 5.5 ebb3fac6bc docs: the pack README after phase 6 (sales counting, tabs in the books, the manager's structure and v2 rules, looks: palettes and styles, the new e2e suites) (platform-v2 step 6.99)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 01:23:47 +02:00
bonaminandClaude Opus 5.5 2b44d55f81 feat(ui,manager): looks: light / dark / device, palettes and styles, chosen in the manager's profile menu (platform-v2 step 6.15)
- @xenia/ui theme.js: a look = mode (light | dark | system) + palette (data-palette) + style (data-style); applyLook /
  getStoredLook (per device), 'system' resolved with matchMedia and followed live, so a palette is just a light and a
  dark token block; applyTheme kept for older callers (keeps palette and style)
- tokens.css: 'Palettes' (first: Nord, light + dark, every colour and the nav rail) and 'Styles' (first: sharp: small
  corners, 1.5px borders, flat cards); --x-border-width used by every component and Tailwind's 'border'
- contrast test: every palette in both modes (+ the nav rail); it caught the default rail's active item at 3.7:1 -> 5.5:1
- manager: the saved look applied at start (was light only); profile menu -> Look: Light / Dark / Device, Colours
  (Xenia, Nord), Shapes (Rounded, Sharp), applied at once and kept on this device
- e2e: manager_look.mjs (every page in light and dark, no large near-white area in dark, contact sheets; 'nord-sharp'
  adds that look; in run-all), manager.mjs 'look:' (dark at once, kept after a reload, Device follows the device)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:30:24 +02:00
bonaminandClaude Opus 5.5 f383060bad feat(ui): the QR card shared in @xenia/ui/qr (platform-v2 step 6.14c)
- QrCode (a QR on a light tile, optional caption; framed or not) in packages/ui, on its own subpath so only
  the apps that show one need qrcode.react (an optional peer); x-qr styles keep the code dark on light in dark themes
- used by the terminal's customer display, the manager's online-ordering link, table QR codes and Settings' pairing QR
  (four copies of the same markup gone)
- the money pad and the order line row stay where they are: the manager's payment is the phones' cash / card choice
  (no cash given, change or split) and its order lines are not the counter's cart lines, so neither has a second user;
  the signage slides keep their own QR (inline styles scaled to the TV)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:11:34 +02:00
bonaminandClaude Opus 5.5 294b769850 feat(manager): the setup wizard and the shell on v2; all of src on the v2 rules (platform-v2 step 6.14b)
- setup wizard (src/pages/setup): welcome (pick the language: the wizard switches at once), the owner's account, the venue
  (kind, name, staff language, time zone), an optional lock-screen PIN, finish -> sign in; English and Greek
- shell (src/shell): AppLayout (license banner in both languages, header, lock button, idle lock / sign-out), Sidebar on a
  new 'nav' token set in @xenia/ui (light + dark), ProfileDialog (name, username, password, 4-6 digit PIN), licenseContext;
  App.jsx loads the session and the setup state with react-query (no setState in effects); the header's dead search box gone
- Management -> Tables -> List (src/pages/tables, was TablesConfigTab): zones as tabs (drag to reorder), zone name / prefix /
  colour, add many numbered on, a table's name (6 chars) / zone / seats, twice-used names flagged, off / on / delete,
  pick several to move, rename in a series or delete (says how many failed)
- the old src/ui kit, layouts/, components/Sidebar + EditProfileModal, the 'primary' palette and the .btn/.card/.input classes deleted;
  NotificationBell / UserMenuButton on tokens; @xenia/ui: nav tokens, 'scrim' in the Tailwind preset
- v2.json paths = src (the guards cover all of it); npm run lint = eslint src; argsIgnorePattern for components in JSX
- tests: shell.test.mjs (3), e2e setup.mjs (new: a fresh install through the wizard in Greek to the overview, in run-all),
  manager.mjs 'tables list' (zone, 3 tables, rename series, profile PIN, rail tokens)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:01:23 +02:00
bonaminandClaude Opus 5.5 f6fcfb7736 feat(manager): every settings tab on v2 (platform-v2 step 6.14a)
- Settings: tabs in the address (?tab=), Fiscal only with the fiscal app, Appearance only with the waiter app
- General: version / update / license / state / uptime, the local network (address by hand or found, the pairing QR),
  what is set up, export / import of the catalogue and the tables (a wrong file refused, two confirmations), support lock
- Sign-in & security: idle lock / sign-out (seconds..hours, warning when sign-out comes first), recovery codes
- Operation: role permissions, waiters' own shifts and takings, card payments, tables and orders, courses (add, rename,
  colour, order), quick notes, table flags (emoji, colour, white/black text, on/off), quick messages, send the QR menu now
- Appearance: the waiter app's table-card colours per state, light and dark, flash, colour picker with opacity, reset
- Fiscal: on/off, driver, folders with a reachability check, clerk / card terminal numbers, receipt end lines, VAT groups
- Development: pretend printing
- dropped: the v1 'automatic store schedule' switches (kept in the browser only, nothing read them) and the second time-zone card
- backend: JSON settings must be JSON (validation.setting_value); fiscal folders are plain paths (were typed json)
- venue colour data in sections/venueColours.js (guard DATA); store/tableColourStore and Settings/tabs deleted
- tests: settings.test.mjs (5), test_settings_json.py, e2e manager.mjs 'settings v2' (12 checks)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:41:14 +02:00
bonaminandClaude Opus 5.5 bde125bf09 feat(manager): customers, throwaways, stock and notes on v2 (platform-v2 step 6.13b)
- CRM -> Customers: search ignoring case and Greek accents (and part of the phone), visits / spent / last visit,
  the card (contact, notes, open tab, every visit with what was on a tab), new/edit/remove
- Inventory -> Throwaways: log (product, quantity with a comma, reason, note) with its cost, today's list (delete today only),
  a period's totals by reason and product, every entry; Inventory -> Stock: an honest 'not available yet'
- Notes: notes (pinned first, edit in place) and to-dos (urgent first, done folded away, who did it kept)
- backend: crm.manage / inventory.manage / notes.use (the customer search also with the dashboard key, for orders);
  spending counted by services/sales.py (refunds off, tab lines in); null clears a field; names/notes not blank, priorities checked;
  waste ?date_from=&date_to= venue dates; the Greek reason labels left the API; live customers.changed / waste.changed / notes.changed
- the overview's notes card needs notes.use and refreshes live
- tests: test_customers_waste_notes.py (4), crm.test.mjs (3), e2e manager.mjs (customers, throwaways, notes, stock, Greek)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 18:36:27 +02:00
bonaminandClaude Opus 5.5 07c9a0aecf feat: tabs in the books (platform-v2 step 6.13c, KI-018; owner 2026-11-19: every movement recorded)
- a line on a customer's tab is sold, not paid: services/sales.py counts tabbed lines as sold (on_tab apart)
- TabEntry / TabPayment record the business day and the shift of whoever did it (Alembic 0037, rows backfilled with their day);
  services/tab_books.py: per shift and per day, on tabs and tab money received (cash / card / other, who, in a shift or not)
- shift: tab cash goes in the drawer (net_to_deliver, the counted difference, total_collected), tab card in the card total;
  items paid other ways (transfer, on the house) are recorded apart and no longer counted as drawer cash;
  'activity': orders, items made / paid / put on a tab with values
- day summary: per person put on tabs and tab money received, every tab payment with who took it, the part taken outside shifts (in no drawer);
  the day's money: paid, on tabs, sold, paid on tabs, money taken (it used to subtract tabs from paid sales)
- Today: on tabs, paid on tabs; Staff -> Cash handover: paid on tabs; the shift dialog: made / paid / on a tab / paid on tabs
- fix: a line put on a tab was charged without its price change (a discount)
- tests: test_tab_books.py (the done-when), overview unit, e2e manager.mjs (the day records the tab payments; Today shows them)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:32:25 +02:00
bonaminandClaude Opus 5.5 93c0dd7d9c feat(manager): expenses, the supplier book and tabs on v2 (platform-v2 step 6.13a)
- Finance -> Expenses: still owed, late, filters, new/edit (supplier picked or added there), pay in parts, details with payments, delete
- CRM -> Contacts: the supplier book with what each one is owed
- Finance -> Tabs: open (who owes most first) / settled, charges and payments, pay (cash/card/other), close, forgive
- backend: expenses.manage / tabs.manage (the list also reports.view, a customer's tabs also crm.manage, put-on-tab needs tabs.manage);
  payment <= due (expense.over_due), total >= paid (expense.below_paid), categories/kinds/methods checked, null clears a field;
  live events expenses.changed / tabs.changed; GET /api/expenses ?from=&to= venue dates (the report uses it); tab_status=settled
- fix: an expense with a due date failed to save (naive date refused by D-11)
- @xenia/i18n/number subpath; tests: test_finance.py (6), finance.test.mjs (5), e2e manager.mjs finance flow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:54:21 +02:00
bonaminandClaude Opus 5.5 6bdf0bdd79 feat: the staff, cancellations/discounts, technical, prep zones and expenses reports on v2; reports all on v2 (platform-v2 step 6.12c)
- Reports -> Staff (src/pages/reports/staff): shifts (pay, collected, to hand
  over, the counted difference, cancellations; a shift opens the overview's
  shift dialog; the owner deletes one), cash handover (starting cash, cash,
  card, refunds, to hand over, counted), sales by person (orders, units,
  cancellations, hours, sales net of refunds, per hour, share; ranked) - the
  v1 activity and leaderboard views merged into it
- Reports -> Cancellations and discounts (src/pages/reports/misc), with totals
  per person; Technical (printing: tickets, failed, printed first time, per
  printer, every ticket with its error, the receipt-printer summary; logs for
  the owner) - v1 printer history + printer health merged
- Prep zones report (per zone: items, value, products, orders; per-zone Excel
  downloads built in the browser with the server's Excel rules; print a zone)
  and Expenses report (period, status, category; split by category or
  supplier; payments) - its categories now match what Finance saves (the v1
  report listed categories that never existed)
- kit: csvText() / download(); PrintDialog modes for the printer summary
- v1 report kit (reports/shared) and every v1 report view deleted;
  src/pages/reports is v2 (all but LogsPanel strict)
- tests: reports.test.mjs (+1), e2e manager.mjs (every report opens, a shift's
  details, the ranking)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:19:49 +02:00
bonaminandClaude Opus 5.5 7767bdb728 feat: the venue and products reports on v2 (platform-v2 step 6.12b)
- Reports -> Venue (src/pages/reports/store): business days (revenue/profit
  trend, each day's times, orders, revenue, fees, refunds, cost, profit; a day
  opens with its orders and shifts, a shift opens the overview's shift dialog;
  the owner corrects a closing time, deletes an empty day or a shift), orders
  (filters by status, person, table; per-order products / fees / refunds),
  busy times (by hour, by weekday of the business date), trends (days, weeks,
  months, the 7-day average), tables (time at the table, per visit, revenue)
- Reports -> Products (src/pages/reports/products): products (units, revenue,
  refunded, cost, profit, margin, waste, share; top 10 by revenue, units or
  profit) and categories (share bars, profit share)
- kit: PrintDialog (receipt printer, summary / full, or print the page),
  TrendChart and BarList on tokens (no chart animation), printBody()
- access: deleting a business day or a shift (which erases its orders) is
  owner-only (core.settings.manage; was any dashboard user)
- v1 StorePage, ProductsReportPage and their seven views removed
- tests: reports.test.mjs (+1), e2e manager.mjs (every tab, a day, products
  revenue = the backend's, Greek)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:06:20 +02:00
bonaminandClaude Opus 5.5 4df59c33ef feat: one way to count sales in every report; exports for Excel; the report kit and Today on v2 (platform-v2 step 6.12a)
- services/sales.py: sold = active + paid lines; a line's value net of what
  was refunded of it; system lines (the delivery fee) counted apart as fees;
  cost/profit with has_gap. Products, categories, tables, traffic, revenue
  trends, business days (list and current), per-waiter sales, order history
  totals and the printed products/categories/tables reports all use it (they
  used to differ: closed-only vs all orders, fee as a product, refunds never
  subtracted)
- the overview's day summary values lines with their price change (discounts
  were valued at full price)
- services/csv_export.py: UTF-8 BOM, times in venue time with the zone in the
  header, ';' and decimal commas for a Greek venue (',' and '.' otherwise);
  every report export uses it; orders export has products / fees / refunded
- fix: /api/reports/shift/orders with business_day_id crashed (no window)
- manager: src/pages/reports/kit (page with tabs, period picker, panels,
  figures, sortable table, export button, order dialog reusing the order
  page's parts, hour chart on tokens) and reports/today on it; v1 Today removed
- tests: test_sales_accounting.py (a day with a fee and a partial refund adds
  up the same in every report), test_reports_export.py (Excel format),
  reports.test.mjs, e2e manager.mjs (Today, order dialog, export, Greek)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:51:13 +02:00
bonaminandClaude Opus 5.5 6643614ff6 feat: staff and the schedule on v2; managers give staff passwords (platform-v2 step 6.11, KI-014)
- staff: PUT /api/waiters/{id}/password (set, change, or take away; 6+ chars)
  so the password sign-in mode works for everyone; PUT /{id}/pin with the PIN in
  the body (was in the address: reset-pin?pin= removed); PINs 4-6 digits when
  adding; a password can be given when adding; has_password on staff; editing
  clears emptied fields and keeps usernames unique; delete only without history
  (orders, items, shifts) and never yourself
- schedule: times checked (schedule.bad_time), one person's overlapping shifts
  refused (schedule.overlap, past midnight understood), everyone active can be
  scheduled (the kitchen too), changes need core.staff.manage
- manager: src/pages/staff (list with search and filters, person dialog with
  photo, PIN / password dialog, zones) and src/pages/schedule (by person, by
  hour with opening hours, shift dialog with clash check, view settings kept in
  the browser); the never-used "automatic start/close" switches dropped; v1
  StaffTab and SchedulePage removed; ApprovalsPage loads with useLiveQuery
- tests: test_staff_v2.py (done-when on a paired screen), staff.test.mjs, e2e
  manager.mjs (add, password, sign-in on a paired till, a shift and a clash)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:05:01 +02:00
bonaminandClaude Opus 5.5 f31bdf42aa feat: printing problems shown and handled; printing set-up on v2 (platform-v2 step 6.10)
- a ticket that doesn't print is a problem for whoever sent it and the managers:
  GET /api/print-problems (the order, table, dishes, printer, since when, tries,
  last error, who sent it) and three ways out: print again, send to another
  printer, handled (services/print_problems.py; print_jobs.resolved_by /
  redirected_to, Alembic 0036); live event print.problems from the print paths
- phone: the red printer button opens the problems sheet, the table page warns
  (usePrintProblems replaces the 8 s poll); counter POS: a red button under the
  modes with the shared panel (@xenia/ordering PrintProblemsPanel + pure rules);
  manager: a card on the overview (top), the Tables page and the order page
- manager: Settings -> Printing (printers with reachability, test print, network
  scan; ticket layout + test ticket, beep, fonts with previews, dot leader,
  dividers) and Management -> Prep zones (cards + zone dialog with the ticket
  language, printers, copies, sorting, category order, kitchen screen) rebuilt in
  src/pages/printing; v1 PrintFontsTab, PrepZonesConfigPage, PendingPrints and
  /api/orders/pending-prints removed
- access: printer add/edit/delete/scan need core.settings.manage, prep zone
  changes catalog.menu.manage (were any dashboard user)
- tests: test_print_problems.py, @xenia/ordering printProblems, manager
  printing.test.mjs, e2e print_problems.mjs (done-when) + manager.mjs printing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 01:40:07 +02:00
bonaminandClaude Opus 5.5 070c9cf625 feat: tables and orders in the manager on v2 (platform-v2 step 6.9)
- manager: new pages/orders/ (Tables page cards + quick actions, order page with
  lines, multi-select pay/discount/cancel/tab, staff + customer, price changes,
  history, the menu + cart beside it); a free table opens a new order on first
  Send; v1 TablesPage, OrderDetailPage, DesktopOrderingTab, ManagerOrderDrawer
  and PaymentMethodModal removed
- ordering by line id like the phones: GET /api/orders/menu (the counter's
  product shape, in-store prices); the product dialog, cart rules and quote hook
  move to packages/ordering (@xenia/ordering), shared by counter, menu tablet,
  manager
- close follows orders.close_with_unpaid (pay first, or write off after saying
  so) on the order page and the overview's quick view; paying asks cash or card
- a confirmed booking can keep its table ahead (manager, phones, counter):
  POST /api/connect/bookings/{id}/table, reservations create/PATCH; refused with
  reservation.table_kept within 2 h of another booking
- tests: test_manager_ordering.py, online bookings +2, manager orders.test.mjs,
  @xenia/ordering, e2e manager.mjs (take, change, pay-first close, RESERVED)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:58:46 +02:00
bonaminandClaude Opus 5.5 f4aae6abbc feat: the table map (platform-v2 step 6.8, D-31)
- floor_plans / floor_items (0035), tables' plan_id + width/height/rotation/shape;
  /api/floor-plans (set-up, catalog.tables.manage, floor_plans.changed) and
  /api/floor-plans/live (each table's state, guests, waiters, time; zone rule)
- @xenia/floorplan: the drawing (Floor, Item, TableShape, FloorView) and its geometry
  (grid snap in whole cells, outlines, chairs), tested
- manager: Management -> Tables -> Floor plans (editor: drag, grid, irregular floor,
  walls/bar/labels/areas, background picture), Tables page List / Map
- counter POS: Tables List / Map; waiter: Map mode, the list stays the default
- tests: test_floor_plans.py, floor + geometry unit tests, manager/waiter/terminal e2e

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:00:45 +02:00
bonaminandClaude Opus 5.5 fd3254aa31 feat: pricing on v2 (platform-v2 step 6.7)
- manager src/pages/pricing: price rules, price groups, deals, discounts on the tokens,
  English and Greek; the rules as data in pricingLogic.js (tests/pricing.test.mjs)
- routers/pricing: set-up needs pricing.manage, broadcasts pricing.changed; incomplete
  conditions refused (pricing.bad_condition); venue discount settings saved again (the
  date-as-text bug) with empty = no limit (pricing.bad_limit), old "None" tolerated
- nav: Offers & pricing needs pricing.manage
- tests: test_pricing_setup.py (a happy-hour rule prices a counter quote), manager.mjs e2e

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:40:51 +02:00
bonaminandClaude Opus 5.5 c1af7770cf feat: ordering from the menu tablet at a table (platform-v2 step 6.6, D-30)
- tablet_orders (0034) + services/tablet_orders.py: venue rules (menu_tablet.ordering) with
  per-tablet overrides: kitchen or waiter confirms first, no open order open/refuse, limits
  (items per order, of one dish, time between orders)
- /api/menu-tablet: quote, order, order/{id}, bill (see + ask), requests accept/decline, ordering
- terminal: Add to the order (POS ProductDialog), cart, note, send, live status, the bill
- waiter: TabletRequests on the table page, tablet_order message theme with Open the table
- manager: Settings -> Menu tablets
- tests: test_tablet_orders.py, menu-tablet unit, menu_tablet.mjs e2e (the done-when)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:42:37 +02:00
bonaminandClaude Opus 5.5 c43dc8b55b test(e2e): the QR menu's new look: allergens, the language switch; the order app's allergens (platform-v2 step 6.5)
run-all also runs the menu app's unit tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:27:10 +02:00
bonaminandClaude Opus 5.5 e395d99704 feat(menu): the menu in English and Greek (platform-v2 step 6.4, D-29)
- products.translations / categories.translations (Alembic 0033, core/menu_languages.py: el + en,
  name / description / quick options by their base name; catalog.translation). Empty = the text
  as typed; no machine translation (owner).
- In the manager's product editor ("In English" / "In Greek", quick extras), the category dialog,
  and a menu board's Language (signage MenuContent.language).
- Customer screens only: cloud snapshot names / descriptions per language (C-2), the menu tablet's
  EL / EN switch the names (localize), signage boards; tickets, KDS, counter, phones keep the base.
- Catalogue bundles carry translations; @xenia/access menuLanguages.js (a backend test compares).
- e2e: manager (the other language saved), menu tablet (EN / EL names), QR table (English on
  the menu, the base name on the kitchen's order, Greek page as typed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:47:03 +02:00
bonaminandClaude Opus 5.5 5048f82a4c feat(manager): products and categories on v2, a product in several categories, allergens (platform-v2 step 6.3)
- Management/ProductsTab + ProductFormModal (3.1k lines) → src/pages/products/: category tree,
  list/grid, toolbar + filters (search folds accents and Latin letters), bulk actions, category
  dialogs; the editor in editor/ (details, sold at, cost, fiscal; the waiter's choices).
  Arithmetic in productsLogic.js / editor/formLogic.js (tests/products.test.mjs).
- Several categories per product with a main one (D-23): edited in the editor, "also in" on the
  rows, each category's list ordered on its own (drag or up/down → PUT /reorder with category_id);
  bulk "move to" / "also list in". The waiter's picker now shows a product in every category.
- Allergens: products.allergens (Alembic 0032, core/allergens.py: 14 EU, contains | may_contain,
  catalog.allergen), in the API, POS menu, menu tablet, catalogue bundles and the cloud snapshot
  (C-2); @xenia/access allergens.js + <Allergens> shown on the phone, the counter, the tablet.
- Bell: only the newest load sets the list (an older answer could hide a live notification).
- e2e: manager (two categories, order per category, allergens), terminal / menu tablet / waiter
  (allergens shown); media saves by test id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:04:35 +02:00
bonaminandClaude Opus 5.5 8a02173450 feat(manager): the overview, online orders and the day summary on v2 (platform-v2 step 6.2)
- DashboardPage (2.8k lines) → src/pages/overview/: OverviewPage + cards (shifts, tables,
  pending prints, notes, bookings, messages) and dialogs (order at a glance, shift review /
  end with the cash handover, day summary with cash count and checks); arithmetic in
  overviewLogic.js (tests/overview.test.mjs). Data via useLiveQuery: orders and tables
  live, day and shifts every 15 s. Bookings typed in venue time; decline reason in a dialog.
- OnlineOrdersPage → src/pages/online/ on react-query + live events; unused API helpers dropped.
- WorkdaySummaryModal → overview/DaySummaryDialog + DaySummaryTabs.
- Every text in manager.json (en + el, 342 keys); tokens only; v2.json adds overview, hooks.
- Backend: business day open/close answer only with codes (license.locked, license.expired,
  business_day.orders_open); XeniaError's v1 `detail` removed.
- @xenia/i18n: formatDateTime with Intl options threw "unknown date style" (fixed, tested).
- e2e manager.mjs: open the day, a shift (start, stats, end short), a live table, a booking,
  day stats, Greek, close the day (forced), online orders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:01:51 +02:00
bonaminandClaude Opus 5.5 2dc5da446e feat: foundations for the manager conversion (platform-v2 step 6.1)
- Backend: every HTTPException in routers/ is an error code now (260 raises, ~105 new codes,
  texts in en + el); XeniaError(detail=...) keeps the three v1-shaped answers old pages read;
  bad / unknown tokens answer auth.session_ended; test_errors refuses new HTTPExceptions.
- Manager: v2.json is the list of pages on the v2 rules: scripts/lint.mjs lints them,
  tests/v2-guards.test.mjs refuses Greek and colour literals, `strict` paths make
  set-state-in-effect an error.
- src/live/useLiveQuery.js (react-query + live events + refresh on reconnect); Signed in now
  uses it.
- Dead manager files removed (3.1k lines unreachable from main.jsx).
- Tests: backend 544 passed, manager unit 33, run-all (no Android) passed (manager's live
  bell check passed on a rerun).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:31:36 +02:00
bonaminandClaude Opus 5.5 218a6c9c5e chore: phase 5 wrap-up (platform-v2 5.99)
- THIRD_PARTY_NOTICES.md in the backend image: FFmpeg (GPL v3, via imageio-ffmpeg)
- video.requeue_missing(): videos whose still frame is gone (a partial restore) are prepared
  again when the backend starts (+1 test, backend 542 passed)
- pack README: data/media belongs in every site backup with pos.db
- stack.mjs: the test video is unique per run (the stack keeps its data between runs)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 03:06:48 +02:00
bonaminandClaude Opus 5.5 b5361e10ca feat(media): video versions: still frame + a version every screen plays (platform-v2 5.4e)
- services/video.py: background worker (one video at a time, low priority) makes a still
  frame (thumb/card/full WebP) and, when needed, play.mp4 (H.264+AAC, <=1920 px, HDR
  tone-mapped, faststart); the original is kept. Media.processing/progress (migration 0031,
  existing videos queued). ffmpeg from the pinned imageio-ffmpeg wheel; none = as uploaded.
- MOV (video/quicktime) accepted; /api/media/file/<sha>/play served with ranges.
- Signage plays the version (poster = still frame) and tells the screens playing it when ready.
- Manager library: still frames in the grid, preparing progress, status in the details.
- Tests: test_video.py (8), backend 541 passed; e2e media/signage/stack new checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:10:22 +02:00
bonaminandClaude Opus 5.5 f8d0d29d8f feat: call a waiter from a menu tablet at a table (platform-v2 step 5.7b)
- backend: menu tablet device config `table` (ref, validated against active
  tables) and `call_waiter`; GET /api/menu-tablet/menu gives the table and
  whether it can call; POST /api/menu-tablet/call sends a `table_call` staff
  message ("Table 5: the guests call a waiter.", venue language) to the table's
  waiters (its open order's, else the zone's), at most once a minute per tablet
  (menu_tablet.call_too_soon with the seconds left; menu_tablet.no_table).
- terminal: "Call a waiter" only on a tablet at a table; "A waiter is on the
  way to table 5", then a countdown before it can call again; a failed call
  says to ask at the counter.
- waiter: the call shows with its own look and "Open the table".
- manager: tables as the choices of a device setting.
- tests: backend +2 (535 → 533 passed total), e2e menu_tablet.mjs +3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 00:04:39 +02:00
bonaminandClaude Opus 5.5 cc81e0a31f feat(terminal): the menu tablet app (platform-v2 step 5.7a)
terminal/src/apps/menu-tablet: the venue's menu for staff (a quick price
check) and guests. Category chips that jump to their section, or one A–Z
list; compact rows, expanded rows (photo, description) or full cards; tap a
product to see it big (photo, price, description, tags); search that ignores
accents and also finds names typed in Latin letters ("souvl"); sold out
marked; the guest's language for the tablet's texts; back to the start (search
cleared, first language, top) after the set time without a touch; light or
dark; the last menu kept for offline; live on menu_tablet.changed /
device.updated. @xenia/i18n exports ./latin for plain-JS use.
tests: logic (3), e2e menu_tablet.mjs (10 checks, in run-all).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:44:42 +02:00
bonaminandClaude Opus 5.5 2a6640fe5c feat(backend): the menu tablet's menu (platform-v2 step 5.7a)
GET /api/menu-tablet/menu for a paired menu tablet: categories in the
catalogue's order (sub-categories after their parent, one category and its
sub-categories when the tablet is set so), each with its products in its own
order (a product in several categories shows in each), the products once with
name, description, tags, photo, the price of the tablet's sales point (or none)
and availability; sold-out hidden when set; the venue's name and the tablet's
settings. Device config: view, photos, descriptions, group, theme, prices of,
sold out, category, search, languages, idle reset (texts in both languages).
Menu changes send menu_tablet.changed to every tablet (main.py, with signage).
tests: test_menu_tablet.py (4); 531 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:44:42 +02:00
bonaminandClaude Opus 5.5 6c982e3139 feat(manager): signage screens, schedules, the message of the day and the weather's town (platform-v2 step 5.6c)
Signage gets tabs:
- Screens: every paired signage TV with what it plays (a playlist, or a
  schedule that wins over it), its shape and rotation, a warning when a
  playlist was made for the other shape; a link to pair one in Devices.
- Schedules: lines (a playlist on days / between hours that may pass midnight /
  between dates, with a priority) and the playlist for the rest of the time;
  "now: …" per schedule; the screens on it.
- Message and weather: the message of the day for every screen; the
  weather's town from a search (°C / °F), now / fetched at, "no forecast"
  when the server can't reach the service, fetch now, remove; says the
  weather needs internet and the widget hides without it.
- e2e signage.mjs +6 (message saved, weather section, choosing a playlist and
  turning the picture move the TV, a schedule built in the manager plays what
  it picks now); a crash is reported as a failed check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:20:44 +02:00
bonaminandClaude Opus 5.5 5f6b51fb8b feat(manager): the menu board editor and widgets (platform-v2 step 5.6b)
- Menu board: everything or chosen whole categories (sub-categories
  included, new products join) plus single products found by search; hide a
  product from the board (and show it again); the board's own order with
  arrows on what the server resolved (categories and products; boardOrder
  writes it); a badge per product; grouping, headings, photos, descriptions,
  whose prices (a sales point or none), sold out crossed out or hidden,
  columns, products per page (or as many as fit), seconds per page; colours,
  font, size, background.
- Widgets (text and menu slides): logo, venue name, date (long / short),
  clock (seconds), message of the day (or its own text), QR code (ordering /
  QR menu / a link + caption), weather (1-3 days, says it needs internet);
  where (corners, bars) and size.
- The preview stays in view while the settings scroll.
- @xenia/signage: the venue clock's Intl call names its time zone where the
  i18n guard reads it.
- tests: manager signage.test.mjs +1; e2e signage.mjs builds a menu board in
  the editor (categories, a single product, the order, a badge, hiding, a
  clock) and checks what was saved and resolved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:16:49 +02:00
bonaminandClaude Opus 5.5 152388321e feat(manager): the signage editor: playlists, the timeline, slides with a live preview, templates (platform-v2 step 5.6a)
Management → Signage: playlists (name, landscape / portrait, default
transition, duplicate, delete with the screens it plays on); the timeline
(drag or arrows to reorder, duplicate, remove, on / off, time and when it
shows at a glance, a round's total time); a slide's settings (name, seconds or
a video to its end, transition, days / hours / dates, the picture or video,
fit, text, alignment, font, colour, size, background colour or photo with
darkening; a menu board's title, columns and colours) with a live preview drawn
by @xenia/signage at 1920 × 1080 and scaled down; new slides empty or from
templates (promotion, announcement, happy hour 17-19, welcome, menu board,
video); a warning on the slide and its card when a picture or video doesn't
fit the playlist's shape. Unit tests (4), e2e signage.mjs builds a playlist in
the manager and the TV plays it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:59:33 +02:00
bonaminandClaude Opus 5.5 4d63216167 feat(backend): signage previews for the editor: menu boards resolved, a draft menu, the widgets' venue (platform-v2 step 5.6a)
GET /api/signage/playlists/{id} gives each menu slide its resolved `menu`;
POST /api/signage/preview/menu resolves a menu board not saved yet; GET
/api/signage/venue gives what the widgets show. 527 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:59:33 +02:00
bonaminandClaude Opus 5.5 314e9c2457 refactor: @xenia/signage: the slides and the player's logic shared by the terminal and the manager (platform-v2 step 5.6a)
The signage slides (SlideView, TextSlide, MenuSlide, Widgets) and the pure
logic (schedule pick, slide windows, menu pages) move from the terminal into
packages/signage, so the manager's previews draw a slide exactly as the TV
does. Sizes are container units (cqmin) instead of viewport units: a slide
draws inside any box with container-type: size (frameStyle sets it on the
TV). Tests move with it (10). Dockerfiles copy its package.json; both apps'
Tailwind content include it; run-all runs its tests. Signage e2e and the
compose stack passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:59:33 +02:00
696 changed files with 55541 additions and 37254 deletions
+105
View File
@@ -0,0 +1,105 @@
# Design language (on-site frontends)
> The rules every screen of the manager (and later the terminal and the waiter app) follows, so the product looks like one thing.
> **Read this before writing or changing any page, dialog or component.** Change a rule here first, then in `packages/ui`, never in one page.
> Started 2026-11-20 from the owner's UI review (modelled on the BellSystems control panel's `DESIGN.md`).
## 1. Principles
- **Global, never local.** Anything that two pages need is a component or a token in `@xenia/ui` (`packages/ui`). If a page needs a new look, add it to `@xenia/ui` and use it from there. Never rebuild a dropdown, a tab strip or a page frame inside a page.
- **Tokens only.** Colours, sizes, radii, paddings and heights come from `packages/ui/src/tokens.css` (Tailwind names from `tailwind-preset.js`). No hex or rgb values in app code (see also CS-16).
- **Same height in a row.** Controls that sit side by side (a search box, dropdowns, chips, buttons) share one height: `md` (44 px, `--x-control-md`) unless the whole row is `sm`.
- **Quiet secondary text.** `text-ink-2` / `text-ink-3` are muted on purpose. Don't make subtitles, hints or labels darker to make them stand out.
## 2. The page rule
Every page's root is `<Page>` from `@xenia/ui`. It provides:
- **its own scrolling** (the shell's `<main>` never scrolls),
- **the width:** it fills the content area up to 2200 px (`--x-page-max`). On a 1080p monitor the page fills the screen; on an ultrawide it stays 2200 px wide and is **centred**. The width never depends on the window's height (owner 2026-11-21: a short window used to narrow the page),
- **the padding and gaps** (`--x-page-pad`, `--x-page-gap`), the same on every page.
```jsx
<Page testId="contacts-page">
<PageHeader title="…" subtitle="…" actions={<Button>New</Button>} />
<Toolbar>
<SearchInput value={q} onChange={setQ} placeholder="…" />
<Dropdown multiple value={kinds} onChange={setKinds} allLabel="All kinds" options={…} />
</Toolbar>
<Panel padded={false}><Table … /></Panel>
</Page>
```
- `top={<Tabs … />}` keeps a tab strip above the scrolling part (Online orders, Settings). The tab is kept in the address (`?tab=`). Tabs that don't fit **wrap onto another row**; they are never hidden in a sideways scroll (6F.0, owner 2026-11-23).
- `header={<PageHeader … />}` with `top`: the page's title and description come **first**, then the tabs (Offers & pricing). Each tab then starts with its own head: title, description, its "New" button at the top right.
- `fit`: the page is exactly the screen's height and doesn't scroll; its `Pane`s do, each on its own (Products). Put them in an element with `x-page__fill`. Phones scroll as usual.
- The scrollbar's room is always kept (`scrollbar-gutter: stable`), so a short tab is exactly as wide as a long one.
- Every page is full width, **Settings included** (6F.0, owner 2026-11-23: an 880 px Settings page looked narrower than the rest and cut its tabs). Settings and other pages of cards put them in `<Columns>`: cards flow top to bottom, then into the next column, each column at least 34rem (two on 1080p, three on an ultrawide, one on a laptop or phone); `x-columns__wide` / `<ColumnsWide>` spans all columns (an intro row, a wide editor). `width="form"` (880 px, centred) stays only for a single form that reads better narrow; no page uses it now.
- A settings row (`SettingRow`) keeps its control in a 16rem box on the right: selects and inputs fill it, switches and buttons sit at its right edge.
- **Never** put `p-*`, `max-w-*`, `mx-auto`, `h-full` or `overflow-*` on a page's root, and never nest a second width limit inside it.
- Checked by `tests/e2e/manager_layout.mjs` (1920×1080 and 3440×1440: every page fills / is centred, and scrolls). Add a new page to its `PAGES` list.
Every page is on `<Page>` except Inventory → Stock (a placeholder). Two-column pages put each side in its own container. Products is a `Page fit` with two `Pane`s (header and footer stay, only the list scrolls; the list's body `sunken`, a shade darker, so the white product rows stand out). The floor editor: the map and its panels, the narrow side `sticky`.
## 3. Components (`@xenia/ui`)
| Need | Use | Notes |
|---|---|---|
| A page | `Page`, `PageHeader` | §2 |
| Cards in columns (settings) | `Columns`, `ColumnsWide` | §2; a card never splits across two columns |
| Filters / actions over a list | `Toolbar`, `ToolbarSpacer` | every control in it the same height; the search box grows |
| Search | `SearchInput` | icon, clear button; `onChange(text)` |
| Choose one / several | `Dropdown` (`multiple`) | **never a native `<select>` in a toolbar.** Multi: value is an array, `[]` = all (`allLabel`). Options can carry a `dot` (a zone's colour) and a `hint`. Search box from 9 options. Same heights as `Input`. Native `Select` stays only inside forms where the phone's own picker is better |
| A small panel under a button | `Popover` (`open`, `anchor` = the button's ref, `onClose`) | a colour picker, an "Add…" menu. Drawn over everything (portal), flips above, stays inside the window: **never an `absolute` panel inside a section** (it is clipped and makes the section scroll) |
| A colour (a venue's: data) | `ColourField` (`auto`, `opacity`, `presets`) | a field with its swatch and code; its panel (over the page) has 12 ready colours, the picker, the opacity (`#rrggbbaa`) and the code. `auto` = a first choice that leaves it to something else ("As the slide"). **Never** a bare `<input type="color">` |
| An icon from a set | `IconPicker` (`icons` = { key: component }) | a field showing the icon; a grid of the set over the page, "No icon" first |
| Money, a weight, any number with decimals | `MoneyInput` (€, cents), `DecimalInput` (`decimals`, `allowNegative`, `suffix`) | typed with a comma **or** a dot ("12,50", "1.234,50"); reports a number, `null` when empty, `NaN` when it isn't a number (show the error). **Never** `type="number"` with a decimal step, `parseFloat` or `.replace(',', '.')`: they drop the comma a Greek keypad types (6F.2; guarded by `packages/i18n/tests/typed-numbers.test.mjs`). Fields kept as text read it with `parseNumber` |
| A whole number (seconds, counts) | `NumberInput` (`min`, `max`, `suffix`) | − / + on its sides, as tall as an input; it may be emptied while typing (`onChange(null)`): the form shows the error and blocks saving. **Never** clamp on every key (the user can't clear the field). With a `min` below 0 a minus may be typed in front |
| A note in a box (what works, a caution) | `Notice` (`tone`, `title`, `icon`, `items` = [{ tone, label, text }]) | a tinted box with a bar on its left; `items` are points with a tone dot and a bold label. **Never** a local `bg-info-soft` paragraph rebuilt per page |
| A slider with its value | `Slider` (`suffix`) | framed and as tall as the fields beside it; the value sits as close to it as the frame's padding. **Never** a bare `<input type="range">` |
| Fields that should wrap | `FieldRow` (`min`, `shade` on every other row) | each field keeps its least width; a row that wraps is framed (and tinted with `shade`), a row on one line looks like any row |
| Toggles that go together (bold / italic / underline) | `Segmented multiple` | value is an array |
| A toggle filter (a state) | `FilterChip` (`tone`, `count`) | |
| Two or three views (List / Map / QR) | `Segmented` | the view in the address (`?view=`) |
| Sections of a page or a dialog | `Tabs` (`size="lg"` on pages) | scrolls sideways only, never up/down. `inset`: the strip is a card's header (card padding at the sides, the same room above and below a button in `end`, the labels level with it, no line under it). `fill`: the tabs share the width equally (a narrow column) |
| A container whose list scrolls | `Pane` (`header`, `footer`, `sunken`) | header and footer stay, the body scrolls; one side of a `Page fit` |
| A help tip | `InfoTip` | opens on hover (mouse) and on tap. Beside a switch: `Switch info={<InfoTip>…}` puts it right after the text, never after the switch |
| Row actions that stand apart | `IconButton tone` | `danger` delete / archive · `warning` block · `info` zones · `accent` edit · `success` unblock: a **grey** square at rest; under the pointer it lights up in its colour (soft background, coloured icon). Every row action of a row has a tone, so they all look the same at rest. Neutral actions stay `ghost` |
| A quiet text action that warns | `Button variant="ghost" tone="danger"` | grey text, red under the pointer ("Remove" a picture) |
| A switch on its own in a row of buttons | `Switch` without a label | lines up with the buttons (centred), never with a text baseline |
| Dialogs | `Dialog` `sm` 400 · `md` 520 · `lg` 720 · `xl` 920 · `wide` (~88 % of a 16:9 screen, capped on ultrawides) | the day summary is `xl`, the product editor `wide` |
| Ask before doing something (delete, leave unsaved work) | `useConfirm()` → `confirm({ title, body, confirmLabel, tone })` (or `ConfirmDialog`) | **never the browser's `window.confirm`**; render the returned dialog in the component. Leaving unsaved work: add `altLabel` ("Save and leave"): the promise answers `'alt'` |
| A switch in a row of fields | `Switch boxed` | framed and as tall as an input: text left, switch right; a click anywhere in the frame toggles it |
| Two or three choices that fill a form column (alignment…) | `Segmented fill` | options share the width; icon-only options pass `ariaLabel` |
| A side drawer | `Sheet side="right"` (`size="wide"`: 600 px) | the permissions editor is `wide` |
| Something that stays at the top of a dialog or drawer | `toolbar` (Dialog / Sheet) | under the title, doesn't scroll: the permissions' search box |
| A control beside a dialog's close button | `headerEnd` (Dialog / Sheet) | the product editor's language picker |
| A toggle on a row (several, compact…) | `FilterChip size="sm" tone pressed` | takes its colour when on; a toned `IconButton` with `aria-pressed` (the favourite's heart) keeps its colour while on |
| Print only this | `PrintArea` (+ `PrintSheet` for cards to cut out) | rendered into `<body>`, hidden on screen; while mounted, printing prints only it. One per page |
| Section titles inside a panel or drawer | `text-overline font-semibold uppercase tracking-wide text-ink-3` + a `flex-1 border-t border-line` rule after it | as the navigation's group titles |
The manager's own building blocks (until they move to `@xenia/ui`): `Panel`, `Table`, `Stat` in `pages/reports/kit/parts.jsx`; `Card`, `Figure`, `Pill`, `SplitBar` in `pages/overview/parts.jsx`.
## 4. Type and spacing tokens
| Token / class | Value | Use |
|---|---|---|
| `text-overline` + `font-semibold uppercase tracking-wide text-ink-3` | 11 px | the small labels over figures and sections ("REVENUE", "TOTAL"). Never `text-caption` for these |
| `text-caption` | 12 px | hints, sub-lines |
| `text-label` | 13 px | rows in summaries, table cells, chips |
| `text-body` | 14 px | body text |
| `p-card`, `px-card`, `py-card-y` | 20 px / 14 px | inside every card, panel and section: header rows (`px-card py-card-y`) and bodies (`p-card`) |
## 5. Tables
- `Table` cells are vertically **centred** (`align-middle`): a one-line cell sits in the middle of a two-line row.
- Row actions last, right-aligned, `IconButton size="sm" variant="ghost"`.
- A column's help is `tip` (an `InfoTip` in the header, opens on hover).
## 6. Before you finish a UI change
1. `npm run build:manager` and `npm run lint -w manager-dashboard` pass.
2. `npm test -w @xenia/ui` (contrast in every look) passes.
3. `node tests/e2e/manager_layout.mjs` passes; look at its screenshots in `tests/e2e/out/manager-layout/`.
4. Live preview while working: `npx vite --port 5184` in `manager_dashboard/` (hot reload, uses the running backend on :8000; touches nothing in Docker).
**After a change to `packages/ui/tailwind-preset.js`, restart every running dev server.** Vite reloads CSS and components, but Tailwind reads the preset only at start: a server started before the change never makes the new classes (`p-card`, `text-overline`, `max-w-page` …), and cards lose all their padding.
+22 -5
View File
File diff suppressed because one or more lines are too long
+25
View File
@@ -0,0 +1,25 @@
# Third-party software shipped in the backend image
Xenia POS's own code is not covered by this file. It lists separate programs that are shipped
inside the backend image and run by it as separate processes.
## FFmpeg
- **What it does here:** makes the still frame and the screen-friendly version of uploaded
videos (`services/video.py`, plan step 5.4e). The backend starts it as a separate program and
reads its output; nothing of FFmpeg is linked into Xenia's code.
- **Where it comes from:** the `imageio-ffmpeg` Python package, version pinned in
`requirements.txt` (0.8.1). The package carries one static FFmpeg build per platform
(Linux x86-64 / ARM64: FFmpeg 9.0.2 built by the imageio project from the BtbN FFmpeg-Builds
scripts; Windows: the gyan.dev "essentials" build). Inside the image the program is at
`/usr/local/lib/python3.12/site-packages/imageio_ffmpeg/binaries/`.
- **Licence:** FFmpeg is free software under the **GNU General Public License, version 3 or
later** (built with `--enable-gpl --enable-version3`, no non-free parts). It includes x264
(GPL v2 or later) and other libraries under the GPL / LGPL. The full licence text:
<https://www.gnu.org/licenses/gpl-3.0.txt>. `ffmpeg -L` prints the licence of the build.
- **Source code:** FFmpeg: <https://ffmpeg.org/download.html> (git tag `n9.0.2`). Build scripts:
<https://github.com/BtbN/FFmpeg-Builds> and <https://github.com/imageio/imageio-ffmpeg>.
On request we provide the exact corresponding source of the FFmpeg build shipped with any
Xenia POS release, for at least three years after that release.
- **The package around it** (`imageio-ffmpeg`): BSD 2-Clause licence,
Copyright (c) 2019-2025, imageio.
+50
View File
@@ -0,0 +1,50 @@
"""Allergens (plan step 6.3): the 14 that EU Regulation 1169/2011 (Annex II) requires a venue
to declare. A fixed list in code, in the Annex's order; labels live in the i18n packages
(`common:allergens.<key>`), the same list in `packages/access/src/allergens.js`.
A product stores what it has (`products.allergens`, JSON) as {key: level}:
contains it is in the recipe
may_contain traces, e.g. made in the same kitchen ("may contain")
A key that isn't listed means neither. Unknown keys or levels are refused (catalog.allergen).
"""
from __future__ import annotations
import json
ALLERGENS: tuple[str, ...] = (
"gluten", "crustaceans", "eggs", "fish", "peanuts", "soybeans", "milk",
"nuts", "celery", "mustard", "sesame", "sulphites", "lupin", "molluscs",
)
LEVELS: tuple[str, ...] = ("contains", "may_contain")
def normalize(value) -> dict[str, str]:
"""A product's allergens as {key: level} in the list's order; raises XeniaError on anything else."""
from core.errors import XeniaError
if value in (None, "", {}):
return {}
if isinstance(value, str):
value = json.loads(value)
if not isinstance(value, dict):
raise XeniaError("catalog.allergen", allergen=str(value))
for key, level in value.items():
if key not in ALLERGENS or level not in LEVELS:
raise XeniaError("catalog.allergen", allergen=f"{key}: {level}")
return {k: value[k] for k in ALLERGENS if k in value}
def of(product) -> dict[str, str]:
"""What a product row stores, read safely (bad data in the column: nothing)."""
raw = getattr(product, "allergens", None)
if not raw:
return {}
try:
return normalize(raw)
except Exception:
return {}
def dump(value) -> str | None:
"""For the column: JSON, or None when there are none."""
data = normalize(value)
return json.dumps(data) if data else None
+53
View File
@@ -0,0 +1,53 @@
"""Smart day filters (owner 2026-11-21): the 1st / last day of the month, its first / last week, and
Greek public holidays (fixed dates and those that follow the Orthodox Easter).
The same rules in JavaScript: packages/signage/src/logic.js (a screen applies its schedule while
the server is down); both sides are tested with the same dates.
"""
from __future__ import annotations
import calendar
from datetime import date, timedelta
# the filters a schedule line can have: any one that holds is enough, except "not_holiday",
# which keeps the line off on public holidays
MONTH_DAYS = ("first", "last", "first_week", "last_week", "holiday", "not_holiday")
_FIXED = ((1, 1), (1, 6), (3, 25), (5, 1), (8, 15), (10, 28), (12, 25), (12, 26))
# days from the Orthodox Easter Sunday: Clean Monday, Good Friday, Easter Sunday, Easter Monday, Whit Monday
_FROM_EASTER = (-48, -2, 0, 1, 50)
def orthodox_easter(year: int) -> date:
"""The Orthodox Easter Sunday (Meeus' Julian algorithm, + 13 days to the Gregorian calendar, 1900-2099)."""
a, b, c = year % 4, year % 7, year % 19
d = (19 * c + 15) % 30
e = (2 * a + 4 * b - d + 34) % 7
month = (d + e + 114) // 31
day = (d + e + 114) % 31 + 1
return date(year, month, day) + timedelta(days=13)
def is_holiday(day: date) -> bool:
"""A Greek public holiday (nationwide)."""
if (day.month, day.day) in _FIXED:
return True
easter = orthodox_easter(day.year)
return any(day == easter + timedelta(days=n) for n in _FROM_EASTER)
def month_days_ok(tokens, day: date) -> bool:
"""Does a day pass a line's smart filters (empty = every day)?"""
tokens = [t for t in (tokens or []) if t in MONTH_DAYS]
if not tokens:
return True
hol = is_holiday(day)
if "not_holiday" in tokens and hol:
return False
wanted = [t for t in tokens if t != "not_holiday"]
if not wanted:
return True
last = calendar.monthrange(day.year, day.month)[1]
return any((t == "first" and day.day == 1) or (t == "last" and day.day == last)
or (t == "first_week" and day.day <= 7) or (t == "last_week" and day.day > last - 7)
or (t == "holiday" and hol) for t in wanted)
+174 -3
View File
@@ -11,8 +11,8 @@ Every error response has this shape:
New and converted code raises XeniaError: New and converted code raises XeniaError:
raise XeniaError("order.not_found", order_id=order_id) raise XeniaError("order.not_found", order_id=order_id)
The status comes from the registry below; pass status= only to override it. The status comes from the registry below; pass status= only to override it.
Plain HTTPException (still in most v1 routers; converted gradually, plan step 6.x) Plain HTTPException is wrapped as code "http.<status>" with its original `detail` untouched
is wrapped as code "http.<status>" with its original `detail` untouched. (the routers have none since step 6.1; tests/test_errors.py refuses new ones).
Request validation errors become "validation.invalid" with the field errors in params. Request validation errors become "validation.invalid" with the field errors in params.
Unhandled exceptions become "internal.error" (500) with the request id in params. Unhandled exceptions become "internal.error" (500) with the request id in params.
@@ -57,6 +57,7 @@ CODES: dict[str, tuple[int, str]] = {
"auth.invalid_credentials": (401, "Wrong username or password."), "auth.invalid_credentials": (401, "Wrong username or password."),
"auth.session_ended": (401, "Your session has ended. Please log in again."), "auth.session_ended": (401, "Your session has ended. Please log in again."),
"auth.session_exists": (409, "You're already logged in on another {client}. Log out there first."), "auth.session_exists": (409, "You're already logged in on another {client}. Log out there first."),
"auth.session_elsewhere": (409, "You're signed in on another device ({device}, since {since}). Continue? It will be signed out."),
"auth.login_mode_not_allowed": (403, "This way of logging in isn't enabled ({mode})."), "auth.login_mode_not_allowed": (403, "This way of logging in isn't enabled ({mode})."),
"auth.mode_needs_device": (403, "Logging in by {mode} only works on a paired device."), "auth.mode_needs_device": (403, "Logging in by {mode} only works on a paired device."),
"auth.username_required": (422, "Enter your username."), "auth.username_required": (422, "Enter your username."),
@@ -99,7 +100,7 @@ CODES: dict[str, tuple[int, str]] = {
"display.look_default": (409, "The default look can't be deleted. Make another look the default first."), "display.look_default": (409, "The default look can't be deleted. Make another look the default first."),
"display.not_a_display": (404, "Device {device_id} isn't a customer display."), "display.not_a_display": (404, "Device {device_id} isn't a customer display."),
"media.not_found": (404, "File {media_id} isn't in the media library."), "media.not_found": (404, "File {media_id} isn't in the media library."),
"media.type": (422, "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4 or WebM)."), "media.type": (422, "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4, MOV or WebM)."),
"media.too_big": (413, "The file is too big (at most {max_mb} MB)."), "media.too_big": (413, "The file is too big (at most {max_mb} MB)."),
"media.too_many_pixels": (422, "The picture is too large (at most {max_mp} megapixels)."), "media.too_many_pixels": (422, "The picture is too large (at most {max_mp} megapixels)."),
"media.unreadable": (422, "This picture can't be read. Save it again as JPG or PNG and upload it."), "media.unreadable": (422, "This picture can't be read. Save it again as JPG or PNG and upload it."),
@@ -110,13 +111,27 @@ CODES: dict[str, tuple[int, str]] = {
"signage.not_a_screen": (404, "Device {device_id} isn't a signage screen."), "signage.not_a_screen": (404, "Device {device_id} isn't a signage screen."),
"signage.schedule_unknown": (404, "Schedule {schedule_id} not found."), "signage.schedule_unknown": (404, "Schedule {schedule_id} not found."),
"signage.not_a_video": (422, "Pick a video for this slide."), "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.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.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."), "signage.weather_offline": (503, "The weather service can't be reached: the venue's server needs internet for it."),
"menu_tablet.no_table": (409, "This tablet isn't at a table, so it can't call a waiter."),
"menu_tablet.call_too_soon": (429, "A waiter was just called. Try again in {seconds} seconds."),
"menu_tablet.no_ordering": (409, "Ordering isn't on for this tablet."),
"menu_tablet.too_many": (422, "At most {most} items in one order."),
"menu_tablet.too_many_of": (422, "At most {most} of \"{name}\" in one order."),
"menu_tablet.too_soon": (429, "An order was just sent. Try again in {seconds} seconds."),
"menu_tablet.table_closed": (409, "Please ask a waiter to open your table first."),
"menu_tablet.day_closed": (409, "The venue isn't taking orders right now. Please ask a waiter."),
"menu_tablet.no_staff": (409, "There is no staff account to place the order with."),
"menu_tablet.order_not_found": (404, "This order was not found."),
"menu_tablet.order_answered": (409, "This order was already answered."),
"media.builtin": (409, "Built-in pictures can't be deleted or renamed."), "media.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.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.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
"reservation.table_unknown": (404, "Table {table_id} not found."), "reservation.table_unknown": (404, "Table {table_id} not found."),
"reservation.table_kept": (409, "That table is already kept for {name} at {time}."),
"reservation.table_busy": (409, "That table already has an open order. Pick another table, or close that order first."), "reservation.table_busy": (409, "That table already has an open order. Pick another table, or close that order first."),
"kds.item_not_found": (404, "Item {item_id} not found on this order."), "kds.item_not_found": (404, "Item {item_id} not found on this order."),
"kds.item_claimed": (409, "{name} is already on this item."), "kds.item_claimed": (409, "{name} is already on this item."),
@@ -145,6 +160,162 @@ CODES: dict[str, tuple[int, str]] = {
"system.log_not_found": (404, "There is no log file for {date}."), "system.log_not_found": (404, "There is no log file for {date}."),
"catalog.unknown_category": (422, "There is no category {category_id}."), "catalog.unknown_category": (422, "There is no category {category_id}."),
"catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."), "catalog.primary_not_listed": (422, "The main category ({category_id}) must be one of the product's categories."),
"catalog.allergen": (422, "Unknown allergen or level: {allergen}."),
"catalog.translation": (422, "The menu can't be translated like that: {what}."),
# converted from HTTPException (plan step 6.1)
"auth.password_current_required": (400, "Enter your current password to set a new one."),
"auth.no_password": (400, "This account has no password yet."),
"auth.password_wrong": (400, "The current password is wrong."),
"auth.password_too_short": (400, "The password must be at least {min} characters long."),
"auth.pin_too_short": (400, "The PIN must be at least {min} digits long."),
"license.locked": (423, "The system was locked by the administrator. Contact support."),
"settings.invalid_json": (422, "The settings must be valid JSON."),
"settings.unknown_key": (400, "There is no setting {key}."),
"business_day.already_open": (400, "A business day is already open."),
"business_day.none_open": (404, "No business day is open."),
"business_day.closed": (403, "The venue isn't open: a manager must open the business day first."),
"business_day.orders_open": (409, "{open_orders} table(s) still open, {partially_paid} with unpaid items."),
"business_day.not_found": (404, "Business day not found."),
"business_day.not_closed": (400, "Only a closed business day can be edited."),
"business_day.close_in_future": (400, "The closing time can't be in the future."),
"business_day.close_before_last_order": (400, "The closing time can't be earlier than the last order's close ({time})."),
"business_day.delete_open": (400, "An open business day can't be deleted. Close it first."),
"business_day.has_shifts": (409, "This business day has {count} shift(s). Delete those first."),
"validation.datetime": (422, "That date or time isn't valid."),
"validation.choice": (400, "{field} can't be {value}."),
"validation.range": (400, "{field} must be between {min} and {max}."),
"validation.positive": (400, "{field} must be more than zero."),
"validation.missing": (400, "{field} is required."),
"validation.lan_ip": (422, "Enter a local network IPv4 address (e.g. 192.168.1.50 or 10.0.0.5)."),
"chat.not_found": (404, "Conversation not found."),
"chat.not_participant": (403, "You're not in this conversation."),
"chat.empty_message": (400, "The message is empty."),
"chat.system_group": (403, "You can't leave the staff group."),
"chat.leave_direct": (400, "A one-to-one conversation can't be left."),
"chat.direct_two": (400, "A one-to-one conversation has exactly two people."),
"chat.group_name": (400, "A group conversation needs a name."),
"customer.not_found": (404, "Customer not found."),
"transfer.wrong_type": (400, "This file isn't a {expected} export."),
"transfer.version": (400, "This export's version isn't supported."),
"contact.not_found": (404, "Contact not found."),
"expense.not_found": (404, "Expense not found."),
"expense.over_due": (400, "That's more than what is still due ({due})."),
"expense.below_paid": (400, "{paid} has been paid already: the total can't be less."),
"expense.document_not_found": (404, "Document not found."),
"channel_price.not_found": (404, "Channel price not found."),
"channel_price.set_one_product": (400, "A set price is for one product: pick one product (and no categories), or change the price by an amount or a percentage."),
"scene.not_found": (404, "Scene {scene_id} not found."),
"scene.until_past": (400, "That time has already passed: pick a later one."),
"signage.scene_unknown": (404, "Scene {scene_id} not found."),
"signage.screen_unknown": (404, "Screen {device_id} not found."),
"expense.document_type": (422, "Upload a PDF or a photo (JPG, PNG, WebP or HEIC)."),
"expense.document_too_big": (413, "The file is too big (at most {max_mb} MB)."),
"flag.not_found": (404, "Mark not found."),
"flag.in_use": (409, "This mark is on {count} table(s). Remove it there first."),
"flag.invalid_ids": (400, "Some of these marks don't exist."),
"staff_message.template_not_found": (404, "Message template not found."),
"staff_message.not_found": (404, "Message not found."),
"note.not_found": (404, "Note not found."),
"todo.not_found": (404, "To-do not found."),
"order.not_yours": (403, "This order isn't one of your tables."),
"order.not_open": (400, "This order isn't open any more."),
"order.item_not_found": (404, "That item isn't on the order any more."),
"order.item_paid": (400, "This item is already paid."),
"order.item_not_active": (400, "Only items still on the order can be changed."),
"order.price_change_off": (403, "Changing prices by hand is turned off for this venue."),
"order.one_more_off": (400, "\"One more\" isn't turned on for this product."),
"order.one_more_line": (400, "This line can't be ordered again with one tap."),
"order.quantity_change_off": (403, "Changing quantities is turned off for this venue."),
"order.quantity_remove_off": (403, "Quantities can only go up at this venue."),
"order.quantity_invalid": (400, "Choose a whole number from 1 to {max}."),
"order.quantity_line": (400, "This line's quantity can't be changed here."),
"order.price_change_sent_off": (403, "Prices can only be changed before the items are sent."),
"order.price_reason_required": (400, "Say why the price changes."),
"split.not_allowed": (403, "Splitting a bill this way isn't turned on for this venue."),
"split.lines_changed": (409, "Some of these items were paid or changed meanwhile. Look again."),
"split.amount_invalid": (400, "Each part must be more than 0 and less than the total ({total})."),
"split.part_locked": (400, "This is part of a split bill: undo the split to change it."),
"split.not_found": (404, "That split bill isn't there any more."),
"split.paid_already": (409, "A part is already paid or on a tab: the split can't be undone."),
"split.parts_unpaid": (400, "Parts of a split bill are still unpaid: take their payment first."),
"order.nothing_paid": (404, "There are no paid items to undo."),
"order.cannot_close": (400, "This order can't be closed now ({status})."),
"order.no_active_items": (400, "None of these items are on the order any more."),
"order.waiter_assigned": (400, "That waiter is already on this order."),
"order.assignment_not_found": (404, "That waiter isn't on this order."),
"order.same_table": (400, "The order is already on that table."),
"order.same_order": (400, "An order can't be joined with itself."),
"order.target_not_found": (404, "The other order isn't there any more."),
"order.split_quantity": (400, "Split into 1 to {max} pieces."),
"order.discounts_off": (403, "Discounts are turned off for this venue."),
"order.no_customer": (400, "Give the order a customer first."),
"order.item_not_tabbable": (400, "This item is already {status}: it can't go on a tab."),
"order.product_unavailable": (400, "Product {product_id} isn't available."),
"printer.not_found": (404, "That printer isn't there or is turned off."),
"print_job.not_found": (404, "That print job isn't there any more."),
"print_job.not_pending": (400, "Only tickets still waiting to print can be cancelled."),
"print_job.done": (409, "That ticket isn't waiting any more: it was printed or dealt with on another screen."),
"print.printer_off": (409, "The printer {printer} is turned off in the settings."),
"print.redirect_failed": (502, "{printer} didn't print it either ({error}). The ticket is still waiting."),
"table.not_found": (404, "Table not found."),
"floor_plan.not_found": (404, "Floor plan not found."),
"floor_plan.bad_outline": (422, "The floor's shape needs 3 to 100 corners, all inside the plan."),
"floor_plan.bad_zone": (422, "That zone no longer exists."),
"floor_plan.bad_background": (422, "The background must be a picture from the media library."),
"floor_plan.bad_layout": (422, "The layout has a table twice or a place that is not a number."),
"table.busy": (400, "That table already has an open order."),
"table.has_order": (400, "A table with an open order can't be deleted or turned off."),
"table.name_too_long": (400, "The table names would be too long ({name}: at most {max} characters). Shorten the prefix or make fewer."),
"table_group.name_taken": (400, "There is already a group with that name."),
"table_group.not_found": (404, "Table group not found."),
"prep_zone.not_found": (404, "Prep zone not found."),
"price_group.not_found": (404, "Price group not found."),
"modifier.not_found": (404, "Price rule not found."),
"deal.not_found": (404, "Deal not found."),
"pricing.bad_condition": (422, "A condition is incomplete: fill in all its values."),
"pricing.bad_limit": (422, "A discount limit must be a number of 0 or more, or empty for no limit."),
"catalog.category_not_found": (404, "Category not found."),
"catalog.parent_not_found": (404, "The parent category doesn't exist."),
"catalog.nest_has_children": (400, "A category with sub-categories can't go under another one."),
"catalog.too_deep": (400, "Categories go at most two levels deep."),
"catalog.own_parent": (400, "A category can't be its own parent."),
"catalog.group_not_found": (404, "Option group not found."),
"product.not_found": (404, "Product not found."),
"product.in_past_orders": (400, "This product is in past orders, so it can't be deleted. Archive it instead."),
"staff.not_found": (404, "Staff member not found."),
"staff.username_taken": (409, "That username is already taken."),
"staff.superadmin_protected": (403, "A superadmin account can't be changed."),
"staff.superadmin_only": (403, "Only a superadmin can give the superadmin role."),
"staff.role_invalid": (400, "There is no role {role}."),
"staff.avatar_type": (400, "The photo must be a picture file."),
"staff.assignment_exists": (400, "That assignment already exists."),
"staff.pin_invalid": (422, "A PIN is {min} to {max} digits."),
"staff.username_needed": (422, "Every person needs a username."),
"staff.password_own": (409, "Change your own password from your profile."),
"staff.delete_self": (409, "You can't delete yourself."),
"staff.has_history": (409, "{name} has orders or shifts on record, so they can't be deleted. Block them instead: they can't sign in, and the reports keep their name."),
"staff.assignment_not_found": (404, "Assignment not found."),
"schedule.shift_not_found": (404, "Scheduled shift not found."),
"schedule.bad_time": (422, "Times are written like 09:30."),
"schedule.overlap": (409, "{name} already has a shift from {start} to {end} that day."),
"setup.done": (409, "Setup is already done: a manager account exists."),
"shift.already_active": (400, "This person already has a shift going."),
"shift.start_needs_manager": (403, "Starting the shift needs a manager's approval."),
"shift.end_needs_manager": (403, "Ending the shift needs a manager's approval."),
"shift.others_need_manager": (403, "Only managers can start shifts for other staff."),
"shift.none_active": (404, "No shift is going."),
"shift.not_found": (404, "Shift not found."),
"shift.not_yours": (403, "This shift belongs to someone else."),
"shift.ended": (400, "This shift has already ended."),
"shift.on_break": (400, "A break is already going."),
"shift.no_break": (404, "No break is going."),
"shift.delete_active": (400, "A shift that is still going can't be deleted. End it first."),
"tab.not_found": (404, "Tab not found."),
"tab.already_open": (400, "This customer already has an open tab."),
"tab.over_balance": (400, "That's more than the balance ({balance})."),
"tab.has_balance": (400, "The tab still owes {balance}. Pay it or forgive it first."),
"waste.not_found": (404, "Throwaway entry not found."),
"waste.not_today": (403, "Only throwaways of the open business day can be deleted."),
} }
+20 -2
View File
@@ -53,7 +53,8 @@
"paid_total": "Πληρωμενο: {value:.2f}e", "paid_total": "Πληρωμενο: {value:.2f}e",
"pending": "ΕΚΚΡΕΜΗ:", "pending": "ΕΚΚΡΕΜΗ:",
"remaining": "Εκκρεμει: {value:.2f}e", "remaining": "Εκκρεμει: {value:.2f}e",
"title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ" "title": "ΣΥΝΟΨΗ ΠΑΡΑΓΓΕΛΙΑΣ",
"split": "ΔΙΑΧΩΡΙΣΜΟΣ (ΕΞΟΦΛΕΙΤΑΙ ΑΠΟ ΤΑ ΜΕΡΗ):"
}, },
"ticket": { "ticket": {
"compact_guests": " | {count}ατ.", "compact_guests": " | {count}ατ.",
@@ -89,13 +90,30 @@
"print": { "print": {
"failed_final": "Ένα δελτίο της παραγγελίας #{order_id} δεν τυπώθηκε ποτέ στον εκτυπωτή {printer} ({attempts} προσπάθειες).", "failed_final": "Ένα δελτίο της παραγγελίας #{order_id} δεν τυπώθηκε ποτέ στον εκτυπωτή {printer} ({attempts} προσπάθειες).",
"failing": "Ένα δελτίο της παραγγελίας #{order_id} δεν έχει τυπωθεί ακόμα στον εκτυπωτή {printer} (αποτυχημένες προσπάθειες μέχρι τώρα: {attempts}· συνεχίζει να προσπαθεί). Ελέγξτε τον εκτυπωτή." "failing": "Ένα δελτίο της παραγγελίας #{order_id} δεν έχει τυπωθεί ακόμα στον εκτυπωτή {printer} (αποτυχημένες προσπάθειες μέχρι τώρα: {attempts}· συνεχίζει να προσπαθεί). Ελέγξτε τον εκτυπωτή."
},
"business_day": {
"not_open": "Είναι {time} και η ημέρα δεν έχει ανοίξει.",
"open_blocked": "Η ημέρα δεν άνοιξε μόνη της στις {time}: η άδεια δεν το επιτρέπει ({reason}).",
"tables_open": "Είναι ώρα κλεισίματος ({time}) αλλά {count} παραγγελίες είναι ακόμα ανοιχτές. Η ημέρα κλείνει μόνη της μόλις κλείσουν.",
"not_closed": "Η ημέρα έπρεπε να κλείσει στις {time} και είναι ακόμα ανοιχτή."
} }
}, },
"system_product": { "system_product": {
"delivery_fee": "Μεταφορικά" "delivery_fee": "Μεταφορικά",
"split_part": "Διαχωρισμός λογαριασμού"
}, },
"qr": { "qr": {
"order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.", "order_message": "Τραπέζι {table}: νέα παραγγελία από το QR μενού ({count} τεμ.), στάλθηκε στην κουζίνα.",
"sender": "QR μενού" "sender": "QR μενού"
},
"tablet": {
"call_message": "Τραπεζι {table}: οι πελατες καλουν σερβιτορο.",
"sender": "Tablet μενου",
"order_sent": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), στάλθηκε στην κουζίνα.",
"order_waiting": "Τραπέζι {table}: παραγγελία από το tablet ({count} τεμ.), επιβεβαιώστε τη στο τραπέζι.",
"bill_message": "Τραπέζι {table}: οι πελάτες ζητούν τον λογαριασμό."
},
"split": {
"part_name": "Μέρος λογαριασμού {n}/{of}"
} }
} }
+20 -2
View File
@@ -53,7 +53,8 @@
"paid_total": "Paid: {value:.2f}e", "paid_total": "Paid: {value:.2f}e",
"pending": "PENDING:", "pending": "PENDING:",
"remaining": "Remaining: {value:.2f}e", "remaining": "Remaining: {value:.2f}e",
"title": "ORDER SUMMARY" "title": "ORDER SUMMARY",
"split": "SPLIT BILL (SETTLED BY THE PARTS):"
}, },
"ticket": { "ticket": {
"compact_guests": " | {count}pax", "compact_guests": " | {count}pax",
@@ -89,13 +90,30 @@
"print": { "print": {
"failed_final": "A ticket for order #{order_id} never printed on {printer} ({attempts} attempts).", "failed_final": "A ticket for order #{order_id} never printed on {printer} ({attempts} attempts).",
"failing": "A ticket for order #{order_id} hasn't printed on {printer} yet (failed attempts so far: {attempts}; still retrying). Check the printer." "failing": "A ticket for order #{order_id} hasn't printed on {printer} yet (failed attempts so far: {attempts}; still retrying). Check the printer."
},
"business_day": {
"not_open": "It's {time} and the day isn't open.",
"open_blocked": "The day didn't open by itself at {time}: the license doesn't allow it ({reason}).",
"tables_open": "It's closing time ({time}) but {count} orders are still open. The day closes by itself once they are closed.",
"not_closed": "The day should have closed at {time} and is still open."
} }
}, },
"system_product": { "system_product": {
"delivery_fee": "Delivery fee" "delivery_fee": "Delivery fee",
"split_part": "Split bill"
}, },
"qr": { "qr": {
"order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.", "order_message": "Table {table}: new order from the QR menu ({count} items), sent to the kitchen.",
"sender": "QR menu" "sender": "QR menu"
},
"tablet": {
"call_message": "Table {table}: the guests call a waiter.",
"sender": "Menu tablet",
"order_sent": "Table {table} ordered from the tablet ({count} items): sent to the kitchen.",
"order_waiting": "Table {table} ordered from the tablet ({count} items): confirm it on the table.",
"bill_message": "Table {table}: the guests ask for the bill."
},
"split": {
"part_name": "Split bill {n}/{of}"
} }
} }
+149
View File
@@ -0,0 +1,149 @@
"""The menu in other languages (plan step 6.4, owner decisions 2026-11-18, D-29; every text per
language, owner 2026-11-21).
Since 2026-11-21 (Alembic 0042) every text of the menu is kept **per language**, the venue's own
language included: a product's name and description, a category's name, and every choice's name
(quick options, ingredients, extras and their sub-choices, preference sets, their choices,
sub-choices and shared sub-set, choice groups). The editor's "Default" is the venue's language
(`venue.language`). The row's own `name` / `description` is the text shown when a language has
none: the venue language's, else the first language that has one. So when the venue changes its
language, the new language starts empty ("Default" is empty) but the item keeps showing its only
text everywhere; languages are never mixed.
products.translations {"el": {"name": "…", "description": "…"}, "en": {…}}
categories.translations {"el": {"name": "…"}, …}
a choice's translations {"el": "…", "en": "…"} (the rows' column; sub-choices inside their JSON)
Before 0042 the base text had no language and quick options were translated on the product
(`"quick": {"<quick option's name>": "…"}`); 0042 moved those onto the quick options.
The menu's languages are English and Greek (fixed for now). A product's own name and
description are its base text, in whatever language the venue typed them (usually the venue's
language). Translations add the other language:
products.translations {"en": {"name": "…", "description": "…", "quick": {"<quick option's name>": "…"}}}
categories.translations {"en": {"name": "…"}}
Quick options are kept by their base name (they are recreated on every product save, so ids
change). A missing translation shows the base text, whatever its language — never Latin letters,
never a machine translation (owner). Who sees translations: the customer-facing screens (QR menu,
order app, menu tablet, signage menu boards), and since 6R.L the waiters' phones and the counter
show menu names in the staff member's language, for display only (`@xenia/access` useMenuText;
`routers/pos.py` sends every text per language). Order lines, tickets and the kitchen display keep
the base text (the venue's): apps send ids, and sub-choices by their stored name.
"""
from __future__ import annotations
import json
MENU_LANGUAGES: tuple[str, ...] = ("el", "en")
PRODUCT_FIELDS = ("name", "description")
def _load(value):
if value in (None, "", {}):
return {}
if isinstance(value, str):
try:
value = json.loads(value)
except ValueError:
return {}
return value if isinstance(value, dict) else {}
def _bad(what):
from core.errors import XeniaError
return XeniaError("catalog.translation", what=what)
def normalize_product(value) -> dict:
"""API input → the stored shape; empty texts dropped; unknown languages or fields refused."""
data = _load(value)
out = {}
for lang, fields in data.items():
if lang not in MENU_LANGUAGES or not isinstance(fields, dict):
raise _bad(lang)
clean = {}
for k, v in fields.items():
if k in PRODUCT_FIELDS:
if v is not None and not isinstance(v, str):
raise _bad(f"{lang}.{k}")
if (v or "").strip():
clean[k] = v.strip()
elif k == "quick":
if not isinstance(v, dict):
raise _bad(f"{lang}.quick")
quick = {str(base): str(text).strip() for base, text in v.items() if str(text or "").strip()}
if quick:
clean["quick"] = quick
else:
raise _bad(f"{lang}.{k}")
if clean:
out[lang] = clean
return out
def normalize_category(value) -> dict:
data = _load(value)
out = {}
for lang, fields in data.items():
if lang not in MENU_LANGUAGES or not isinstance(fields, dict) or set(fields) - {"name"}:
raise _bad(lang)
if (fields.get("name") or "").strip():
out[lang] = {"name": fields["name"].strip()}
return out
def dump(data: dict) -> str | None:
return json.dumps(data, ensure_ascii=False) if data else None
def of(row) -> dict:
"""A product's or category's stored translations, read safely."""
return _load(getattr(row, "translations", None))
def texts(base: str | None, translations: dict, field: str) -> dict:
"""{language: text} for every menu language: the translation, else the base text."""
return {lang: (translations.get(lang) or {}).get(field) or base for lang in MENU_LANGUAGES}
def quick_texts(base: str, translations: dict, own: dict | None = None) -> dict:
"""A quick option's texts: its own translations (since 0042), else the product's old
`quick` map, else the base text."""
own = own or {}
return {lang: own.get(lang) or ((translations.get(lang) or {}).get("quick") or {}).get(base) or base for lang in MENU_LANGUAGES}
def product_texts(product, customer: bool = True) -> dict:
"""{"names": {lang: …}, "descriptions": {lang: …}} for a customer-facing screen. `customer`:
the customer apps' own name / description (digital_*) are the base when set."""
tr = of(product)
name = (product.digital_name if customer else None) or product.name
desc = (product.digital_description if customer else None) or product.description
return {"names": texts(name, tr, "name"), "descriptions": texts(desc or None, tr, "description")}
def normalize_names(value) -> dict:
"""A choice's translations {language: text}: API input → stored; empty texts dropped."""
data = _load(value)
out = {}
for lang, text in data.items():
if text is not None and not isinstance(text, str):
raise _bad(str(lang))
if not (text or "").strip():
continue # empty: nothing to keep, whatever the language
if lang not in MENU_LANGUAGES:
raise _bad(str(lang))
out[lang] = text.strip()
return out
def names_of(row) -> dict:
"""A choice row's translations {language: text}, read safely."""
return {k: v for k, v in _load(getattr(row, "translations", None)).items() if isinstance(v, str)}
def name_texts(base: str, names: dict) -> dict:
"""{language: text} of a choice for every menu language: its own, else the base text."""
return {lang: names.get(lang) or base for lang in MENU_LANGUAGES}
+17
View File
@@ -38,6 +38,22 @@ router = APIRouter()
_optional_bearer = HTTPBearer(auto_error=False) _optional_bearer = HTTPBearer(auto_error=False)
def _identity_brief(db) -> dict:
"""What every app needs of the venue's identity (6R.20): its first colour (the accent when
venue.theme is "identity"), the slogan and the logos' addresses. Public, like the venue's name."""
try:
from routers.identity import identity_out
ident = identity_out(db)
except Exception:
return {"colour": None, "slogan": None, "logo": None, "logo_light": None, "logo_dark": None, "icon": None}
logos = ident.get("logos") or {}
def card(k):
return (logos.get(k) or {}).get("card")
return {"colour": (ident.get("colours") or [{}])[0].get("colour"), "slogan": ident.get("slogan"),
"logo": card("main"), "logo_light": card("light"), "logo_dark": card("dark"), "icon": (logos.get("icon") or {}).get("thumb")}
def permission_keys_for(user) -> list[str]: def permission_keys_for(user) -> list[str]:
"""The keys a user holds (user_permissions; superadmin: every key).""" """The keys a user holds (user_permissions; superadmin: every key)."""
from core.access.check import user_keys from core.access.check import user_keys
@@ -113,6 +129,7 @@ def bootstrap(
"language": i18n.venue_language(), "language": i18n.venue_language(),
"currency": _setting(db, "venue.currency", "EUR"), "currency": _setting(db, "venue.currency", "EUR"),
"theme": _setting(db, "venue.theme", "amber") or "amber", # the accent colour (4.6, data-venue-theme) "theme": _setting(db, "venue.theme", "amber") or "amber", # the accent colour (4.6, data-venue-theme)
"identity": _identity_brief(db), # 6R.20: its colour and logos for the apps
"business_day_rollover_hour": timeutil.rollover_hour(), "business_day_rollover_hour": timeutil.rollover_hour(),
}, },
"modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective], "modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective],
+7 -3
View File
@@ -55,9 +55,13 @@ def _ref_exists(source: str, value: int, db) -> bool:
if source == "signage_playlists": if source == "signage_playlists":
from models.signage import SignagePlaylist from models.signage import SignagePlaylist
return db.get(SignagePlaylist, value) is not None return db.get(SignagePlaylist, value) is not None
if source == "signage_schedules": if source == "signage_slides":
from models.signage import SignageSchedule from models.signage import SignageSavedSlide
return db.get(SignageSchedule, value) is not None return db.get(SignageSavedSlide, value) is not None
if source == "tables":
from models.table import Table
t = db.get(Table, value)
return t is not None and bool(t.is_active)
if source == "display_looks": if source == "display_looks":
from models.display_look import DisplayLook from models.display_look import DisplayLook
return db.get(DisplayLook, value) is not None return db.get(DisplayLook, value) is not None
+22
View File
@@ -85,6 +85,7 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
row = db.query(Notification).filter( row = db.query(Notification).filter(
Notification.dedupe_key == dedupe_key, Notification.dedupe_key == dedupe_key,
(Notification.expires_at.is_(None)) | (Notification.expires_at > now), (Notification.expires_at.is_(None)) | (Notification.expires_at > now),
Notification.resolved_at.is_(None),
).order_by(Notification.id.desc()).first() ).order_by(Notification.id.desc()).first()
if row is not None: if row is not None:
if not fold: if not fold:
@@ -119,6 +120,27 @@ def notify(key: str, severity: str, audience: str, params: dict | None = None, *
db.close() db.close()
def resolve(db, dedupe_keys) -> int:
"""Sticky alerts whose cause is gone (6F.8): hide the live rows with these dedupe keys.
Sends `platform_notification` {id, resolved: true} so open bells refresh. Commits."""
from models.notification import Notification
rows = db.query(Notification).filter(Notification.dedupe_key.in_(list(dedupe_keys)),
Notification.resolved_at.is_(None)).all()
if not rows:
return 0
now = utcnow()
for r in rows:
r.resolved_at = now
db.commit()
try:
from services.ws_bus import broadcast_sync
for r in rows:
broadcast_sync(EVENT, {"id": r.id, "resolved": True}, user_ids=recipients(db, r.audience))
except Exception:
logger.exception("notification.resolve_event_failed")
return len(rows)
# ── producers that need a little logic ─────────────────────────────────────── # ── producers that need a little logic ───────────────────────────────────────
EXPIRY_WARN_DAYS = (14, 7, 3, 1) EXPIRY_WARN_DAYS = (14, 7, 3, 1)
+41 -5
View File
@@ -2,7 +2,11 @@
Sessions Sessions
- start(db, user, client, request) creates a row and applies the client's single-session - start(db, user, client, request) creates a row and applies the client's single-session
rule (setting auth.single_session_<client>: off | refuse_new | end_old). rule (setting auth.single_session_<client>: off | refuse_new | end_old | ask).
`ask` (waiters, the default since 6F.7): a login while signed in elsewhere is refused with
auth.session_elsewhere (where, since when) until the app retries with replace=True; then
the old sessions end with reason "replaced" (their sockets get session.ended at once).
Only the waiter's phones count: a terminal session (the counter) is its own client.
- validate(sid) is called on every authenticated request (routers.deps.decode_token). - validate(sid) is called on every authenticated request (routers.deps.decode_token).
Results are cached for CACHE_TTL_S; end()/end_for_user() drop the cache entry at once, Results are cached for CACHE_TTL_S; end()/end_for_user() drop the cache entry at once,
so an ended session is refused on its very next request. so an ended session is refused on its very next request.
@@ -61,15 +65,32 @@ def _setting(db, key: str, default: str) -> str:
def single_session_rule(db, client: str) -> str: def single_session_rule(db, client: str) -> str:
return _setting(db, f"auth.single_session_{client}", "off") if client in ("manager", "waiter") else "off" if client == "waiter":
return _setting(db, "auth.single_session_waiter", "ask") # 6F.7: ask is the default
return _setting(db, "auth.single_session_manager", "off") if client == "manager" else "off"
# ── lifecycle ──────────────────────────────────────────────────────────────── # ── lifecycle ────────────────────────────────────────────────────────────────
def start(db, user, client: str, request=None, *, device=None, expires_at=None): def device_label(user_agent: str | None) -> str:
"""A short, language-neutral name for where a session runs ("Android · Chrome")."""
ua = user_agent or ""
system = next((name for key, name in (("iPhone", "iPhone"), ("iPad", "iPad"), ("Android", "Android"),
("Windows", "Windows"), ("Macintosh", "Mac"), ("Linux", "Linux"))
if key in ua), "")
browser = next((name for key, name in (("EdgA", "Edge"), ("Edg/", "Edge"), ("Firefox", "Firefox"), ("FxiOS", "Firefox"),
("CriOS", "Chrome"), ("Chrome", "Chrome"), ("Safari", "Safari"))
if key in ua), "")
if "; wv)" in ua:
browser = "app"
return " · ".join(x for x in (system, browser) if x)
def start(db, user, client: str, request=None, *, device=None, expires_at=None, replace: bool = False):
"""Create a session for user (None user_id for the support account). Commits. """Create a session for user (None user_id for the support account). Commits.
`device`: the paired device of a terminal login; its previous sessions are replaced `device`: the paired device of a terminal login; its previous sessions are replaced
(a shared screen shows one user at a time).""" (a shared screen shows one user at a time). `replace`: the person said yes to signing
out their other session (rule `ask`)."""
from models.session import LoginSession from models.session import LoginSession
if client not in CLIENTS: if client not in CLIENTS:
raise ValueError(f"unknown client {client!r}") raise ValueError(f"unknown client {client!r}")
@@ -80,6 +101,11 @@ def start(db, user, client: str, request=None, *, device=None, expires_at=None):
LoginSession.ended_at.is_(None)).all() LoginSession.ended_at.is_(None)).all()
if active and rule == "refuse_new": if active and rule == "refuse_new":
raise XeniaError("auth.session_exists", client=client) raise XeniaError("auth.session_exists", client=client)
if active and rule == "ask" and not replace:
last = max(active, key=lambda s: s.created_at)
from core.timeutil import iso_z
raise XeniaError("auth.session_elsewhere", client=client, since=iso_z(last.created_at),
device=device_label(last.user_agent) or "?", ip=last.ip or "")
for s in active: for s in active:
_end_row(s, "replaced") _end_row(s, "replaced")
if device is not None: if device is not None:
@@ -186,7 +212,8 @@ def validate(sid: str | None, db=None) -> Active:
if row is None or row.ended_at is not None: if row is None or row.ended_at is not None:
with _lock: with _lock:
_cache.pop(sid, None) _cache.pop(sid, None)
raise XeniaError("auth.session_ended") # why it ended (replaced, logout, idle...): the app can say "you signed in elsewhere"
raise XeniaError("auth.session_ended", reason=(row.end_reason if row is not None else None) or "unknown")
info = Active(row.user_id, row.device_id, row.expires_at) info = Active(row.user_id, row.device_id, row.expires_at)
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S) stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
finally: finally:
@@ -233,3 +260,12 @@ def waiter_login_mode(db) -> str:
def waiter_requires_username(db) -> bool: def waiter_requires_username(db) -> bool:
return _setting(db, "auth.waiter_require_username", "false") == "true" return _setting(db, "auth.waiter_require_username", "false") == "true"
def terminal_requires_username(db, device=None) -> bool:
"""Paired screens (6F.7): type a username instead of picking a name. The device's own
choice (Device.require_username) wins over the venue's auth.terminal_require_username."""
own = getattr(device, "require_username", None)
if own is not None:
return bool(own)
return _setting(db, "auth.terminal_require_username", "false") == "true"
+8 -1
View File
@@ -66,6 +66,8 @@ async def lifespan(app: FastAPI):
from services.tls_identity import ensure_tls_identity from services.tls_identity import ensure_tls_identity
ensure_tls_identity() ensure_tls_identity()
start_print_retry_thread() start_print_retry_thread()
from services.video import start_worker as start_video_worker
start_video_worker() # videos' still frames and playable versions (5.4e)
pruned = prune_old_events(hours=24) pruned = prune_old_events(hours=24)
if pruned: if pruned:
logger.info("ws_bus: pruned %d old sync_events", pruned) logger.info("ws_bus: pruned %d old sync_events", pruned)
@@ -77,7 +79,10 @@ async def lifespan(app: FastAPI):
from core.modules import supervisor from core.modules import supervisor
supervisor.start(loop) supervisor.start(loop)
reservation_task = await start_reservation_tasks() reservation_task = await start_reservation_tasks()
from services import day_auto
day_task = await day_auto.start() # the day opens / closes by itself (6F.8)
yield yield
day_task.cancel()
supervisor.stop_all() supervisor.stop_all()
sync_task.cancel() sync_task.cancel()
reservation_task.cancel() reservation_task.cancel()
@@ -112,12 +117,14 @@ async def _menu_change_push(request, call_next):
def _signage_menu_changed() -> None: def _signage_menu_changed() -> None:
"""The signage screens showing a menu board read it again (plan step 5.4b).""" """The signage screens showing a menu board (5.4b) and the menu tablets (5.7a) read their menu again."""
try: try:
from routers.menu_tablet import menu_changed as tablet_menu_changed
from routers.signage import menu_changed as signage_menu_changed from routers.signage import menu_changed as signage_menu_changed
db = SessionLocal() db = SessionLocal()
try: try:
signage_menu_changed(db) signage_menu_changed(db)
tablet_menu_changed(db) # the menu tablets read their menu again (5.7a)
finally: finally:
db.close() db.close()
except Exception as e: # never breaks the request that changed the menu except Exception as e: # never breaks the request that changed the menu
@@ -0,0 +1,29 @@
"""Video versions (plan step 5.4e): a video's still frame and a version every screen plays are
made in the background after the upload; the library shows how far it got.
Videos already in the library are queued (`waiting`) so they get theirs too.
Revision ID: 0031_video_versions
Revises: 0030_signage_schedules
Create Date: 2026-11-18 09:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0031_video_versions'
down_revision = '0030_signage_schedules'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('media', schema=None) as batch_op:
batch_op.add_column(sa.Column('processing', sa.String(), nullable=True))
batch_op.add_column(sa.Column('progress', sa.Integer(), nullable=True))
op.execute("UPDATE media SET processing = 'waiting' WHERE kind = 'video'")
def downgrade() -> None:
with op.batch_alter_table('media', schema=None) as batch_op:
batch_op.drop_column('progress')
batch_op.drop_column('processing')
@@ -0,0 +1,24 @@
"""Allergens (plan step 6.3): the 14 EU allergens per product, each "contains" or
"may contain" (core/allergens.py), as JSON {key: level}; null = none declared.
Revision ID: 0032_product_allergens
Revises: 0031_video_versions
Create Date: 2026-11-18 12:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0032_product_allergens'
down_revision = '0031_video_versions'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.add_column(sa.Column('allergens', sa.Text(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('products', schema=None) as batch_op:
batch_op.drop_column('allergens')
@@ -0,0 +1,26 @@
"""The menu in other languages (plan step 6.4, core/menu_languages.py): a product's and a
category's translations as JSON {language: {field: text}}; null = none.
Revision ID: 0033_menu_translations
Revises: 0032_product_allergens
Create Date: 2026-11-18 15:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0033_menu_translations'
down_revision = '0032_product_allergens'
branch_labels = None
depends_on = None
def upgrade() -> None:
for table in ('products', 'categories'):
with op.batch_alter_table(table, schema=None) as batch_op:
batch_op.add_column(sa.Column('translations', sa.Text(), nullable=True))
def downgrade() -> None:
for table in ('products', 'categories'):
with op.batch_alter_table(table, schema=None) as batch_op:
batch_op.drop_column('translations')
@@ -0,0 +1,47 @@
"""Orders from a menu tablet at a table (plan step 6.6, D-30, models/tablet_order.py).
Revision ID: 0034_tablet_orders
Revises: 0033_menu_translations
Create Date: 2026-11-18 16:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0034_tablet_orders'
down_revision = '0033_menu_translations'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'tablet_orders',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('device_id', sa.Integer(), nullable=True),
sa.Column('table_id', sa.Integer(), nullable=True),
sa.Column('lines', sa.JSON(), nullable=False),
sa.Column('note', sa.Text(), nullable=True),
sa.Column('total', sa.Float(), nullable=False),
sa.Column('status', sa.String(), nullable=False),
sa.Column('order_id', sa.Integer(), nullable=True),
sa.Column('reason', sa.String(), nullable=True),
sa.Column('decided_by_id', sa.Integer(), nullable=True),
sa.Column('decided_at', UTCDateTime(), nullable=True),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.ForeignKeyConstraint(['decided_by_id'], ['users.id'], ondelete='SET NULL'),
sa.ForeignKeyConstraint(['device_id'], ['devices.id'], ondelete='SET NULL'),
sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ondelete='SET NULL'),
sa.ForeignKeyConstraint(['table_id'], ['tables.id'], ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id'),
)
with op.batch_alter_table('tablet_orders', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_tablet_orders_created_at'), ['created_at'], unique=False)
batch_op.create_index(batch_op.f('ix_tablet_orders_device_id'), ['device_id'], unique=False)
batch_op.create_index(batch_op.f('ix_tablet_orders_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_tablet_orders_status'), ['status'], unique=False)
batch_op.create_index(batch_op.f('ix_tablet_orders_table_id'), ['table_id'], unique=False)
def downgrade() -> None:
op.drop_table('tablet_orders')
@@ -0,0 +1,85 @@
"""Floor plans, their walls / bar / labels / areas, and the tables' place on a plan
(plan step 6.8, D-31, models/floor_plan.py). Existing tables stay off any plan.
Revision ID: 0035_floor_plans
Revises: 0034_tablet_orders
Create Date: 2026-11-18 16:05:26
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0035_floor_plans'
down_revision = '0034_tablet_orders'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'floor_plans',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('group_id', sa.Integer(), nullable=True),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('width', sa.Integer(), nullable=False),
sa.Column('height', sa.Integer(), nullable=False),
sa.Column('outline', sa.JSON(), nullable=True),
sa.Column('grid_on', sa.Boolean(), nullable=False),
sa.Column('grid_size', sa.Integer(), nullable=False),
sa.Column('media_id', sa.Integer(), nullable=True),
sa.Column('background_opacity', sa.Float(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.ForeignKeyConstraint(['group_id'], ['table_groups.id'], ondelete='SET NULL'),
sa.ForeignKeyConstraint(['media_id'], ['media.id'], ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id'),
)
with op.batch_alter_table('floor_plans', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_floor_plans_group_id'), ['group_id'], unique=False)
batch_op.create_index(batch_op.f('ix_floor_plans_id'), ['id'], unique=False)
op.create_table(
'floor_items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('plan_id', sa.Integer(), nullable=False),
sa.Column('kind', sa.String(), nullable=False),
sa.Column('x', sa.Float(), nullable=False),
sa.Column('y', sa.Float(), nullable=False),
sa.Column('width', sa.Float(), nullable=False),
sa.Column('height', sa.Float(), nullable=False),
sa.Column('rotation', sa.Float(), nullable=False),
sa.Column('text', sa.String(), nullable=True),
sa.ForeignKeyConstraint(['plan_id'], ['floor_plans.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'),
)
with op.batch_alter_table('floor_items', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_floor_items_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_floor_items_plan_id'), ['plan_id'], unique=False)
with op.batch_alter_table('tables', schema=None) as batch_op:
batch_op.add_column(sa.Column('plan_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('width', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('height', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('rotation', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('shape', sa.String(), nullable=True))
batch_op.create_index(batch_op.f('ix_tables_plan_id'), ['plan_id'], unique=False)
batch_op.create_foreign_key('fk_tables_plan_id_floor_plans', 'floor_plans', ['plan_id'], ['id'], ondelete='SET NULL')
def downgrade() -> None:
with op.batch_alter_table('tables', schema=None) as batch_op:
batch_op.drop_constraint('fk_tables_plan_id_floor_plans', type_='foreignkey')
batch_op.drop_index(batch_op.f('ix_tables_plan_id'))
batch_op.drop_column('shape')
batch_op.drop_column('rotation')
batch_op.drop_column('height')
batch_op.drop_column('width')
batch_op.drop_column('plan_id')
with op.batch_alter_table('floor_items', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_floor_items_plan_id'))
batch_op.drop_index(batch_op.f('ix_floor_items_id'))
op.drop_table('floor_items')
with op.batch_alter_table('floor_plans', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_floor_plans_id'))
batch_op.drop_index(batch_op.f('ix_floor_plans_group_id'))
op.drop_table('floor_plans')
@@ -0,0 +1,28 @@
"""A print job's way out besides printing (plan step 6.10): who resolved it and, when the
ticket was sent to another printer, which one. `status` gains no new value: a ticket sent
elsewhere ends as 'success' (redirected_to set), one marked as handled as 'cancelled' with
cancel_reason 'handled'.
Revision ID: 0036_print_job_resolution
Revises: 0035_floor_plans
Create Date: 2026-11-19 09:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0036_print_job_resolution'
down_revision = '0035_floor_plans'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('print_jobs', schema=None) as batch_op:
batch_op.add_column(sa.Column('resolved_by', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('redirected_to', sa.Integer(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('print_jobs', schema=None) as batch_op:
batch_op.drop_column('redirected_to')
batch_op.drop_column('resolved_by')
@@ -0,0 +1,47 @@
"""Tabs in the books (plan step 6.13c, KI-018): a line put on a tab and a payment on a tab
record the business day and the shift they happened in (the shift of whoever did it, if they
were on one), so a shift shows what it put on tabs and the tab money it received, and the
day shows both. Existing rows get their business day from when they happened.
Revision ID: 0037_tab_books
Revises: 0036_print_job_resolution
Create Date: 2026-11-19 12:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0037_tab_books'
down_revision = '0036_print_job_resolution'
branch_labels = None
depends_on = None
TABLES = ('tab_entries', 'tab_payments')
def upgrade() -> None:
for t in TABLES:
with op.batch_alter_table(t, schema=None) as batch_op:
batch_op.add_column(sa.Column('business_day_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('shift_id', sa.Integer(), nullable=True))
batch_op.create_index(f'ix_{t}_business_day_id', ['business_day_id'])
batch_op.create_index(f'ix_{t}_shift_id', ['shift_id'])
batch_op.create_foreign_key(f'fk_{t}_business_day_id_business_days', 'business_days', ['business_day_id'], ['id'])
batch_op.create_foreign_key(f'fk_{t}_shift_id_waiter_shifts', 'waiter_shifts', ['shift_id'], ['id'])
# the day each existing row happened in (a closed day's window, or the open one)
op.execute(f"""
UPDATE {t} SET business_day_id = (
SELECT d.id FROM business_days d
WHERE d.opened_at <= {t}.created_at AND (d.closed_at IS NULL OR d.closed_at >= {t}.created_at)
ORDER BY d.opened_at DESC LIMIT 1)
""")
def downgrade() -> None:
for t in TABLES:
with op.batch_alter_table(t, schema=None) as batch_op:
batch_op.drop_constraint(f'fk_{t}_shift_id_waiter_shifts', type_='foreignkey')
batch_op.drop_constraint(f'fk_{t}_business_day_id_business_days', type_='foreignkey')
batch_op.drop_index(f'ix_{t}_shift_id')
batch_op.drop_index(f'ix_{t}_business_day_id')
batch_op.drop_column('shift_id')
batch_op.drop_column('business_day_id')
@@ -0,0 +1,101 @@
"""Indexes on the columns the screens look rows up by (UI review 2026-11-20).
The order lines had no index on their order, the orders none on their day or customer, and so
on: every report and the customers list read whole tables once per order, so a few thousand
orders made Customers take ~2 s and Reports → Days ~15 s (and time out). One index per column
below; the models carry index=True so new databases get them too.
Revision ID: 0038_lookup_indexes
Revises: 0037_tab_books
Create Date: 2026-11-20 15:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0038_lookup_indexes'
down_revision = '0037_tab_books'
branch_labels = None
depends_on = None
INDEXES = [
('orders', 'table_id'),
('orders', 'business_day_id'),
('orders', 'customer_id'),
('orders', 'status'),
('orders', 'opened_at'),
('order_items', 'order_id'),
('order_items', 'product_id'),
('order_items', 'paid_in_shift_id'),
('order_items', 'status'),
('order_waiters', 'order_id'),
('order_waiters', 'waiter_id'),
('order_audit_log', 'order_id'),
('order_discounts', 'order_id'),
('print_jobs', 'order_id'),
('print_log', 'order_id'),
('waiter_shifts', 'waiter_id'),
('waiter_shifts', 'business_day_id'),
('tab_entries', 'tab_id'),
('tab_entries', 'order_id'),
('tab_entries', 'order_item_id'),
('tab_payments', 'tab_id'),
('tabs', 'customer_id'),
('expenses', 'business_day_id'),
('expenses', 'contact_id'),
('expense_payments', 'expense_id'),
('reservations', 'order_id'),
('reservations', 'table_id'),
('phone_calls', 'customer_id'),
('waste_log', 'business_day_id'),
('waste_log', 'product_id'),
('tables', 'group_id'),
('scheduled_shifts', 'user_id'),
('shift_breaks', 'shift_id'),
('chat_messages', 'conversation_id'),
('conversation_participants', 'conversation_id'),
('conversation_participants', 'user_id'),
('staff_message_acks', 'message_id'),
('price_modifier_conditions', 'modifier_id'),
('price_modifier_targets', 'modifier_id'),
('deal_conditions', 'deal_id'),
('deal_targets', 'deal_id'),
('product_ingredients', 'product_id'),
('product_modifier_groups', 'product_id'),
('product_options', 'product_id'),
('product_preference_sets', 'product_id'),
('product_preference_choices', 'set_id'),
('product_quick_options', 'product_id'),
('tablet_orders', 'order_id'),
]
# what a person did in a time window (a shift's orders and lines)
PAIRS = [
('orders', ('opened_by', 'opened_at')),
('order_items', ('added_by', 'added_at')),
]
def _existing(table: str) -> set[str]:
return {ix['name'] for ix in sa.inspect(op.get_bind()).get_indexes(table)}
def upgrade() -> None:
for table, column in INDEXES:
name = f'ix_{table}_{column}'
if name not in _existing(table):
op.create_index(name, table, [column])
for table, columns in PAIRS:
name = f'ix_{table}_{"_".join(columns)}'
if name not in _existing(table):
op.create_index(name, table, list(columns))
def downgrade() -> None:
for table, columns in PAIRS:
name = f'ix_{table}_{"_".join(columns)}'
if name in _existing(table):
op.drop_index(name, table_name=table)
for table, column in reversed(INDEXES):
name = f'ix_{table}_{column}'
if name in _existing(table):
op.drop_index(name, table_name=table)
@@ -0,0 +1,54 @@
"""Expense lines and documents (UI review 2026-11-20): what an expense bought (quantity, price
before VAT, VAT rate; the lines make the total) and the files kept with it (the invoice as a
PDF, a photo of the receipt).
Revision ID: 0039_expense_lines_documents
Revises: 0038_lookup_indexes
Create Date: 2026-11-20 16:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0039_expense_lines_documents'
down_revision = '0038_lookup_indexes'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'expense_lines',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('expense_id', sa.Integer(), nullable=False),
sa.Column('position', sa.Integer(), nullable=False),
sa.Column('description', sa.String(), nullable=False),
sa.Column('quantity', sa.Float(), nullable=False),
sa.Column('unit_price', sa.Float(), nullable=False),
sa.Column('vat_rate', sa.Float(), nullable=False),
sa.ForeignKeyConstraint(['expense_id'], ['expenses.id']),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_expense_lines_id', 'expense_lines', ['id'])
op.create_index('ix_expense_lines_expense_id', 'expense_lines', ['expense_id'])
op.create_table(
'expense_documents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('expense_id', sa.Integer(), nullable=False),
sa.Column('filename', sa.String(), nullable=False),
sa.Column('stored_name', sa.String(), nullable=False),
sa.Column('content_type', sa.String(), nullable=False),
sa.Column('size', sa.Integer(), nullable=False),
sa.Column('uploaded_by_id', sa.Integer(), nullable=True),
sa.Column('uploaded_at', UTCDateTime(), nullable=True),
sa.ForeignKeyConstraint(['expense_id'], ['expenses.id']),
sa.ForeignKeyConstraint(['uploaded_by_id'], ['users.id']),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_expense_documents_id', 'expense_documents', ['id'])
op.create_index('ix_expense_documents_expense_id', 'expense_documents', ['expense_id'])
def downgrade() -> None:
op.drop_table('expense_documents')
op.drop_table('expense_lines')
@@ -0,0 +1,40 @@
"""Order channel prices (UI review 2026-11-20): a product's price at a sales point, set per
product, per category or for the whole channel (services/channel_prices.py).
Revision ID: 0040_channel_prices
Revises: 0039_expense_lines_documents
Create Date: 2026-11-20 17:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0040_channel_prices'
down_revision = '0039_expense_lines_documents'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'channel_prices',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('sales_points', sa.Text(), nullable=False),
sa.Column('product_ids', sa.Text(), nullable=False),
sa.Column('category_ids', sa.Text(), nullable=False),
sa.Column('action_type', sa.String(), nullable=False),
sa.Column('value', sa.Float(), nullable=False),
sa.Column('round_to', sa.String(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=True),
sa.Column('updated_at', UTCDateTime(), nullable=True),
sa.Column('updated_by', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['updated_by'], ['users.id']),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_channel_prices_id', 'channel_prices', ['id'])
def downgrade() -> None:
op.drop_table('channel_prices')
@@ -0,0 +1,23 @@
"""A floor area's colour (UI review 2026-11-20): "#rrggbb", drawn see-through on the plan.
Revision ID: 0041_floor_item_color
Revises: 0040_channel_prices
Create Date: 2026-11-20 18:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0041_floor_item_color'
down_revision = '0040_channel_prices'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('floor_items', schema=None) as batch_op:
batch_op.add_column(sa.Column('color', sa.String(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('floor_items', schema=None) as batch_op:
batch_op.drop_column('color')
@@ -0,0 +1,123 @@
"""Every menu text per language (owner 2026-11-21, core/menu_languages.py).
- Every choice gets its own `translations` {language: text}: choice groups, quick options,
extras, ingredients, preference sets and their choices (sub-choices and a set's shared
sub-set keep theirs inside their JSON).
- The texts typed so far had no language: they become the text **in their language**: Greek
letters → "el", else the venue's language (`venue.language`, default "en"). A language that
already had a translation keeps it.
- The product's old `"quick": {"<quick option's name>": "…"}` translations move onto the quick
options.
Revision ID: 0042_menu_texts_per_language
Revises: 0041_floor_item_color
Create Date: 2026-11-21 12:00:00
"""
import json
import re
from alembic import op
import sqlalchemy as sa
revision = '0042_menu_texts_per_language'
down_revision = '0041_floor_item_color'
branch_labels = None
depends_on = None
CHOICE_TABLES = ('product_modifier_groups', 'product_quick_options', 'product_options', 'product_ingredients',
'product_preference_sets', 'product_preference_choices')
GREEK = re.compile('[Ͱ-Ͽἀ-῿]')
LANGS = ('el', 'en')
def _load(v):
if not v:
return {}
try:
d = json.loads(v)
except ValueError:
return {}
return d if isinstance(d, (dict, list)) else {}
def _dump(d):
return json.dumps(d, ensure_ascii=False) if d else None
def upgrade() -> None:
for table in CHOICE_TABLES:
with op.batch_alter_table(table, schema=None) as batch_op:
batch_op.add_column(sa.Column('translations', sa.Text(), nullable=True))
bind = op.get_bind()
row = bind.execute(sa.text("SELECT value FROM pos_settings WHERE key = 'venue.language'")).first()
venue = (row[0] if row else None) or 'en'
venue = venue if venue in LANGS else 'en'
def lang_of(text):
return 'el' if GREEK.search(text or '') else venue
def names(text, current=None):
out = dict(current or {})
if (text or '').strip():
out.setdefault(lang_of(text), text.strip())
return out
def subs(raw):
"""Sub-choices (a JSON list of dicts) with their names per language."""
data = _load(raw)
if not isinstance(data, list) or not data:
return raw
for s in data:
if isinstance(s, dict):
s['translations'] = names(s.get('name'), s.get('translations') if isinstance(s.get('translations'), dict) else None)
return json.dumps(data, ensure_ascii=False)
# products: name / description in their language; the quick options' translations move out
quick_moved = {}
for pid, name, desc, tr in bind.execute(sa.text("SELECT id, name, description, translations FROM products")).fetchall():
data = _load(tr)
data = data if isinstance(data, dict) else {}
for lang, fields in list(data.items()):
if not isinstance(fields, dict):
data.pop(lang)
continue
for base, text in (fields.pop('quick', None) or {}).items():
quick_moved.setdefault(pid, {}).setdefault(base, {})[lang] = text
for field, text in (('name', name), ('description', desc)):
if (text or '').strip():
data.setdefault(lang_of(text), {}).setdefault(field, text.strip())
data = {k: v for k, v in data.items() if v}
bind.execute(sa.text("UPDATE products SET translations = :t WHERE id = :id"), {'t': _dump(data), 'id': pid})
for cid, name, tr in bind.execute(sa.text("SELECT id, name, translations FROM categories")).fetchall():
data = _load(tr)
data = data if isinstance(data, dict) else {}
if (name or '').strip():
data.setdefault(lang_of(name), {}).setdefault('name', name.strip())
bind.execute(sa.text("UPDATE categories SET translations = :t WHERE id = :id"), {'t': _dump(data), 'id': cid})
for qid, pid, name in bind.execute(sa.text("SELECT id, product_id, name FROM product_quick_options")).fetchall():
bind.execute(sa.text("UPDATE product_quick_options SET translations = :t WHERE id = :id"),
{'t': _dump(names(name, quick_moved.get(pid, {}).get(name))), 'id': qid})
for table in ('product_modifier_groups', 'product_ingredients'):
for rid, name in bind.execute(sa.text(f"SELECT id, name FROM {table}")).fetchall():
bind.execute(sa.text(f"UPDATE {table} SET translations = :t WHERE id = :id"), {'t': _dump(names(name)), 'id': rid})
for table in ('product_options', 'product_preference_choices'):
for rid, name, sub in bind.execute(sa.text(f"SELECT id, name, sub_choices FROM {table}")).fetchall():
bind.execute(sa.text(f"UPDATE {table} SET translations = :t, sub_choices = :s WHERE id = :id"),
{'t': _dump(names(name)), 's': subs(sub), 'id': rid})
for rid, name, shared in bind.execute(sa.text("SELECT id, name, shared_subset FROM product_preference_sets")).fetchall():
data = _load(shared)
if isinstance(data, dict) and data:
data['translations'] = names(data.get('name'))
data['choices'] = json.loads(subs(json.dumps(data.get('choices') or [])) or '[]')
shared = json.dumps(data, ensure_ascii=False)
bind.execute(sa.text("UPDATE product_preference_sets SET translations = :t, shared_subset = :s WHERE id = :id"),
{'t': _dump(names(name)), 's': shared, 'id': rid})
def downgrade() -> None:
for table in CHOICE_TABLES:
with op.batch_alter_table(table, schema=None) as batch_op:
batch_op.drop_column('translations')
@@ -0,0 +1,119 @@
"""Scenes, and signage schedule lines that name their screens (owner 2026-11-21).
- `scenes`: named modes of the venue (party mode…) that are on or off (models/scene.py).
- `signage_schedule_items` replaces the named schedules of 5.4d: each line has its playlist, its
screens ([] = every screen), its priority, days, hours, dates, smart days and an optional scene.
A schedule's lines become lines for the screens that had that schedule (a schedule no screen
used: its lines are kept, turned off). A screen's own playlist is its default; a screen on a
schedule without its own playlist gets the schedule's "otherwise" playlist as its default.
The device config key `schedule` is gone.
- The key `core.scenes.manage` for owners and store managers.
Revision ID: 0043_scenes_and_schedule_items
Revises: 0042_menu_texts_per_language
Create Date: 2026-11-21 16:00:00
"""
import json
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0043_scenes_and_schedule_items'
down_revision = '0042_menu_texts_per_language'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'scenes',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('color', sa.String(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.Column('activated_at', UTCDateTime(), nullable=True),
sa.Column('until', UTCDateTime(), nullable=True),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_scenes_id', 'scenes', ['id'])
op.create_table(
'signage_schedule_items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('playlist_id', sa.Integer(), sa.ForeignKey('signage_playlists.id', ondelete='CASCADE'), nullable=False),
sa.Column('screen_ids', sa.JSON(), nullable=False),
sa.Column('priority', sa.Integer(), nullable=False),
sa.Column('enabled', sa.Boolean(), nullable=False),
sa.Column('days', sa.JSON(), nullable=False),
sa.Column('month_days', sa.JSON(), nullable=False),
sa.Column('time_from', sa.String(), nullable=True),
sa.Column('time_to', sa.String(), nullable=True),
sa.Column('date_from', sa.String(), nullable=True),
sa.Column('date_to', sa.String(), nullable=True),
sa.Column('scene_id', sa.Integer(), sa.ForeignKey('scenes.id', ondelete='SET NULL'), nullable=True),
sa.Column('position', sa.Integer(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('updated_at', UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_signage_schedule_items_id', 'signage_schedule_items', ['id'])
op.create_index('ix_signage_schedule_items_playlist_id', 'signage_schedule_items', ['playlist_id'])
op.create_index('ix_signage_schedule_items_scene_id', 'signage_schedule_items', ['scene_id'])
bind = op.get_bind()
playlists = {r[0] for r in bind.execute(sa.text("SELECT id FROM signage_playlists")).fetchall()}
screens = []
for did, cfg in bind.execute(sa.text("SELECT id, config FROM devices WHERE app_key = 'signage'")).fetchall():
c = json.loads(cfg) if isinstance(cfg, str) and cfg else (cfg or {})
screens.append((did, c if isinstance(c, dict) else {}))
from datetime import datetime, timezone
stamp = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')
pos = 0
for sid, name, fallback, entries in bind.execute(sa.text("SELECT id, name, fallback_playlist_id, entries FROM signage_schedules ORDER BY id")).fetchall():
entries = json.loads(entries) if isinstance(entries, str) and entries else (entries or [])
on = [did for did, c in screens if c.get('schedule') == sid]
for e in entries:
if e.get('playlist_id') not in playlists:
continue
bind.execute(sa.text(
"INSERT INTO signage_schedule_items (name, playlist_id, screen_ids, priority, enabled, days, month_days, time_from, time_to, "
"date_from, date_to, scene_id, position, created_at, updated_at) VALUES (:name, :pl, :scr, :pri, :en, :days, '[]', :tf, :tt, :df, :dt, "
"NULL, :pos, :now, :now)"),
{'name': name, 'pl': e['playlist_id'], 'scr': json.dumps(on), 'pri': int(e.get('priority') or 0), 'en': bool(on),
'days': json.dumps(e.get('days') or []), 'tf': e.get('time_from'), 'tt': e.get('time_to'),
'df': e.get('date_from'), 'dt': e.get('date_to'), 'pos': pos, 'now': stamp})
pos += 1
for did, c in screens:
if c.get('schedule') == sid and not c.get('playlist') and fallback in playlists:
c['playlist'] = fallback
for did, c in screens:
if 'schedule' in c:
c.pop('schedule')
bind.execute(sa.text("UPDATE devices SET config = :c WHERE id = :id"), {'c': json.dumps(c) if c else None, 'id': did})
elif c.get('playlist'):
bind.execute(sa.text("UPDATE devices SET config = :c WHERE id = :id"), {'c': json.dumps(c), 'id': did})
op.drop_table('signage_schedules')
# the new key core.scenes.manage for owners and store managers (their role's template)
bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, 'core.scenes.manage' from users where role in ('owner', 'store_manager')"))
def downgrade() -> None:
op.create_table(
'signage_schedules',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('fallback_playlist_id', sa.Integer(), sa.ForeignKey('signage_playlists.id', ondelete='SET NULL'), nullable=True),
sa.Column('entries', sa.JSON(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('updated_at', UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.drop_table('signage_schedule_items')
op.drop_table('scenes')
op.get_bind().execute(sa.text("delete from user_permissions where key = 'core.scenes.manage'"))
@@ -0,0 +1,46 @@
"""The signage Slides library (owner 2026-11-21): slides kept with a name and a description, added
to playlists as copies or shown alone as a screen's default (device config `slide`).
Revision ID: 0044_signage_saved_slides
Revises: 0043_scenes_and_schedule_items
Create Date: 2026-11-21 22:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0044_signage_saved_slides'
down_revision = '0043_scenes_and_schedule_items'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'signage_saved_slides',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('description', sa.String(), nullable=True),
sa.Column('orientation', sa.String(), nullable=False),
sa.Column('kind', sa.String(), nullable=False),
sa.Column('duration_s', sa.Integer(), nullable=False),
sa.Column('transition', sa.String(), nullable=True),
sa.Column('video_to_end', sa.Boolean(), nullable=False),
sa.Column('enabled', sa.Boolean(), nullable=False),
sa.Column('days', sa.JSON(), nullable=True),
sa.Column('time_from', sa.String(), nullable=True),
sa.Column('time_to', sa.String(), nullable=True),
sa.Column('date_from', sa.String(), nullable=True),
sa.Column('date_to', sa.String(), nullable=True),
sa.Column('content', sa.JSON(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('updated_at', UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_signage_saved_slides_id', 'signage_saved_slides', ['id'])
def downgrade() -> None:
op.drop_index('ix_signage_saved_slides_id', table_name='signage_saved_slides')
op.drop_table('signage_saved_slides')
@@ -0,0 +1,28 @@
"""Signage slide shapes (6R.13, owner 2026-11-22): a playlist or a library slide may be built for a
custom shape ("21:9", "16:10", …) besides landscape / portrait. NULL = its orientation's 16:9 / 9:16.
Revision ID: 0045_signage_shapes
Revises: 0044_signage_saved_slides
Create Date: 2026-11-22 10:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0045_signage_shapes'
down_revision = '0044_signage_saved_slides'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('signage_playlists') as b:
b.add_column(sa.Column('aspect', sa.String(), nullable=True))
with op.batch_alter_table('signage_saved_slides') as b:
b.add_column(sa.Column('aspect', sa.String(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('signage_saved_slides') as b:
b.drop_column('aspect')
with op.batch_alter_table('signage_playlists') as b:
b.drop_column('aspect')
@@ -0,0 +1,41 @@
"""Media folders (6R.16, owner 2026-11-22): the Media page groups files in folders. Only a grouping in
the database (media.folder_id); the files stay where they are on disk. A gallery widget can show a folder.
Revision ID: 0046_media_folders
Revises: 0045_signage_shapes
Create Date: 2026-11-22 16:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0046_media_folders'
down_revision = '0045_signage_shapes'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'media_folders',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('position', sa.Integer(), nullable=False, server_default='0'),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_media_folders_id', 'media_folders', ['id'])
with op.batch_alter_table('media') as b:
b.add_column(sa.Column('folder_id', sa.Integer(), nullable=True))
b.create_index('ix_media_folder_id', ['folder_id'])
b.create_foreign_key('fk_media_folder', 'media_folders', ['folder_id'], ['id'], ondelete='SET NULL')
def downgrade() -> None:
with op.batch_alter_table('media') as b:
b.drop_constraint('fk_media_folder', type_='foreignkey')
b.drop_index('ix_media_folder_id')
b.drop_column('folder_id')
op.drop_index('ix_media_folders_id', 'media_folders')
op.drop_table('media_folders')
@@ -0,0 +1,45 @@
"""Prices changed by hand, on the record (owner 2026-11-23, plan 6F.3).
- price_event_log: approved_by_user_id, stage (cart | sent | served), quantity, for the new
event type manual_price (services/price_changes.py).
- The keys ordering.prices.modify_sent (everyone who holds ordering.prices.modify today: nobody
loses what they could do) and ordering.prices.view_changes (owners and store managers).
Revision ID: 0047_price_changes
Revises: 0046_media_folders
Create Date: 2026-11-23 12:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0047_price_changes'
down_revision = '0046_media_folders'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('price_event_log') as b:
b.add_column(sa.Column('approved_by_user_id', sa.Integer(), nullable=True))
b.add_column(sa.Column('stage', sa.String(), nullable=True))
b.add_column(sa.Column('quantity', sa.Float(), nullable=True))
b.create_foreign_key('fk_price_event_approved_by', 'users', ['approved_by_user_id'], ['id'])
bind = op.get_bind()
bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select user_id, 'ordering.prices.modify_sent' from user_permissions where key = 'ordering.prices.modify'"))
# a venue that changed a role's default for modify gets the same for modify_sent
bind.execute(sa.text("insert or ignore into role_permissions (role, key, granted) "
"select role, 'ordering.prices.modify_sent', granted from role_permissions where key = 'ordering.prices.modify'"))
bind.execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, 'ordering.prices.view_changes' from users where role in ('owner', 'store_manager')"))
def downgrade() -> None:
bind = op.get_bind()
bind.execute(sa.text("delete from user_permissions where key in ('ordering.prices.modify_sent', 'ordering.prices.view_changes')"))
bind.execute(sa.text("delete from role_permissions where key = 'ordering.prices.modify_sent'"))
with op.batch_alter_table('price_event_log') as b:
b.drop_constraint('fk_price_event_approved_by', type_='foreignkey')
b.drop_column('quantity')
b.drop_column('stage')
b.drop_column('approved_by_user_id')
@@ -0,0 +1,121 @@
"""Moves on the record (owner 2026-11-23, plan 6F.4, services/moves.py).
- order_moves / order_move_items: every table transfer, lines moved, orders merged, with its lines.
- order_items.split_from_id: the line a line was cut from (a split), so its path follows it.
- Backfill from the audit log written before 6F.4 (notes "Transferred from table A to table B",
"Moved to order #N (table T)", "Items merged from order #N (table T)"): one move each, marked
note='backfill'. A transfer's lines are the order's lines added before it; quantities unknown.
Revision ID: 0048_order_moves
Revises: 0047_price_changes
Create Date: 2026-11-23 15:00:00
"""
import json
import re
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0048_order_moves'
down_revision = '0047_price_changes'
branch_labels = None
depends_on = None
_TABLE = r"(?:table )?(\d+|None)"
def _int(v):
return int(v) if v not in (None, "None", "") else None
def upgrade() -> None:
op.create_table(
'order_moves',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('kind', sa.String(), nullable=False),
sa.Column('from_order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=True),
sa.Column('to_order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=True),
sa.Column('from_table_id', sa.Integer(), sa.ForeignKey('tables.id'), nullable=True),
sa.Column('to_table_id', sa.Integer(), sa.ForeignKey('tables.id'), nullable=True),
sa.Column('by_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('approved_by_user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('business_day_id', sa.Integer(), sa.ForeignKey('business_days.id'), nullable=True),
sa.Column('at', UTCDateTime(), nullable=False),
sa.Column('note', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
)
for col in ('id', 'kind', 'from_order_id', 'to_order_id', 'business_day_id', 'at'):
op.create_index(f'ix_order_moves_{col}', 'order_moves', [col])
op.create_table(
'order_move_items',
sa.Column('move_id', sa.Integer(), sa.ForeignKey('order_moves.id', ondelete='CASCADE'), nullable=False),
sa.Column('item_id', sa.Integer(), sa.ForeignKey('order_items.id'), nullable=False),
sa.Column('quantity', sa.Float(), nullable=True),
sa.PrimaryKeyConstraint('move_id', 'item_id'),
)
op.create_index('ix_order_move_items_item_id', 'order_move_items', ['item_id'])
with op.batch_alter_table('order_items') as b:
b.add_column(sa.Column('split_from_id', sa.Integer(), nullable=True))
b.create_index('ix_order_items_split_from_id', ['split_from_id'])
b.create_foreign_key('fk_order_items_split_from', 'order_items', ['split_from_id'], ['id'])
_backfill(op.get_bind())
def _backfill(bind) -> None:
rows = bind.execute(sa.text(
"select a.id, a.order_id, a.event_type, a.waiter_id, a.item_ids, a.note, a.created_at, o.table_id, o.business_day_id "
"from order_audit_log a join orders o on o.id = a.order_id "
"where a.event_type in ('TABLE_TRANSFER', 'ITEMS_MOVED_OUT', 'ITEMS_ADDED') and a.note is not null order by a.id")).fetchall()
existing_items = {r[0] for r in bind.execute(sa.text("select id from order_items")).fetchall()}
existing_orders = {r[0] for r in bind.execute(sa.text("select id from orders")).fetchall()}
def add(kind, frm, to, ft, tt, by, at, day, items):
res = bind.execute(sa.text(
"insert into order_moves (kind, from_order_id, to_order_id, from_table_id, to_table_id, by_user_id, business_day_id, at, note) "
"values (:k, :fo, :to, :ft, :tt, :by, :day, :at, 'backfill')"),
{'k': kind, 'fo': frm if frm in existing_orders else None, 'to': to if to in existing_orders else None,
'ft': ft, 'tt': tt, 'by': by, 'day': day, 'at': at})
mid = res.lastrowid
for iid in sorted({i for i in items if i in existing_items}):
bind.execute(sa.text("insert or ignore into order_move_items (move_id, item_id, quantity) values (:m, :i, null)"),
{'m': mid, 'i': iid})
def ids(raw):
try:
v = json.loads(raw or '[]')
return [int(x) for x in v if isinstance(x, int)]
except (ValueError, TypeError):
return []
for (_id, order_id, kind, by, item_ids, note, at, table_id, day) in rows:
if kind == 'TABLE_TRANSFER':
m = re.match(rf"Transferred from table (\d+|None) to table (\d+|None)", note)
if not m:
continue
items = [r[0] for r in bind.execute(sa.text(
"select id from order_items where order_id = :o and added_at <= :at"), {'o': order_id, 'at': at}).fetchall()]
add('table_transfer', order_id, order_id, _int(m.group(1)), _int(m.group(2)), by, at, day, items)
elif kind == 'ITEMS_MOVED_OUT':
m = re.match(rf"Moved to order #(\d+) \({_TABLE}\)", note)
if not m:
continue
add('items_moved', order_id, int(m.group(1)), table_id, _int(m.group(2)), by, at, day, ids(item_ids))
elif kind == 'ITEMS_ADDED':
m = re.match(rf"Items merged from order #(\d+) \({_TABLE}\)", note)
if not m:
continue
add('orders_merged', int(m.group(1)), order_id, _int(m.group(2)), table_id, by, at, day, ids(item_ids))
def downgrade() -> None:
with op.batch_alter_table('order_items') as b:
b.drop_constraint('fk_order_items_split_from', type_='foreignkey')
b.drop_index('ix_order_items_split_from_id')
b.drop_column('split_from_id')
op.drop_index('ix_order_move_items_item_id', 'order_move_items')
op.drop_table('order_move_items')
for col in ('id', 'kind', 'from_order_id', 'to_order_id', 'business_day_id', 'at'):
op.drop_index(f'ix_order_moves_{col}', 'order_moves')
op.drop_table('order_moves')
@@ -0,0 +1,30 @@
"""One more and quantity changes (owner 2026-11-23, plan 6F.5).
- products.one_more_enabled (off: the owner turns it on per product).
- The key ordering.items.change_quantity for owners and store managers (the venue's setting
orders.quantity_change starts 'off').
Revision ID: 0049_one_more
Revises: 0048_order_moves
Create Date: 2026-11-23 18:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0049_one_more'
down_revision = '0048_order_moves'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('products') as b:
b.add_column(sa.Column('one_more_enabled', sa.Boolean(), nullable=False, server_default='0'))
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select id, 'ordering.items.change_quantity' from users where role in ('owner', 'store_manager')"))
def downgrade() -> None:
op.get_bind().execute(sa.text("delete from user_permissions where key = 'ordering.items.change_quantity'"))
with op.batch_alter_table('products') as b:
b.drop_column('one_more_enabled')
@@ -0,0 +1,59 @@
"""Split the bill by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py).
- split_bills: chosen lines settled together and cut into parts paid on their own.
- order_items.split_bill_id: on the settled lines (status 'split') and on the part lines.
- The key ordering.payments.split_amount for everyone who takes payments (holds
ordering.orders.close); the venue's setting payments.split_amount starts 'off'.
Revision ID: 0050_split_bills
Revises: 0049_one_more
Create Date: 2026-11-23 21:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0050_split_bills'
down_revision = '0049_one_more'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'split_bills',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('order_id', sa.Integer(), sa.ForeignKey('orders.id'), nullable=False),
sa.Column('total', sa.Float(), nullable=False),
sa.Column('mode', sa.String(), nullable=False),
sa.Column('parts', sa.Integer(), nullable=False),
sa.Column('amounts', sa.Text(), nullable=False),
sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('business_day_id', sa.Integer(), sa.ForeignKey('business_days.id'), nullable=True),
sa.Column('undone_at', UTCDateTime(), nullable=True),
sa.Column('undone_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('receipt_issued_at', UTCDateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
)
for col in ('id', 'order_id', 'business_day_id'):
op.create_index(f'ix_split_bills_{col}', 'split_bills', [col])
with op.batch_alter_table('order_items') as b:
b.add_column(sa.Column('split_bill_id', sa.Integer(), nullable=True))
b.create_index('ix_order_items_split_bill_id', ['split_bill_id'])
b.create_foreign_key('fk_order_items_split_bill', 'split_bills', ['split_bill_id'], ['id'])
op.get_bind().execute(sa.text("insert or ignore into user_permissions (user_id, key) "
"select user_id, 'ordering.payments.split_amount' from user_permissions "
"where key = 'ordering.orders.close'"))
def downgrade() -> None:
op.get_bind().execute(sa.text("delete from user_permissions where key = 'ordering.payments.split_amount'"))
with op.batch_alter_table('order_items') as b:
b.drop_constraint('fk_order_items_split_bill', type_='foreignkey')
b.drop_index('ix_order_items_split_bill_id')
b.drop_column('split_bill_id')
for col in ('id', 'order_id', 'business_day_id'):
op.drop_index(f'ix_split_bills_{col}', 'split_bills')
op.drop_table('split_bills')
@@ -0,0 +1,30 @@
"""Sign-in (owner 2026-11-23, plan 6F.7).
- devices.require_username: a paired screen's own choice (NULL = the venue's
auth.terminal_require_username).
- auth.single_session_waiter: 'ask' is the new default; a venue that has the row set to
'off' gets 'ask' too (Q-9). A venue that chose refuse_new / end_old keeps its choice.
Revision ID: 0051_sign_in
Revises: 0050_split_bills
Create Date: 2026-11-23 22:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0051_sign_in'
down_revision = '0050_split_bills'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('devices') as b:
b.add_column(sa.Column('require_username', sa.Boolean(), nullable=True))
op.get_bind().execute(sa.text("update pos_settings set value = 'ask' "
"where key = 'auth.single_session_waiter' and value = 'off'"))
def downgrade() -> None:
with op.batch_alter_table('devices') as b:
b.drop_column('require_username')
@@ -0,0 +1,35 @@
"""The day opens and closes by itself (owner 2026-11-23, plan 6F.8, services/day_auto.py).
- business_days.opened_auto / closed_auto; opened_by_id may be NULL (opened by the system).
- notifications.resolved_at: sticky alerts that stay until their cause is gone.
Revision ID: 0052_day_auto
Revises: 0051_sign_in
Create Date: 2026-11-23 23:30:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0052_day_auto'
down_revision = '0051_sign_in'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('business_days') as b:
b.alter_column('opened_by_id', existing_type=sa.Integer(), nullable=True)
b.add_column(sa.Column('opened_auto', sa.Boolean(), nullable=False, server_default='0'))
b.add_column(sa.Column('closed_auto', sa.Boolean(), nullable=False, server_default='0'))
with op.batch_alter_table('notifications') as b:
b.add_column(sa.Column('resolved_at', UTCDateTime(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('notifications') as b:
b.drop_column('resolved_at')
with op.batch_alter_table('business_days') as b:
b.drop_column('closed_auto')
b.drop_column('opened_auto')
+4 -1
View File
@@ -40,4 +40,7 @@ import models.fees # noqa: F401 DeliveryArea, FeeRule (phase 3S, S.3)
import models.refund # noqa: F401 Refund, RefundItem (step 3.3e) import models.refund # noqa: F401 Refund, RefundItem (step 3.3e)
import models.media # noqa: F401 Media (media library, step 5.1) import models.media # noqa: F401 Media (media library, step 5.1)
import models.display_look # noqa: F401 DisplayLook (customer display looks, step 5.3) import models.display_look # noqa: F401 DisplayLook (customer display looks, step 5.3)
import models.signage # noqa: F401 SignagePlaylist, SignageSlide (signage, step 5.4a) import models.signage # noqa: F401 SignagePlaylist, SignageSlide, SignageSavedSlide (signage, 5.4a; library 2026-11-21)
import models.scene # noqa: F401 Scene (2026-11-21)
import models.tablet_order # noqa: F401 TabletOrder (ordering from a menu tablet, step 6.6)
import models.floor_plan # noqa: F401 FloorPlan, FloorItem (the table map, step 6.8)
+4 -2
View File
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Date, Integer, String, Float, ForeignKey, Text from sqlalchemy import Boolean, Column, Date, Integer, String, Float, ForeignKey, Text
from core.timeutil import UTCDateTime, utcnow from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
from database import Base from database import Base
@@ -15,7 +15,9 @@ class BusinessDay(Base):
# The date this day counts as (D-11): set once when the day opens with # The date this day counts as (D-11): set once when the day opens with
# core.timeutil.business_date_of(opened_at), never recalculated. Reports group by it. # core.timeutil.business_date_of(opened_at), never recalculated. Reports group by it.
business_date = Column(Date, nullable=False, index=True) business_date = Column(Date, nullable=False, index=True)
opened_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) opened_by_id = Column(Integer, ForeignKey("users.id"), nullable=True) # NULL = opened by the system (6F.8)
opened_auto = Column(Boolean, nullable=False, default=False) # 6F.8: opened / closed by
closed_auto = Column(Boolean, nullable=False, default=False) # services/day_auto.py
closed_at = Column(UTCDateTime, nullable=True) closed_at = Column(UTCDateTime, nullable=True)
closed_by_id = Column(Integer, ForeignKey("users.id"), nullable=True) closed_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
notes = Column(Text, nullable=True) notes = Column(Text, nullable=True)
+3 -3
View File
@@ -32,8 +32,8 @@ class ConversationParticipant(Base):
__tablename__ = "conversation_participants" __tablename__ = "conversation_participants"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False) conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False) user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
joined_at = Column(UTCDateTime, default=utcnow) joined_at = Column(UTCDateTime, default=utcnow)
last_read_at = Column(UTCDateTime, nullable=True) last_read_at = Column(UTCDateTime, nullable=True)
@@ -45,7 +45,7 @@ class ChatMessage(Base):
__tablename__ = "chat_messages" __tablename__ = "chat_messages"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False) conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False, index=True)
sender_id = Column(Integer, ForeignKey("users.id"), nullable=False) sender_id = Column(Integer, ForeignKey("users.id"), nullable=False)
body = Column(Text, nullable=False) body = Column(Text, nullable=False)
sent_at = Column(UTCDateTime, default=utcnow) sent_at = Column(UTCDateTime, default=utcnow)
+2 -1
View File
@@ -13,7 +13,7 @@ Devices are never deleted: revoked rows keep their token hash so the device is t
`device.revoked` (not "unknown"), and old sessions/audit rows keep a valid device_id. `device.revoked` (not "unknown"), and old sessions/audit rows keep a valid device_id.
Read and written through routers/devices.py and core/access/context.py. Read and written through routers/devices.py and core/access/context.py.
""" """
from sqlalchemy import JSON, Column, ForeignKey, Integer, String from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String
from core.timeutil import UTCDateTime, utcnow from core.timeutil import UTCDateTime, utcnow
from database import Base from database import Base
@@ -29,6 +29,7 @@ class Device(Base):
app_key = Column(String, nullable=False, index=True) # a kind="app" module with device_app app_key = Column(String, nullable=False, index=True) # a kind="app" module with device_app
config = Column(JSON, nullable=True) # app-specific (e.g. KDS prep zone) config = Column(JSON, nullable=True) # app-specific (e.g. KDS prep zone)
login_mode = Column(String, nullable=True) # NULL = site default auth.default_login_mode login_mode = Column(String, nullable=True) # NULL = site default auth.default_login_mode
require_username = Column(Boolean, nullable=True) # NULL = site default auth.terminal_require_username (6F.7)
token_hash = Column(String, nullable=True, unique=True) # sha256 hex; NULL until the device picks it up token_hash = Column(String, nullable=True, unique=True) # sha256 hex; NULL until the device picks it up
linked_device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True) linked_device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True)
user_agent = Column(String, nullable=True) # from the pairing request user_agent = Column(String, nullable=True) # from the pairing request
+42 -3
View File
@@ -28,11 +28,11 @@ class Expense(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
description = Column(String, nullable=False) description = Column(String, nullable=False)
category = Column(String, nullable=False) # supplier|utilities|rent|maintenance|staff|equipment|other category = Column(String, nullable=False) # supplier|utilities|rent|maintenance|staff|equipment|other
contact_id = Column(Integer, ForeignKey("contacts.id"), nullable=True) contact_id = Column(Integer, ForeignKey("contacts.id"), nullable=True, index=True)
total_amount = Column(Float, nullable=False) total_amount = Column(Float, nullable=False)
paid_amount = Column(Float, default=0.0, nullable=False) paid_amount = Column(Float, default=0.0, nullable=False)
due_date = Column(UTCDateTime, nullable=True) due_date = Column(UTCDateTime, nullable=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True) business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
created_at = Column(UTCDateTime, default=utcnow) created_at = Column(UTCDateTime, default=utcnow)
notes = Column(Text, nullable=True) notes = Column(Text, nullable=True)
@@ -40,13 +40,18 @@ class Expense(Base):
contact = relationship("Contact", back_populates="expenses") contact = relationship("Contact", back_populates="expenses")
created_by = relationship("User", foreign_keys=[created_by_id]) created_by = relationship("User", foreign_keys=[created_by_id])
payments = relationship("ExpensePayment", back_populates="expense", cascade="all, delete-orphan") payments = relationship("ExpensePayment", back_populates="expense", cascade="all, delete-orphan")
# what was bought (2026-11-20): when an expense has lines, its total is theirs
lines = relationship("ExpenseLine", back_populates="expense", cascade="all, delete-orphan",
order_by="ExpenseLine.position")
documents = relationship("ExpenseDocument", back_populates="expense", cascade="all, delete-orphan",
order_by="ExpenseDocument.id")
class ExpensePayment(Base): class ExpensePayment(Base):
__tablename__ = "expense_payments" __tablename__ = "expense_payments"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False) expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False, index=True)
amount = Column(Float, nullable=False) amount = Column(Float, nullable=False)
paid_at = Column(UTCDateTime, default=utcnow) paid_at = Column(UTCDateTime, default=utcnow)
paid_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) paid_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
@@ -54,3 +59,37 @@ class ExpensePayment(Base):
expense = relationship("Expense", back_populates="payments") expense = relationship("Expense", back_populates="payments")
paid_by = relationship("User", foreign_keys=[paid_by_id]) paid_by = relationship("User", foreign_keys=[paid_by_id])
class ExpenseLine(Base):
"""A line of an expense (2026-11-20): what was bought, how many, the price of one before VAT
and its VAT rate. Line total = quantity × unit price × (1 + VAT %)."""
__tablename__ = "expense_lines"
id = Column(Integer, primary_key=True, index=True)
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False, index=True)
position = Column(Integer, default=0, nullable=False)
description = Column(String, nullable=False)
quantity = Column(Float, default=1.0, nullable=False)
unit_price = Column(Float, nullable=False) # one, before VAT
vat_rate = Column(Float, default=0.0, nullable=False) # %, e.g. 24
expense = relationship("Expense", back_populates="lines")
class ExpenseDocument(Base):
"""A file kept with an expense (2026-11-20): the invoice as a PDF or a photo of the receipt.
Stored under MEDIA_DIR/expenses/<expense id>/ (services/expense_docs.py)."""
__tablename__ = "expense_documents"
id = Column(Integer, primary_key=True, index=True)
expense_id = Column(Integer, ForeignKey("expenses.id"), nullable=False, index=True)
filename = Column(String, nullable=False) # as uploaded
stored_name = Column(String, nullable=False) # on disk
content_type = Column(String, nullable=False)
size = Column(Integer, nullable=False)
uploaded_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
uploaded_at = Column(UTCDateTime, default=utcnow)
expense = relationship("Expense", back_populates="documents")
uploaded_by = relationship("User", foreign_keys=[uploaded_by_id])
+59
View File
@@ -0,0 +1,59 @@
"""Floor plans: where the tables stand (plan step 6.8, owner decisions D-31).
A zone (table group) can have several floor plans ("Ground floor", "Terrace"); a plan may also
have no zone. A plan is a canvas `width` × `height` in plan units (1 unit = 1 px at 100%):
- `outline`: the floor's shape as a polygon [[x, y], …] (irregular floors); empty = the whole
rectangle;
- `grid_on` / `grid_size`: with the grid on, the editor snaps positions and sizes to multiples
of `grid_size` (the grid is a help for drawing, the stored positions are plain numbers);
- `media_id`: a picture from the media library drawn under everything (e.g. a top-down photo),
with `background_opacity`.
`FloorItem`s are the things that aren't tables: walls, the bar, labels and areas, each a
rectangle (x, y = its centre) with a rotation. A table's place is on the table itself
(models/table.py: plan_id, floor_x/floor_y = its centre, width/height, rotation, shape).
"""
from sqlalchemy import JSON, Boolean, Column, Float, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from core.timeutil import UTCDateTime, utcnow
from database import Base
ITEM_KINDS = ("wall", "bar", "label", "area")
TABLE_SHAPES = ("round", "square", "long")
class FloorPlan(Base):
__tablename__ = "floor_plans"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
group_id = Column(Integer, ForeignKey("table_groups.id", ondelete="SET NULL"), nullable=True, index=True)
sort_order = Column(Integer, nullable=False, default=0)
width = Column(Integer, nullable=False, default=1200)
height = Column(Integer, nullable=False, default=800)
outline = Column(JSON, nullable=True)
grid_on = Column(Boolean, nullable=False, default=False)
grid_size = Column(Integer, nullable=False, default=40)
media_id = Column(Integer, ForeignKey("media.id", ondelete="SET NULL"), nullable=True)
background_opacity = Column(Float, nullable=False, default=0.6)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
media = relationship("Media")
items = relationship("FloorItem", back_populates="plan", cascade="all, delete-orphan", order_by="FloorItem.id")
class FloorItem(Base):
__tablename__ = "floor_items"
id = Column(Integer, primary_key=True, index=True)
plan_id = Column(Integer, ForeignKey("floor_plans.id", ondelete="CASCADE"), nullable=False, index=True)
kind = Column(String, nullable=False)
x = Column(Float, nullable=False)
y = Column(Float, nullable=False)
width = Column(Float, nullable=False)
height = Column(Float, nullable=False)
rotation = Column(Float, nullable=False, default=0.0)
text = Column(String, nullable=True)
color = Column(String, nullable=True) # an area's colour, "#rrggbb" (drawn see-through; 2026-11-20)
plan = relationship("FloorPlan", back_populates="items")
+17
View File
@@ -34,9 +34,26 @@ class Media(Base):
created_at = Column(UTCDateTime, default=utcnow, nullable=False) created_at = Column(UTCDateTime, default=utcnow, nullable=False)
# Shipped with the server (assets/builtin_media, step 5.4a): can't be deleted or renamed # Shipped with the server (assets/builtin_media, step 5.4a): can't be deleted or renamed
builtin = Column(Boolean, nullable=False, default=False, server_default='0') builtin = Column(Boolean, nullable=False, default=False, server_default='0')
# Videos (step 5.4e, services/video.py): the still frame and the version every screen plays are
# made in the background. waiting | working | done | failed; None = nothing to do (pictures,
# or no video tool on this server). `progress` 0-100 while working.
processing = Column(String, nullable=True)
progress = Column(Integer, nullable=True)
# its folder on the Media page (6R.16): only a grouping, the file stays where it is
folder_id = Column(Integer, ForeignKey("media_folders.id", ondelete="SET NULL"), nullable=True, index=True)
uploader = relationship("User", lazy="joined") uploader = relationship("User", lazy="joined")
@property @property
def uploaded_by_name(self): def uploaded_by_name(self):
return self.uploader.full_name or self.uploader.username if self.uploader is not None else None 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)
+1 -1
View File
@@ -42,7 +42,7 @@ class StaffMessageAck(Base):
__tablename__ = "staff_message_acks" __tablename__ = "staff_message_acks"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
message_id = Column(Integer, ForeignKey("staff_messages.id"), nullable=False) message_id = Column(Integer, ForeignKey("staff_messages.id"), nullable=False, index=True)
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False) waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False)
acked_at = Column(UTCDateTime, default=utcnow) acked_at = Column(UTCDateTime, default=utcnow)
+5 -2
View File
@@ -7,8 +7,10 @@ failures (later: Ergani, close-day reminders). NOT staff chat or manager message
- The text is an i18n key (`notification.<key>` in core/i18n/*.json) + params, rendered - The text is an i18n key (`notification.<key>` in core/i18n/*.json) + params, rendered
in the reader's language when listed. in the reader's language when listed.
- audience: "all_managers" (holders of core.dashboard.access) | "perm:<key>" | "user:<id>". - audience: "all_managers" (holders of core.dashboard.access) | "perm:<key>" | "user:<id>".
- dedupe_key: while a row with the same key is still live (expires_at NULL or future), - dedupe_key: while a row with the same key is still live (expires_at NULL or future, not
notify() bumps its `count` / `last_at` instead of adding a row. resolved), notify() bumps its `count` / `last_at` instead of adding a row.
- resolved_at (6F.8): a sticky alert ("the day isn't open") stays until its cause is gone;
core.notifications.resolve() then hides it.
Written through core/notifications.py only. Written through core/notifications.py only.
""" """
from sqlalchemy import JSON, Column, ForeignKey, Integer, String from sqlalchemy import JSON, Column, ForeignKey, Integer, String
@@ -31,6 +33,7 @@ class Notification(Base):
created_at = Column(UTCDateTime, nullable=False, default=utcnow, index=True) created_at = Column(UTCDateTime, nullable=False, default=utcnow, index=True)
last_at = Column(UTCDateTime, nullable=False, default=utcnow) last_at = Column(UTCDateTime, nullable=False, default=utcnow)
expires_at = Column(UTCDateTime, nullable=True) # hidden (and dedupe ends) after this expires_at = Column(UTCDateTime, nullable=True) # hidden (and dedupe ends) after this
resolved_at = Column(UTCDateTime, nullable=True) # 6F.8: a sticky alert whose cause is gone (hidden, dedupe ends)
class NotificationRead(Base): class NotificationRead(Base):
+81 -18
View File
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Text from sqlalchemy import Column, Integer, String, Boolean, Float, ForeignKey, Index, Text
from core.timeutil import UTCDateTime, utcnow from core.timeutil import UTCDateTime, utcnow
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
from database import Base from database import Base
@@ -8,16 +8,18 @@ from database import Base
class Order(Base): class Order(Base):
__tablename__ = "orders" __tablename__ = "orders"
# who opened what when (a shift's orders: migration 0038)
__table_args__ = (Index("ix_orders_opened_by_opened_at", "opened_by", "opened_at"),)
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True) # nullable for online orders table_id = Column(Integer, ForeignKey("tables.id"), nullable=True, index=True) # nullable for online orders
opened_by = Column(Integer, ForeignKey("users.id"), nullable=False) opened_by = Column(Integer, ForeignKey("users.id"), nullable=False)
opened_at = Column(UTCDateTime, default=utcnow) opened_at = Column(UTCDateTime, default=utcnow, index=True)
status = Column(String, default="open", nullable=False) # open|partially_paid|paid|closed|cancelled status = Column(String, default="open", nullable=False, index=True) # open|partially_paid|paid|closed|cancelled
closed_at = Column(UTCDateTime, nullable=True) closed_at = Column(UTCDateTime, nullable=True)
closed_by = Column(Integer, ForeignKey("users.id"), nullable=True) closed_by = Column(Integer, ForeignKey("users.id"), nullable=True)
notes = Column(Text, nullable=True) notes = Column(Text, nullable=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True) business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
# KDS # KDS
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done
kds_status_changed_at = Column(UTCDateTime, nullable=True) kds_status_changed_at = Column(UTCDateTime, nullable=True)
@@ -41,7 +43,7 @@ class Order(Base):
# when the customer wants it (S.5); NULL = as soon as possible # when the customer wants it (S.5); NULL = as soon as possible
requested_for = Column(UTCDateTime, nullable=True) requested_for = Column(UTCDateTime, nullable=True)
# Phase 2F — customer CRM # Phase 2F — customer CRM
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=True) customer_id = Column(Integer, ForeignKey("customers.id"), nullable=True, index=True)
# Number of customers at the table for this order # Number of customers at the table for this order
customer_count = Column(Integer, nullable=True) customer_count = Column(Integer, nullable=True)
@@ -53,7 +55,7 @@ class Order(Base):
opener = relationship("User", foreign_keys=[opened_by], back_populates="orders_opened") opener = relationship("User", foreign_keys=[opened_by], back_populates="orders_opened")
closer = relationship("User", foreign_keys=[closed_by], back_populates="orders_closed") closer = relationship("User", foreign_keys=[closed_by], back_populates="orders_closed")
customer = relationship("Customer", back_populates="orders", foreign_keys=[customer_id]) customer = relationship("Customer", back_populates="orders", foreign_keys=[customer_id])
items = relationship("OrderItem", back_populates="order", cascade="all, delete-orphan") items = relationship("OrderItem", back_populates="order", cascade="all, delete-orphan", lazy="selectin")
waiters = relationship("OrderWaiter", back_populates="order", cascade="all, delete-orphan") waiters = relationship("OrderWaiter", back_populates="order", cascade="all, delete-orphan")
print_logs = relationship("PrintLog", back_populates="order", cascade="all, delete-orphan") print_logs = relationship("PrintLog", back_populates="order", cascade="all, delete-orphan")
print_jobs = relationship("PrintJob", back_populates="order", cascade="all, delete-orphan") print_jobs = relationship("PrintJob", back_populates="order", cascade="all, delete-orphan")
@@ -65,8 +67,8 @@ class OrderWaiter(Base):
__tablename__ = "order_waiters" __tablename__ = "order_waiters"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False) waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
assigned_at = Column(UTCDateTime, default=utcnow) assigned_at = Column(UTCDateTime, default=utcnow)
order = relationship("Order", back_populates="waiters") order = relationship("Order", back_populates="waiters")
@@ -75,10 +77,12 @@ class OrderWaiter(Base):
class OrderItem(Base): class OrderItem(Base):
__tablename__ = "order_items" __tablename__ = "order_items"
# what someone added when (a shift's lines, cancellations: migration 0038)
__table_args__ = (Index("ix_order_items_added_by_added_at", "added_by", "added_at"),)
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
added_by = Column(Integer, ForeignKey("users.id"), nullable=False) added_by = Column(Integer, ForeignKey("users.id"), nullable=False)
quantity = Column(Float, nullable=False) quantity = Column(Float, nullable=False)
unit_price = Column(Float, nullable=False) # price snapshot at time of order unit_price = Column(Float, nullable=False) # price snapshot at time of order
@@ -92,7 +96,7 @@ class OrderItem(Base):
selected_options = Column(Text, nullable=True) # JSON array of option ids selected_options = Column(Text, nullable=True) # JSON array of option ids
removed_ingredients = Column(Text, nullable=True) # JSON array of ingredient ids removed_ingredients = Column(Text, nullable=True) # JSON array of ingredient ids
notes = Column(Text, nullable=True) notes = Column(Text, nullable=True)
status = Column(String, default="active", nullable=False) # active|paid|cancelled status = Column(String, default="active", nullable=False, index=True) # active|paid|cancelled
kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done|served|declined kds_status = Column(String, default="pending", nullable=False) # pending|preparing|done|served|declined
added_at = Column(UTCDateTime, default=utcnow) added_at = Column(UTCDateTime, default=utcnow)
printed = Column(Boolean, default=False, nullable=False) printed = Column(Boolean, default=False, nullable=False)
@@ -101,7 +105,7 @@ class OrderItem(Base):
paid_by = Column(Integer, ForeignKey("users.id"), nullable=True) paid_by = Column(Integer, ForeignKey("users.id"), nullable=True)
paid_at = Column(UTCDateTime, nullable=True) paid_at = Column(UTCDateTime, nullable=True)
payment_method = Column(String, nullable=True) # 'cash'|'card'|'other' — future use payment_method = Column(String, nullable=True) # 'cash'|'card'|'other' — future use
paid_in_shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True) paid_in_shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True, index=True)
# Phase 2A — cost snapshot (copied from product at time of order, never updated) # Phase 2A — cost snapshot (copied from product at time of order, never updated)
unit_cost = Column(Float, nullable=True) unit_cost = Column(Float, nullable=True)
@@ -129,6 +133,12 @@ class OrderItem(Base):
# Deal binding — which deal created this item, and which original item it's linked to # Deal binding — which deal created this item, and which original item it's linked to
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True) deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
linked_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) linked_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True)
# the line this one was cut from (6F.4): a split, a lowered quantity, a split payment; its moves
# before the cut are this line's too (services/moves.py)
split_from_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True)
# a split bill (6F.6): on the lines it settled (status "split") and on its part lines (the
# system product split_part, paid like any line); services/split_bills.py
split_bill_id = Column(Integer, ForeignKey("split_bills.id"), nullable=True, index=True)
order = relationship("Order", back_populates="items") order = relationship("Order", back_populates="items")
product = relationship("Product", back_populates="order_items") product = relationship("Product", back_populates="order_items")
@@ -150,7 +160,7 @@ class PrintLog(Base):
__tablename__ = "print_log" __tablename__ = "print_log"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False) printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False)
printed_at = Column(UTCDateTime, default=utcnow) printed_at = Column(UTCDateTime, default=utcnow)
item_ids = Column(Text, nullable=False) # JSON array of order_item ids item_ids = Column(Text, nullable=False) # JSON array of order_item ids
@@ -169,7 +179,7 @@ class PrintJob(Base):
__tablename__ = "print_jobs" __tablename__ = "print_jobs"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False) printer_id = Column(Integer, ForeignKey("printers.id"), nullable=False)
zone_id = Column(Integer, nullable=True) # prep zone id, NULL for legacy zone_id = Column(Integer, nullable=True) # prep zone id, NULL for legacy
item_ids = Column(Text, nullable=False) # JSON array of order_item ids item_ids = Column(Text, nullable=False) # JSON array of order_item ids
@@ -181,7 +191,9 @@ class PrintJob(Base):
last_attempted_at = Column(UTCDateTime, nullable=True) last_attempted_at = Column(UTCDateTime, nullable=True)
succeeded_at = Column(UTCDateTime, nullable=True) succeeded_at = Column(UTCDateTime, nullable=True)
cancelled_at = Column(UTCDateTime, nullable=True) cancelled_at = Column(UTCDateTime, nullable=True)
cancel_reason = Column(String, nullable=True) # "staff_cancelled" | "order_closed" cancel_reason = Column(String, nullable=True) # "staff_cancelled" | "order_closed" | "handled" (6.10)
resolved_by = Column(Integer, nullable=True) # 6.10: who sent it elsewhere / marked it handled
redirected_to = Column(Integer, nullable=True) # 6.10: the printer it was sent to instead (status success)
order = relationship("Order", back_populates="print_jobs") order = relationship("Order", back_populates="print_jobs")
printer = relationship("Printer", back_populates="print_jobs") printer = relationship("Printer", back_populates="print_jobs")
@@ -192,7 +204,7 @@ class OrderAuditLog(Base):
__tablename__ = "order_audit_log" __tablename__ = "order_audit_log"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
event_type = Column(String, nullable=False) event_type = Column(String, nullable=False)
# ORDER_OPENED | ITEMS_ADDED | PAYMENT | PAYMENT_OFFLINE | ORDER_CLOSED | ORDER_CANCELLED | ITEM_CANCELLED # ORDER_OPENED | ITEMS_ADDED | PAYMENT | PAYMENT_OFFLINE | ORDER_CLOSED | ORDER_CANCELLED | ITEM_CANCELLED
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=True) waiter_id = Column(Integer, ForeignKey("users.id"), nullable=True)
@@ -219,7 +231,7 @@ class OrderDiscount(Base):
__tablename__ = "order_discounts" __tablename__ = "order_discounts"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) # NULL = whole-order discount item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) # NULL = whole-order discount
discount_type = Column(String, nullable=False) # 'percent' | 'fixed' discount_type = Column(String, nullable=False) # 'percent' | 'fixed'
discount_value = Column(Float, nullable=False) # e.g. 10.0 = 10% or €10.00 discount_value = Column(Float, nullable=False) # e.g. 10.0 = 10% or €10.00
@@ -255,3 +267,54 @@ def _snapshot_item_names(session, flush_context, instances):
cat = session.get(Category, obj.category_id) cat = session.get(Category, obj.category_id)
obj.category_name = cat.name if cat else None obj.category_name = cat.name if cat else None
class OrderMove(Base):
"""Something moved between tables or orders (owner 2026-11-23, plan 6F.4, services/moves.py):
a whole order to another table (`table_transfer`), chosen lines to another order
(`items_moved`), or one order joined into another (`orders_merged`). Never deleted."""
__tablename__ = "order_moves"
id = Column(Integer, primary_key=True, index=True)
kind = Column(String, nullable=False, index=True) # table_transfer | items_moved | orders_merged
from_order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
to_order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
from_table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
to_table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
approved_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
note = Column(Text, nullable=True) # the importer / backfill: where it came from
items = relationship("OrderMoveItem", back_populates="move", cascade="all, delete-orphan")
class OrderMoveItem(Base):
"""A line that went with a move, and how much of it (its quantity at the time)."""
__tablename__ = "order_move_items"
move_id = Column(Integer, ForeignKey("order_moves.id", ondelete="CASCADE"), primary_key=True)
item_id = Column(Integer, ForeignKey("order_items.id"), primary_key=True, index=True)
quantity = Column(Float, nullable=True)
move = relationship("OrderMove", back_populates="items")
class SplitBill(Base):
"""A bill split by amount (owner 2026-11-23, plan 6F.6, services/split_bills.py): chosen lines
settled together (status "split") and cut into `parts` part lines that are paid on their own.
Undone (undone_at) only while no part was paid or put on a tab."""
__tablename__ = "split_bills"
id = Column(Integer, primary_key=True, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True)
total = Column(Float, nullable=False)
mode = Column(String, nullable=False) # equal | custom
parts = Column(Integer, nullable=False)
amounts = Column(Text, nullable=False) # JSON [4.5, 10.5]: each part, in order
created_by = Column(Integer, ForeignKey("users.id"), nullable=True)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
undone_at = Column(UTCDateTime, nullable=True)
undone_by = Column(Integer, ForeignKey("users.id"), nullable=True)
receipt_issued_at = Column(UTCDateTime, nullable=True) # the fiscal receipt of the settled lines (last part paid)
+1 -1
View File
@@ -12,4 +12,4 @@ class PhoneCall(Base):
at = Column(UTCDateTime, default=utcnow, nullable=False, index=True) at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
number = Column(String, nullable=False) # as the phone system sent it number = Column(String, nullable=False) # as the phone system sent it
ext = Column(String, nullable=True) # the extension that was dialled ext = Column(String, nullable=True) # the extension that was dialled
customer_id = Column(Integer, ForeignKey("customers.id", ondelete="SET NULL"), nullable=True) customer_id = Column(Integer, ForeignKey("customers.id", ondelete="SET NULL"), nullable=True, index=True)
+33 -5
View File
@@ -91,6 +91,7 @@ class PriceModifierCondition(Base):
min_order_value {"min": 0.00} (cart total before modifiers) min_order_value {"min": 0.00} (cart total before modifiers)
order_channel {"channels": [sales point, ...]} (core/sales_points.py; phase 3S) order_channel {"channels": [sales point, ...]} (core/sales_points.py; phase 3S)
price_group_active {"price_group_id": N} price_group_active {"price_group_id": N}
scene_active {"scene_id": N} (a scene is on: services/scenes.py, 2026-11-21)
user_tier {"tiers": ["bronze","silver","gold"]} (placeholder, needs user accounts) user_tier {"tiers": ["bronze","silver","gold"]} (placeholder, needs user accounts)
low_stock {"threshold": N} (placeholder, needs inventory) low_stock {"threshold": N} (placeholder, needs inventory)
""" """
@@ -98,7 +99,7 @@ class PriceModifierCondition(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"), modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"),
nullable=False) nullable=False, index=True)
condition_type = Column(String, nullable=False) condition_type = Column(String, nullable=False)
params = Column(Text, nullable=False, default="{}") # JSON params = Column(Text, nullable=False, default="{}") # JSON
@@ -120,7 +121,7 @@ class PriceModifierTarget(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"), modifier_id = Column(Integer, ForeignKey("price_modifiers.id", ondelete="CASCADE"),
nullable=False) nullable=False, index=True)
target_type = Column(String, nullable=False) # 'all'|'item'|'category'|'prep_zone'|'tag' target_type = Column(String, nullable=False) # 'all'|'item'|'category'|'prep_zone'|'tag'
target_id = Column(Integer, nullable=True) # legacy single value target_id = Column(Integer, nullable=True) # legacy single value
target_tag = Column(String, nullable=True) # legacy single value target_tag = Column(String, nullable=True) # legacy single value
@@ -180,7 +181,7 @@ class DealCondition(Base):
__tablename__ = "deal_conditions" __tablename__ = "deal_conditions"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False) deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False, index=True)
condition_type = Column(String, nullable=False) condition_type = Column(String, nullable=False)
params = Column(Text, nullable=False, default="{}") # JSON params = Column(Text, nullable=False, default="{}") # JSON
@@ -195,7 +196,7 @@ class DealTarget(Base):
__tablename__ = "deal_targets" __tablename__ = "deal_targets"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False) deal_id = Column(Integer, ForeignKey("deals.id", ondelete="CASCADE"), nullable=False, index=True)
target_type = Column(String, nullable=False) # 'item'|'category'|'tag'|'any' target_type = Column(String, nullable=False) # 'item'|'category'|'tag'|'any'
target_id = Column(Integer, nullable=True) # legacy single value target_id = Column(Integer, nullable=True) # legacy single value
target_tag = Column(String, nullable=True) # legacy single value target_tag = Column(String, nullable=True) # legacy single value
@@ -226,6 +227,7 @@ class PriceEventLog(Base):
# deal_offer_dismissed — waiter dismissed the deal offer # deal_offer_dismissed — waiter dismissed the deal offer
# waiter_discount — manual waiter discount applied # waiter_discount — manual waiter discount applied
# free_item_added — free item added to order as result of a deal # free_item_added — free item added to order as result of a deal
# manual_price — a price changed by hand (6F.3, services/price_changes.py)
modifier_id = Column(Integer, ForeignKey("price_modifiers.id"), nullable=True) modifier_id = Column(Integer, ForeignKey("price_modifiers.id"), nullable=True)
deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True) deal_id = Column(Integer, ForeignKey("deals.id"), nullable=True)
@@ -235,10 +237,15 @@ class PriceEventLog(Base):
price_after = Column(Float, nullable=True) price_after = Column(Float, nullable=True)
delta_amount = Column(Float, nullable=True) # price_after - price_before; negative = discount delta_amount = Column(Float, nullable=True) # price_after - price_before; negative = discount
# Waiter discount fields # Waiter discount fields (also manual_price: who changed it, and the reason)
applied_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True) applied_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
waiter_note = Column(Text, nullable=True) waiter_note = Column(Text, nullable=True)
# manual_price (6F.3, services/price_changes.py): a price changed by hand
approved_by_user_id = Column(Integer, ForeignKey("users.id"), nullable=True) # a manager's PIN (D-10)
stage = Column(String, nullable=True) # cart | sent | served
quantity = Column(Float, nullable=True) # the line's quantity at the time
# Snapshot of the conditions that evaluated to True when the event fired. # Snapshot of the conditions that evaluated to True when the event fired.
# JSON object: {"condition_type": evaluated_value, ...} # JSON object: {"condition_type": evaluated_value, ...}
# e.g. {"day_of_week": 5, "time_range": "21:45", "price_group_active": true} # e.g. {"day_of_week": 5, "time_range": "21:45", "price_group_active": true}
@@ -254,6 +261,7 @@ class PriceEventLog(Base):
modifier = relationship("PriceModifier", foreign_keys=[modifier_id]) modifier = relationship("PriceModifier", foreign_keys=[modifier_id])
deal = relationship("Deal", foreign_keys=[deal_id]) deal = relationship("Deal", foreign_keys=[deal_id])
applied_by = relationship("User", foreign_keys=[applied_by_user_id]) applied_by = relationship("User", foreign_keys=[applied_by_user_id])
approved_by = relationship("User", foreign_keys=[approved_by_user_id])
class WaiterDiscountSettings(Base): class WaiterDiscountSettings(Base):
@@ -280,3 +288,23 @@ class WaiterDiscountSettings(Base):
max_items_per_order = Column(Integer, nullable=True) max_items_per_order = Column(Integer, nullable=True)
user = relationship("User", foreign_keys=[user_id]) user = relationship("User", foreign_keys=[user_id])
class ChannelPrice(Base):
"""A price at one or more sales points (2026-11-20, services/channel_prices.py): for listed
products, the products of listed categories, or (neither) everything sold there. The most
precise rule wins: product > category > channel."""
__tablename__ = "channel_prices"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=True)
sales_points = Column(Text, nullable=False, default="[]") # JSON ["online_delivery", …]
product_ids = Column(Text, nullable=False, default="[]") # JSON [int]
category_ids = Column(Text, nullable=False, default="[]") # JSON [int]
action_type = Column(String, nullable=False) # 'set' | 'add_amount' | 'add_percent'
value = Column(Float, nullable=False)
round_to = Column(String, nullable=True) # as PriceModifier.round_to
is_active = Column(Boolean, nullable=False, default=True)
created_at = Column(UTCDateTime, default=utcnow)
updated_at = Column(UTCDateTime, nullable=True)
updated_by = Column(Integer, ForeignKey("users.id"), nullable=True)
+27 -6
View File
@@ -22,6 +22,8 @@ class Category(Base):
# Its picture in the media library (plan step 5.2); the library refuses to delete it while set # Its picture in the media library (plan step 5.2); the library refuses to delete it while set
media_id = Column(Integer, ForeignKey("media.id", ondelete="SET NULL"), nullable=True, index=True) media_id = Column(Integer, ForeignKey("media.id", ondelete="SET NULL"), nullable=True, index=True)
media = relationship("Media", lazy="joined") media = relationship("Media", lazy="joined")
# The menu in other languages (plan step 6.4, core/menu_languages.py): {"en": {"name": "…"}}
translations = Column(Text, nullable=True)
@property @property
def image(self): def image(self):
@@ -80,12 +82,19 @@ class Product(Base):
# Quick Add: allow adding 1 unit directly from product list without opening config modal # Quick Add: allow adding 1 unit directly from product list without opening config modal
quick_add_enabled = Column(Boolean, default=True, nullable=False) quick_add_enabled = Column(Boolean, default=True, nullable=False)
# "One more" (6F.5): a sent line of this product shows +1 (re-order the same, printed as new)
one_more_enabled = Column(Boolean, default=False, nullable=False, server_default="0")
# Service item: non-inventoried table-service items (cutlery, glasses, etc.) # Service item: non-inventoried table-service items (cutlery, glasses, etc.)
is_service_item = Column(Boolean, default=False, nullable=False) is_service_item = Column(Boolean, default=False, nullable=False)
# Tags: JSON array of strings e.g. ["vegan", "gluten-free"] # Tags: JSON array of strings e.g. ["vegan", "gluten-free"]
tags = Column(Text, nullable=True) tags = Column(Text, nullable=True)
# The EU allergens it has (plan step 6.3, core/allergens.py): JSON {key: "contains" | "may_contain"}
allergens = Column(Text, nullable=True)
# The menu in other languages (plan step 6.4, core/menu_languages.py):
# {"en": {"name": "…", "description": "…", "quick": {"<quick option>": "…"}}}
translations = Column(Text, nullable=True)
# Fiscal printer (ΦΗΜ) fields # Fiscal printer (ΦΗΜ) fields
fiscal_name = Column(String, nullable=True) # short name for receipt (falls back to name) fiscal_name = Column(String, nullable=True) # short name for receipt (falls back to name)
@@ -128,11 +137,13 @@ class ProductModifierGroup(Base):
__tablename__ = "product_modifier_groups" __tablename__ = "product_modifier_groups"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
# "option" | "ingredient" | "preference" # "option" | "ingredient" | "preference"
modifier_type = Column(String, nullable=False) modifier_type = Column(String, nullable=False)
name = Column(String, nullable=False) name = Column(String, nullable=False)
sort_order = Column(Integer, default=0, nullable=False) sort_order = Column(Integer, default=0, nullable=False)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
product = relationship("Product", back_populates="modifier_groups") product = relationship("Product", back_populates="modifier_groups")
@@ -141,7 +152,7 @@ class ProductOption(Base):
__tablename__ = "product_options" __tablename__ = "product_options"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
extra_cost = Column(Float, default=0.0) extra_cost = Column(Float, default=0.0)
allow_multiple = Column(Boolean, default=False, nullable=False) allow_multiple = Column(Boolean, default=False, nullable=False)
@@ -155,6 +166,8 @@ class ProductOption(Base):
is_compact = Column(Boolean, default=False, nullable=False) is_compact = Column(Boolean, default=False, nullable=False)
# Optional group/folder this option belongs to # Optional group/folder this option belongs to
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True) group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
product = relationship("Product", back_populates="options") product = relationship("Product", back_populates="options")
@@ -163,7 +176,7 @@ class ProductQuickOption(Base):
__tablename__ = "product_quick_options" __tablename__ = "product_quick_options"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
price = Column(Float, default=0.0, nullable=False) price = Column(Float, default=0.0, nullable=False)
allow_multiple = Column(Boolean, default=False, nullable=False) allow_multiple = Column(Boolean, default=False, nullable=False)
@@ -171,6 +184,8 @@ class ProductQuickOption(Base):
is_favorite = Column(Boolean, default=False, nullable=False) is_favorite = Column(Boolean, default=False, nullable=False)
favorite_sort_order = Column(Integer, default=0, nullable=False) favorite_sort_order = Column(Integer, default=0, nullable=False)
is_compact = Column(Boolean, default=False, nullable=False) is_compact = Column(Boolean, default=False, nullable=False)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
product = relationship("Product", back_populates="quick_options") product = relationship("Product", back_populates="quick_options")
@@ -179,7 +194,7 @@ class ProductIngredient(Base):
__tablename__ = "product_ingredients" __tablename__ = "product_ingredients"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
extra_cost = Column(Float, default=0.0) extra_cost = Column(Float, default=0.0)
is_favorite = Column(Boolean, default=False, nullable=False) is_favorite = Column(Boolean, default=False, nullable=False)
@@ -188,6 +203,8 @@ class ProductIngredient(Base):
is_compact = Column(Boolean, default=False, nullable=False) is_compact = Column(Boolean, default=False, nullable=False)
# Optional group/folder this ingredient belongs to # Optional group/folder this ingredient belongs to
group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True) group_id = Column(Integer, ForeignKey("product_modifier_groups.id"), nullable=True)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
product = relationship("Product", back_populates="ingredients") product = relationship("Product", back_populates="ingredients")
@@ -196,7 +213,7 @@ class ProductPreferenceSet(Base):
__tablename__ = "product_preference_sets" __tablename__ = "product_preference_sets"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
default_choice_id = Column(Integer, nullable=True) default_choice_id = Column(Integer, nullable=True)
# JSON: {name, default_choice_index, choices:[{name,extra_cost,is_default}]} # JSON: {name, default_choice_index, choices:[{name,extra_cost,is_default}]}
@@ -210,6 +227,8 @@ class ProductPreferenceSet(Base):
allow_multi_select = Column(Boolean, default=False, nullable=False) allow_multi_select = Column(Boolean, default=False, nullable=False)
# When True, each selected choice can have a quantity (x2, x3, …) # When True, each selected choice can have a quantity (x2, x3, …)
allow_choice_quantity = Column(Boolean, default=False, nullable=False) allow_choice_quantity = Column(Boolean, default=False, nullable=False)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
product = relationship("Product", back_populates="preference_sets") product = relationship("Product", back_populates="preference_sets")
choices = relationship("ProductPreferenceChoice", back_populates="set", cascade="all, delete-orphan") choices = relationship("ProductPreferenceChoice", back_populates="set", cascade="all, delete-orphan")
@@ -219,7 +238,7 @@ class ProductPreferenceChoice(Base):
__tablename__ = "product_preference_choices" __tablename__ = "product_preference_choices"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
set_id = Column(Integer, ForeignKey("product_preference_sets.id"), nullable=False) set_id = Column(Integer, ForeignKey("product_preference_sets.id"), nullable=False, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
extra_cost = Column(Float, default=0.0) extra_cost = Column(Float, default=0.0)
# JSON array of sub-choice objects: [{name, extra_cost, is_default, is_compact}] # JSON array of sub-choice objects: [{name, extra_cost, is_default, is_compact}]
@@ -229,6 +248,8 @@ class ProductPreferenceChoice(Base):
disables_subset = Column(Boolean, default=False, nullable=False) disables_subset = Column(Boolean, default=False, nullable=False)
# When True renders as half-width card on the PWA # When True renders as half-width card on the PWA
is_compact = Column(Boolean, default=False, nullable=False) is_compact = Column(Boolean, default=False, nullable=False)
# Its name per language (Alembic 0042, core/menu_languages.py): {"el": "…", "en": "…"}
translations = Column(Text, nullable=True)
set = relationship("ProductPreferenceSet", back_populates="choices") set = relationship("ProductPreferenceSet", back_populates="choices")
+2 -2
View File
@@ -20,7 +20,7 @@ class Reservation(Base):
reserved_for = Column(UTCDateTime, nullable=False) reserved_for = Column(UTCDateTime, nullable=False)
# Optional table assignment (assignable/editable later) # Optional table assignment (assignable/editable later)
table_id = Column(Integer, ForeignKey("tables.id"), nullable=True) table_id = Column(Integer, ForeignKey("tables.id"), nullable=True, index=True)
# Lifecycle: pending (confirmed, upcoming) | arrived | cancelled | no_show; # Lifecycle: pending (confirmed, upcoming) | arrived | cancelled | no_show;
# online requests (phase 3S, S.6) start as requested → pending (confirmed) | declined # online requests (phase 3S, S.6) start as requested → pending (confirmed) | declined
@@ -43,7 +43,7 @@ class Reservation(Base):
total = Column(Float, nullable=True) total = Column(Float, nullable=True)
online_price_diff = Column(Text, nullable=True) # services/online_check.py; NULL = matched online_price_diff = Column(Text, nullable=True) # services/online_check.py; NULL = matched
fire_at = Column(UTCDateTime, nullable=True) # when the kitchen gets the food (set on confirming) fire_at = Column(UTCDateTime, nullable=True) # when the kitchen gets the food (set on confirming)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=True) # created at fire time order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True) # created at fire time
response_note = Column(Text, nullable=True) # why it was declined / cancelled (the customer sees it) response_note = Column(Text, nullable=True) # why it was declined / cancelled (the customer sees it)
created_at = Column(UTCDateTime, default=utcnow) created_at = Column(UTCDateTime, default=utcnow)
+23
View File
@@ -0,0 +1,23 @@
"""Scenes (owner 2026-11-21): a named mode of the venue ("Party mode", "Match night") that is on or
off. What follows a scene: signage schedule lines that play only while it is on (and win by their
priority), and price rules / deals with the condition "a scene is on". Several can be on at once;
one may turn itself off at a time (`until`). services/scenes.py.
"""
from sqlalchemy import Boolean, Column, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class Scene(Base):
__tablename__ = "scenes"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
color = Column(String, nullable=True) # "#rrggbb", the venue's choice
description = Column(String, nullable=True)
is_active = Column(Boolean, nullable=False, default=False)
activated_at = Column(UTCDateTime, nullable=True)
until = Column(UTCDateTime, nullable=True) # on until then (None: until turned off)
sort_order = Column(Integer, nullable=False, default=0)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
+1 -1
View File
@@ -10,7 +10,7 @@ class ScheduledShift(Base):
__tablename__ = "scheduled_shifts" __tablename__ = "scheduled_shifts"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False) user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
scheduled_date = Column(Date, nullable=False) scheduled_date = Column(Date, nullable=False)
start_time = Column(String, nullable=False) # "HH:MM" stored as string (SQLite has no Time type) start_time = Column(String, nullable=False) # "HH:MM" stored as string (SQLite has no Time type)
end_time = Column(String, nullable=False) end_time = Column(String, nullable=False)
+3 -3
View File
@@ -10,8 +10,8 @@ class WaiterShift(Base):
__tablename__ = "waiter_shifts" __tablename__ = "waiter_shifts"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False) waiter_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=False) business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=False, index=True)
started_at = Column(UTCDateTime, default=utcnow, nullable=False) started_at = Column(UTCDateTime, default=utcnow, nullable=False)
ended_at = Column(UTCDateTime, nullable=True) ended_at = Column(UTCDateTime, nullable=True)
starting_cash = Column(Float, nullable=True) starting_cash = Column(Float, nullable=True)
@@ -32,7 +32,7 @@ class ShiftBreak(Base):
__tablename__ = "shift_breaks" __tablename__ = "shift_breaks"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=False) shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=False, index=True)
started_at = Column(UTCDateTime, default=utcnow, nullable=False) started_at = Column(UTCDateTime, default=utcnow, nullable=False)
ended_at = Column(UTCDateTime, nullable=True) ended_at = Column(UTCDateTime, nullable=True)
+50 -9
View File
@@ -6,8 +6,9 @@ a text, with its time on screen, its transition and when it may show (days, hour
What the slide shows is `content`, typed per kind in routers/signage.py (pictures and videos What the slide shows is `content`, typed per kind in routers/signage.py (pictures and videos
as media library ids, which the library protects while used). as media library ids, which the library protects while used).
A paired signage screen plays the playlist in its device config (`playlist`), in its own A paired signage screen plays its default playlist (device config `playlist`) in its own
orientation and rotation (modules/signage/manifest.py). orientation and rotation (modules/signage/manifest.py), unless a schedule line for it matches
(SignageScheduleItem, 2026-11-21).
""" """
from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
@@ -22,6 +23,7 @@ class SignagePlaylist(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
orientation = Column(String, nullable=False, default="landscape") # landscape | portrait 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 transition = Column(String, nullable=False, default="fade") # the slides' default
created_at = Column(UTCDateTime, default=utcnow, nullable=False) created_at = Column(UTCDateTime, default=utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False) updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
@@ -53,15 +55,54 @@ class SignageSlide(Base):
playlist = relationship("SignagePlaylist", back_populates="slides") playlist = relationship("SignagePlaylist", back_populates="slides")
class SignageSchedule(Base): class SignageScheduleItem(Base):
"""Which playlist plays when (5.4d): entries matched in venue time (services/signage_schedule.py), """A schedule line (owner 2026-11-21, was named schedules of 5.4d): a playlist on some screens
the fallback when none matches. A screen with a schedule plays it instead of a single playlist.""" (none picked = every screen), on some days / hours / dates / smart days (core/calendar_days.py),
__tablename__ = "signage_schedules" optionally only while a scene is on, with a priority. At a moment, a screen plays the line
that matches with the highest priority (then the most specific, then the later one); none →
its own default playlist (Screens). services/signage_schedule.py."""
__tablename__ = "signage_schedule_items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=True)
playlist_id = Column(Integer, ForeignKey("signage_playlists.id", ondelete="CASCADE"), nullable=False, index=True)
screen_ids = Column(JSON, nullable=False, default=list) # [] = every screen
priority = Column(Integer, nullable=False, default=0)
enabled = Column(Boolean, nullable=False, default=True)
days = Column(JSON, nullable=False, default=list) # [0..6], Monday = 0; [] = every day
month_days = Column(JSON, nullable=False, default=list) # smart days: first, last, first_week, last_week, holiday, not_holiday
time_from = Column(String, nullable=True)
time_to = Column(String, nullable=True)
date_from = Column(String, nullable=True)
date_to = Column(String, nullable=True)
scene_id = Column(Integer, ForeignKey("scenes.id", ondelete="SET NULL"), nullable=True, index=True)
position = Column(Integer, nullable=False, default=0)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
class SignageSavedSlide(Base):
"""A slide kept in the Slides library (owner 2026-11-21): built once, with a name and a short
description, then added to playlists (a copy goes in) or shown alone on a screen that has it
as its default (device config `slide`). The same fields as a playlist's slide, plus the shape
it is built for (its preview and the picture-fit warnings)."""
__tablename__ = "signage_saved_slides"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
fallback_playlist_id = Column(Integer, ForeignKey("signage_playlists.id", ondelete="SET NULL"), nullable=True) description = Column(String, nullable=True)
# [{playlist_id, days, time_from, time_to, date_from, date_to, priority}] orientation = Column(String, nullable=False, default="landscape") # landscape | portrait
entries = Column(JSON, nullable=False, default=list) aspect = Column(String, nullable=True) # a custom shape "21:9" (6R.13); None: 16:9 / 9:16
kind = Column(String, nullable=False) # menu | image | video | text | blank
duration_s = Column(Integer, nullable=False, default=10)
transition = Column(String, nullable=True)
video_to_end = Column(Boolean, nullable=False, default=False)
enabled = Column(Boolean, nullable=False, default=True)
days = Column(JSON, nullable=True)
time_from = Column(String, nullable=True)
time_to = Column(String, nullable=True)
date_from = Column(String, nullable=True)
date_to = Column(String, nullable=True)
content = Column(JSON, nullable=False, default=dict)
created_at = Column(UTCDateTime, default=utcnow, nullable=False) created_at = Column(UTCDateTime, default=utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False) updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
+7 -1
View File
@@ -22,11 +22,17 @@ class Table(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
number = Column(Integer, nullable=False) number = Column(Integer, nullable=False)
label = Column(String, nullable=True) label = Column(String, nullable=True)
group_id = Column(Integer, ForeignKey("table_groups.id"), nullable=True) group_id = Column(Integer, ForeignKey("table_groups.id"), nullable=True, index=True)
is_active = Column(Boolean, default=True, nullable=False) is_active = Column(Boolean, default=True, nullable=False)
seat_count = Column(Integer, nullable=True) seat_count = Column(Integer, nullable=True)
# its place on a floor plan (6.8, D-31; models/floor_plan.py): floor_x / floor_y = its centre
plan_id = Column(Integer, ForeignKey("floor_plans.id", ondelete="SET NULL"), nullable=True, index=True)
floor_x = Column(Float, nullable=True) floor_x = Column(Float, nullable=True)
floor_y = Column(Float, nullable=True) floor_y = Column(Float, nullable=True)
width = Column(Float, nullable=True)
height = Column(Float, nullable=True)
rotation = Column(Float, nullable=True)
shape = Column(String, nullable=True) # round | square | long
# the table's QR code (phase 3S, S.7): a random token in the QR menu link; the cloud gets # the table's QR code (phase 3S, S.7): a random token in the QR menu link; the cloud gets
# only its sha256 (services/table_qr.py). A new token makes the printed code useless. # only its sha256 (services/table_qr.py). A new token makes the printed code useless.
qr_token = Column(String, nullable=True, unique=True) qr_token = Column(String, nullable=True, unique=True)
+30
View File
@@ -0,0 +1,30 @@
"""Orders from a menu tablet at a table (plan step 6.6, D-30).
Every order a tablet sends is a row: what was sent (`lines`, as the counter's lines by id,
services/pos_cart.py), its note, the total it was quoted at, and what happened:
waiting a waiter must confirm it first (the venue's or the tablet's setting)
sent on the table's order and in the kitchen (`order_id`)
declined a waiter declined it (`reason` for the guests)
The rows also give the time limit between two orders from one tablet.
"""
from sqlalchemy import JSON, Column, Float, ForeignKey, Integer, String, Text
from core.timeutil import UTCDateTime, utcnow
from database import Base
class TabletOrder(Base):
__tablename__ = "tablet_orders"
id = Column(Integer, primary_key=True, index=True)
device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True, index=True)
table_id = Column(Integer, ForeignKey("tables.id", ondelete="SET NULL"), nullable=True, index=True)
lines = Column(JSON, nullable=False, default=list)
note = Column(Text, nullable=True)
total = Column(Float, nullable=False, default=0.0)
status = Column(String, nullable=False, default="waiting", index=True)
order_id = Column(Integer, ForeignKey("orders.id", ondelete="SET NULL"), nullable=True, index=True)
reason = Column(String, nullable=True)
decided_by_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
decided_at = Column(UTCDateTime, nullable=True)
created_at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
+11 -5
View File
@@ -10,7 +10,7 @@ class Tab(Base):
__tablename__ = "tabs" __tablename__ = "tabs"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
customer_id = Column(Integer, ForeignKey("customers.id"), nullable=False) customer_id = Column(Integer, ForeignKey("customers.id"), nullable=False, index=True)
status = Column(String, default="open", nullable=False) # open | closed | forgiven status = Column(String, default="open", nullable=False) # open | closed | forgiven
opened_at = Column(UTCDateTime, default=utcnow) opened_at = Column(UTCDateTime, default=utcnow)
closed_at = Column(UTCDateTime, nullable=True) closed_at = Column(UTCDateTime, nullable=True)
@@ -28,13 +28,16 @@ class TabEntry(Base):
__tablename__ = "tab_entries" __tablename__ = "tab_entries"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False) tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False, index=True)
order_id = Column(Integer, ForeignKey("orders.id"), nullable=True) order_id = Column(Integer, ForeignKey("orders.id"), nullable=True, index=True)
order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True)
amount = Column(Float, nullable=False) # snapshot at time of tab entry amount = Column(Float, nullable=False) # snapshot at time of tab entry
description = Column(Text, nullable=True) # auto-generated summary description = Column(Text, nullable=True) # auto-generated summary
created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
created_at = Column(UTCDateTime, default=utcnow) created_at = Column(UTCDateTime, default=utcnow)
# 6.13c: the business day and the shift (of whoever did it, if on one) it happened in
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True, index=True)
tab = relationship("Tab", back_populates="entries") tab = relationship("Tab", back_populates="entries")
created_by = relationship("User", foreign_keys=[created_by_id]) created_by = relationship("User", foreign_keys=[created_by_id])
@@ -45,12 +48,15 @@ class TabPayment(Base):
__tablename__ = "tab_payments" __tablename__ = "tab_payments"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False) tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False, index=True)
amount = Column(Float, nullable=False) amount = Column(Float, nullable=False)
payment_method = Column(String, nullable=True) # cash | card | other payment_method = Column(String, nullable=True) # cash | card | other
received_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) received_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
notes = Column(Text, nullable=True) notes = Column(Text, nullable=True)
created_at = Column(UTCDateTime, default=utcnow) created_at = Column(UTCDateTime, default=utcnow)
# 6.13c: the business day and the shift (of whoever did it, if on one) it happened in
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
shift_id = Column(Integer, ForeignKey("waiter_shifts.id"), nullable=True, index=True)
tab = relationship("Tab", back_populates="payments") tab = relationship("Tab", back_populates="payments")
received_by = relationship("User", foreign_keys=[received_by_id]) received_by = relationship("User", foreign_keys=[received_by_id])
+2 -2
View File
@@ -10,14 +10,14 @@ class WasteLog(Base):
__tablename__ = "waste_log" __tablename__ = "waste_log"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, ForeignKey("products.id"), nullable=False) product_id = Column(Integer, ForeignKey("products.id"), nullable=False, index=True)
quantity = Column(Float, nullable=False) # supports decimals quantity = Column(Float, nullable=False) # supports decimals
unit_cost_snapshot = Column(Float, nullable=True) # product's effective cost at log time unit_cost_snapshot = Column(Float, nullable=True) # product's effective cost at log time
total_cost = Column(Float, nullable=True) # unit_cost_snapshot * quantity total_cost = Column(Float, nullable=True) # unit_cost_snapshot * quantity
reason = Column(String, nullable=False) # kitchen_error|dropped|expired|other reason = Column(String, nullable=False) # kitchen_error|dropped|expired|other
reason_notes = Column(Text, nullable=True) reason_notes = Column(Text, nullable=True)
logged_by_id = Column(Integer, ForeignKey("users.id"), nullable=False) logged_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True) business_day_id = Column(Integer, ForeignKey("business_days.id"), nullable=True, index=True)
logged_at = Column(UTCDateTime, default=utcnow) logged_at = Column(UTCDateTime, default=utcnow)
product = relationship("Product", foreign_keys=[product_id]) product = relationship("Product", foreign_keys=[product_id])
@@ -12,6 +12,7 @@ MODULE = Module(
), ),
routers=( routers=(
Mount('routers.tables', '/api/tables'), Mount('routers.tables', '/api/tables'),
Mount('routers.floor_plans', '/api/floor-plans'),
Mount('routers.products', '/api/products'), Mount('routers.products', '/api/products'),
Mount('routers.prep_zones', '/api/prep-zones'), Mount('routers.prep_zones', '/api/prep-zones'),
Mount('routers.data_transfer', '/api/data-transfer'), Mount('routers.data_transfer', '/api/data-transfer'),
+8 -2
View File
@@ -12,6 +12,7 @@ MODULE = Module(
Perm('core.settings.manage', 'Change venue settings', roles=('owner',)), Perm('core.settings.manage', 'Change venue settings', roles=('owner',)),
Perm('core.modules.manage', 'Turn apps, features and integrations on or off', roles=('owner',)), Perm('core.modules.manage', 'Turn apps, features and integrations on or off', roles=('owner',)),
Perm('core.devices.manage', 'Pair, rename, reassign and remove devices', roles=('owner', 'store_manager')), Perm('core.devices.manage', 'Pair, rename, reassign and remove devices', roles=('owner', 'store_manager')),
Perm('core.scenes.manage', 'Make scenes and turn them on or off', roles=('owner', 'store_manager')),
Perm('core.system.admin', 'Support-only maintenance (superadmin)', roles=()), Perm('core.system.admin', 'Support-only maintenance (superadmin)', roles=()),
), ),
settings=( settings=(
@@ -26,13 +27,16 @@ MODULE = Module(
SettingDef('auth.default_login_mode', 'pin', "How staff log in on paired devices (KDS, counter POS) unless the device sets its own: 'pin' | 'password' | 'tap' | 'none'. Apps that can't use it fall back to their first mode.", type='enum', choices=('pin', 'password', 'tap', 'none')), SettingDef('auth.default_login_mode', 'pin', "How staff log in on paired devices (KDS, counter POS) unless the device sets its own: 'pin' | 'password' | 'tap' | 'none'. Apps that can't use it fall back to their first mode.", type='enum', choices=('pin', 'password', 'tap', 'none')),
SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'), SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'),
SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')), SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
SettingDef('auth.single_session_waiter', 'off', "One waiter session per user (no double login): 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')), SettingDef('auth.single_session_waiter', 'ask', "One waiter session per user, phones only (no double login): 'off' | 'refuse_new' | 'end_old' | 'ask' (the default: the phone asks, yes signs the other one out)", type='enum', choices=('off', 'refuse_new', 'end_old', 'ask')),
SettingDef('auth.terminal_require_username', 'false', 'Paired screens (counter, KDS): type a username instead of picking a name; no names are listed, and "tap" is not used. A device can choose otherwise on the Devices page.', type='bool'),
SettingDef('auth.idle_days', '14', 'Sign people out after this many days without using the app (manager, waiter, paired-device sessions; support has its own 4 h). 0 = never.', type='int'), SettingDef('auth.idle_days', '14', 'Sign people out after this many days without using the app (manager, waiter, paired-device sessions; support has its own 4 h). 0 = never.', type='int'),
SettingDef('system.log_retention_days', '30', 'Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.', type='int'), SettingDef('system.log_retention_days', '30', 'Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.', type='int'),
SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'), SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'),
SettingDef('venue.timezone', 'Europe/Athens', 'IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.', type='str'), SettingDef('venue.timezone', 'Europe/Athens', 'IANA time zone of the venue (e.g. Europe/Athens). All times are shown in it; DST is automatic. Applies immediately.', type='str'),
SettingDef('venue.name', '', 'Venue name shown on screens and tickets.', type='str'), SettingDef('venue.name', '', 'Venue name shown on screens and tickets.', type='str'),
SettingDef('venue.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.type', '', 'Kind of venue (restaurant, cafe, bar...), chosen in the setup wizard.', type='str'),
SettingDef('venue.currency', 'EUR', 'ISO 4217 currency of all prices.', type='str'), SettingDef('venue.currency', 'EUR', 'ISO 4217 currency of all prices.', type='str'),
), ),
@@ -48,6 +52,8 @@ MODULE = Module(
Mount('routers.media', '/api/media'), Mount('routers.media', '/api/media'),
Mount('routers.access', '/api/access'), Mount('routers.access', '/api/access'),
Mount('routers.notifications', '/api/platform/notifications'), Mount('routers.notifications', '/api/platform/notifications'),
Mount('routers.scenes', '/api/scenes'),
Mount('routers.identity', '/api/identity'),
Mount('core.modules.api', '/api/platform'), Mount('core.modules.api', '/api/platform'),
), ),
) )
+2 -2
View File
@@ -15,8 +15,8 @@ MODULE = Module(
SettingDef('fiscal.eftpos_id', '1', "EFTPOS terminal ID sent in CD commands (integer string, e.g. '1')", type='int'), SettingDef('fiscal.eftpos_id', '1', "EFTPOS terminal ID sent in CD commands (integer string, e.g. '1')", type='int'),
SettingDef('fiscal.enabled', 'false', "Master switch for fiscal printing: 'true' | 'false'", type='bool'), SettingDef('fiscal.enabled', 'false', "Master switch for fiscal printing: 'true' | 'false'", type='bool'),
SettingDef('fiscal.end_message', '[]', 'JSON array of up to 5 strings printed at end of receipt via FM commands', type='json'), SettingDef('fiscal.end_message', '[]', 'JSON array of up to 5 strings printed at end of receipt via FM commands', type='json'),
SettingDef('fiscal.in_folder', '', 'Path the backend reads fiscal reply files FROM (output of the fiscal driver)', type='json'), SettingDef('fiscal.in_folder', '', 'Path the backend reads fiscal reply files FROM (output of the fiscal driver)', type='str'),
SettingDef('fiscal.out_folder', '', 'Path the backend writes fiscal command files TO (input for the fiscal driver)', type='json'), SettingDef('fiscal.out_folder', '', 'Path the backend writes fiscal command files TO (input for the fiscal driver)', type='str'),
SettingDef('fiscal.type', 'txt_file', "Fiscal driver type: 'txt_file' (dTEC100extra) — more types coming", type='str'), SettingDef('fiscal.type', 'txt_file', "Fiscal driver type: 'txt_file' (dTEC100extra) — more types coming", type='str'),
SettingDef('fiscal.vat_groups', '[]', 'JSON array of VAT group definitions: [{machine_id: int, friendly_name: str}]', type='json'), SettingDef('fiscal.vat_groups', '[]', 'JSON array of VAT group definitions: [{machine_id: int, friendly_name: str}]', type='json'),
), ),
+36 -3
View File
@@ -1,11 +1,13 @@
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4.""" """Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
from core.modules.model import DeviceApp, Limit, Module, Perm from core.modules.model import ConfigField, DeviceApp, Limit, Module, Mount, Perm, SettingDef
POINTS = ('in_store', 'in_store_takeaway', 'qr_table', 'online_takeaway', 'online_delivery', 'online_preorder', 'none')
MODULE = Module( MODULE = Module(
key='menu_tablet', key='menu_tablet',
kind='app', kind='app',
name='Menu tablet', name='Menu tablet',
description='Self-service catalogue on a tablet (phase 5).', description="The venue's menu on a tablet: a quick price check for staff and a menu for guests (plan step 5.7a).",
depends=('catalog',), depends=('catalog',),
permissions=( permissions=(
Perm('menu_tablet.manage', 'Set up menu tablets', roles=('owner', 'store_manager')), Perm('menu_tablet.manage', 'Set up menu tablets', roles=('owner', 'store_manager')),
@@ -13,5 +15,36 @@ MODULE = Module(
limits=( limits=(
Limit('devices', 'Number of menu tablets', free=0, licensed_default=1), Limit('devices', 'Number of menu tablets', free=0, licensed_default=1),
), ),
device_app=DeviceApp(login_modes=('none',), scope=()), routers=(
Mount('routers.menu_tablet', '/api/menu-tablet'),
),
# Ordering from a tablet at a table (6.6, D-30): the venue's rules, each overridable per tablet
settings=(
SettingDef('menu_tablet.ordering', '{}', 'Ordering from menu tablets at tables (plan step 6.6): confirm (kitchen | waiter), no_order (open | refuse), max_items, max_of_one, min_seconds. Edited in Settings > Menu tablets.', type='json'),
),
# How the menu looks on this tablet (owner 2026-11-17: views, photos, descriptions, grouping…)
device_app=DeviceApp(login_modes=('none',), scope=(), config=(
ConfigField('view', 'enum', default='expanded', choices=('compact', 'expanded', 'full'), group='look'),
ConfigField('photos', 'bool', default=True, group='look'),
ConfigField('descriptions', 'bool', default=True, group='look'),
ConfigField('group', 'bool', default=True, group='look'),
ConfigField('theme', 'enum', default='light', choices=('light', 'dark'), group='look'),
ConfigField('sales_point', 'enum', default='in_store', choices=POINTS, group='menu'),
ConfigField('sold_out', 'enum', default='strike', choices=('strike', 'hide'), group='menu'),
ConfigField('category', 'ref', default=None, choices_from='categories', group='menu'),
ConfigField('search', 'bool', default=True, group='use'),
ConfigField('languages', 'enum', default='both', choices=('both', 'el', 'en'), group='use'),
ConfigField('idle_seconds', 'int', default=120, choices=(0, 30, 60, 120, 300, 600), group='use'),
# A tablet on a table (5.7b): only then guests can call a waiter
ConfigField('table', 'ref', default=None, choices_from='tables', group='table'),
ConfigField('call_waiter', 'bool', default=True, group='table'),
# Guests order from it (6.6, D-30): off until the venue turns it on; the rest -1 / venue = the venue's setting
ConfigField('ordering', 'bool', default=False, group='order'),
ConfigField('bill', 'bool', default=True, group='order'),
ConfigField('order_confirm', 'enum', default='venue', choices=('venue', 'kitchen', 'waiter'), group='order'),
ConfigField('order_no_order', 'enum', default='venue', choices=('venue', 'open', 'refuse'), group='order'),
ConfigField('order_max_items', 'int', default=-1, choices=(-1, 5, 10, 15, 20, 30, 50), group='order'),
ConfigField('order_max_of_one', 'int', default=-1, choices=(-1, 1, 2, 3, 5, 10, 20), group='order'),
ConfigField('order_min_seconds', 'int', default=-1, choices=(-1, 0, 30, 60, 120, 300, 600), group='order'),
)),
) )
+19 -1
View File
@@ -11,20 +11,37 @@ MODULE = Module(
Perm('ordering.orders.open', 'Open orders and add items', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')), Perm('ordering.orders.open', 'Open orders and add items', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
Perm('ordering.orders.close', 'Take payments and close orders', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')), Perm('ordering.orders.close', 'Take payments and close orders', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter')),
Perm('ordering.orders.cancel', 'Cancel items already sent', roles=('owner', 'store_manager'), overridable=True), Perm('ordering.orders.cancel', 'Cancel items already sent', roles=('owner', 'store_manager'), overridable=True),
Perm('ordering.prices.modify', "Change an item's price", roles=('owner',), overridable=True), Perm('ordering.prices.modify', "Change an item's price before it is sent", roles=('owner',), overridable=True),
Perm('ordering.prices.modify_sent', "Change the price of an item already sent or served", roles=('owner',), overridable=True),
Perm('ordering.items.change_quantity', "Change a sent line's quantity (no new ticket)", roles=('owner', 'store_manager'), overridable=True),
Perm('ordering.prices.view_changes', 'See the prices changed by hand (who, when, why)', roles=('owner', 'store_manager')),
Perm('ordering.refunds', 'Refund payments from other shifts', roles=('owner', 'store_manager'), overridable=True), Perm('ordering.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.revert', 'Turn paid items back to unpaid', roles=('owner', 'store_manager'), overridable=True),
Perm('ordering.payments.split_amount', 'Split a bill by amount (equal parts or a ratio)', roles=('owner', 'store_manager', 'barista', 'barman', 'waiter'), overridable=True),
Perm('ordering.business_day.manage', 'Open and close the business day', roles=('owner', 'store_manager', 'staff_manager')), Perm('ordering.business_day.manage', 'Open and close the business day', roles=('owner', 'store_manager', 'staff_manager')),
), ),
settings=( settings=(
SettingDef('business_day.force_close_allowed', 'true', 'Allow force-closing business day with open tables', type='bool'), SettingDef('business_day.force_close_allowed', 'true', 'Allow force-closing business day with open tables', type='bool'),
SettingDef('business_day.auto_open', 'off', "The day opens by itself (6F.8): 'off' | 'schedule' (at the opening hours) | 'time' (every day at business_day.auto_open_time) | 'alert' (at the opening hours, only tell the managers)", type='enum', choices=('off', 'schedule', 'time', 'alert')),
SettingDef('business_day.auto_close', 'off', "The day closes by itself (6F.8): 'off' | 'schedule' | 'time' | 'alert'. Closes only when every order of the day is closed; otherwise the managers are alerted and it tries again every 15 minutes.", type='enum', choices=('off', 'schedule', 'time', 'alert')),
SettingDef('business_day.auto_open_time', '09:00', "HH:MM venue time, for business_day.auto_open = 'time' (6F.8).", type='str'),
SettingDef('business_day.auto_close_time', '23:30', "HH:MM venue time, for business_day.auto_close = 'time' (6F.8).", type='str'),
SettingDef('business_day.auto_ignore_break', 'true', "A day's opening spans count as one (first opening to last closing); 'false' = the break between spans closes the day and the next span opens a new one (6F.8).", type='bool'),
SettingDef('business_day.auto_open_offset_min', '0', 'Open this many minutes before the opening hours start (6F.8, 0-720).', type='int'),
SettingDef('business_day.auto_close_offset_min', '0', 'Close this many minutes after the opening hours end (6F.8, 0-720).', type='int'),
SettingDef('business_day.rollover_hour', '6', 'Hour (0-23, venue time) before which a newly opened business day counts as the previous date. Default 6.', type='int'), SettingDef('business_day.rollover_hour', '6', 'Hour (0-23, venue time) before which a newly opened business day counts as the previous date. Default 6.', type='int'),
SettingDef('orders.auto_close_on_full_payment', 'false', "Automatically close the table order when all items have been paid: 'true' | 'false'", type='bool'), SettingDef('orders.auto_close_on_full_payment', 'false', "Automatically close the table order when all items have been paid: 'true' | 'false'", type='bool'),
SettingDef('orders.close_with_unpaid', 'false', "Allow closing an order that still has unpaid items (they are written off as unpaid): 'true' | 'false'. When 'false', closing asks for the payment first (plan step 4.8).", type='bool'), SettingDef('orders.close_with_unpaid', 'false', "Allow closing an order that still has unpaid items (they are written off as unpaid): 'true' | 'false'. When 'false', closing asks for the payment first (plan step 4.8).", type='bool'),
SettingDef('orders.bypass_kds_serve', 'false', "Skip KDS pending/serve flow — new orders and items are immediately marked as served: 'true' | 'false'", type='bool'), SettingDef('orders.bypass_kds_serve', 'false', "Skip KDS pending/serve flow — new orders and items are immediately marked as served: 'true' | 'false'", type='bool'),
SettingDef('orders.quantity_change', 'off', "Changing a sent line's quantity without sending it again (6F.5): 'off' | 'add_only' | 'add_and_remove' (lowering cancels the difference; also needs ordering.orders.cancel). Who may: ordering.items.change_quantity.", type='enum', choices=('off', 'add_only', 'add_and_remove')),
SettingDef('orders.price_change', 'anytime', "Changing a line's price by hand (6F.3): 'off' | 'before_sending' (only in the cart) | 'anytime' (also a sent or served line). Who may: the keys ordering.prices.modify / modify_sent.", type='enum', choices=('off', 'before_sending', 'anytime')),
SettingDef('orders.price_change_reason', 'false', "A price changed by hand needs a reason: 'true' | 'false' (6F.3).", type='bool'),
SettingDef('orders.price_change_reasons', '[]', 'JSON array of quick reasons offered when a price is changed by hand (6F.3); [] = the built-in ones.', type='json'),
SettingDef('orders.courses', '[]', 'JSON array of course objects [{id, name, color}] defining available courses', type='json'), SettingDef('orders.courses', '[]', 'JSON array of course objects [{id, name, color}] defining available courses', type='json'),
SettingDef('orders.courses_enabled', 'false', "Enable per-item course assignment when ordering: 'true' | 'false'", type='bool'), SettingDef('orders.courses_enabled', 'false', "Enable per-item course assignment when ordering: 'true' | 'false'", type='bool'),
SettingDef('orders.quick_notes', '["Χωρίς αλάτι","Βγάλτε γρήγορα","Αλλεργία!","Κόψτε σε μικρά κομμάτια","Έξτρα χαρτοπετσέτες"]', 'JSON array of quick-note strings shown in the waiter note tab', type='json'), SettingDef('orders.quick_notes', '["Χωρίς αλάτι","Βγάλτε γρήγορα","Αλλεργία!","Κόψτε σε μικρά κομμάτια","Έξτρα χαρτοπετσέτες"]', 'JSON array of quick-note strings shown in the waiter note tab', type='json'),
SettingDef('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('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.alert_after_failures', '2', 'Tell managers when a kitchen/bar ticket has failed to print this many times and is still retrying (0 = never; they are always told when a ticket is finally given up).', type='int'),
SettingDef('print.beep_on_ticket', 'true', "Play beep when a kitchen ticket prints: 'true' | 'false'", type='bool'), SettingDef('print.beep_on_ticket', 'true', "Play beep when a kitchen ticket prints: 'true' | 'false'", type='bool'),
@@ -51,5 +68,6 @@ MODULE = Module(
Mount('routers.business_day', '/api/business-day'), Mount('routers.business_day', '/api/business-day'),
Mount('routers.shifts', '/api/shifts'), Mount('routers.shifts', '/api/shifts'),
Mount('routers.flags', '/api/flags'), Mount('routers.flags', '/api/flags'),
Mount('routers.print_problems', '/api/print-problems'), # 6.10
), ),
) )
+11 -2
View File
@@ -17,6 +17,7 @@ MODULE = Module(
), ),
settings=( settings=(
SettingDef('signage.message', '', 'The message of the day on every signage screen with a message widget (Signage > Message of the day).'), 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.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.latitude', '', 'Latitude of the weather place.'),
SettingDef('signage.weather.longitude', '', 'Longitude of the weather place.'), SettingDef('signage.weather.longitude', '', 'Longitude of the weather place.'),
@@ -27,9 +28,17 @@ MODULE = Module(
device_app=DeviceApp(login_modes=('none',), scope=(), config=( device_app=DeviceApp(login_modes=('none',), scope=(), config=(
# What it plays and how the TV hangs (5.4a); the editor builds for the screen's shape # What it plays and how the TV hangs (5.4a); the editor builds for the screen's shape
ConfigField('playlist', 'ref', default=None, choices_from='signage_playlists'), ConfigField('playlist', 'ref', default=None, choices_from='signage_playlists'),
# or a schedule: which playlist plays when (5.4d); it wins over the single playlist # ... or a library slide shown alone (owner 2026-11-21; a playlist wins when both are set)
ConfigField('schedule', 'ref', default=None, choices_from='signage_schedules'), ConfigField('slide', 'ref', default=None, choices_from='signage_slides'),
ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')), ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')),
ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)), ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)),
# 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'),
)), )),
) )
+1
View File
@@ -12,3 +12,4 @@ python-multipart==0.0.9
cryptography==46.0.4 cryptography==46.0.4
alembic==1.14.0 alembic==1.14.0
tzdata==2026.6 tzdata==2026.6
imageio-ffmpeg==0.8.1
+15 -11
View File
@@ -7,7 +7,7 @@ import threading
from typing import Optional from typing import Optional
import jwt import jwt
from fastapi import APIRouter, Depends, HTTPException, Request, status from fastapi import APIRouter, Depends, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@@ -44,7 +44,7 @@ def _check_secret(user, pin, password, db) -> bool:
def do_login(db: Session, request: Request, *, client: str, username: str | None, user_id: int | None, def do_login(db: Session, request: Request, *, client: str, username: str | None, user_id: int | None,
pin: str | None, password: str | None) -> TokenResponse: pin: str | None, password: str | None, replace: bool = False) -> TokenResponse:
"""The one login path. Applies the client's login mode, its access key and the """The one login path. Applies the client's login mode, its access key and the
single-session rule, then creates a session (core/sessions.py).""" single-session rule, then creates a session (core/sessions.py)."""
if client not in ("manager", "waiter", "terminal"): if client not in ("manager", "waiter", "terminal"):
@@ -81,7 +81,7 @@ def do_login(db: Session, request: Request, *, client: str, username: str | None
if not holds(user, needed): if not holds(user, needed):
raise XeniaError("auth.client_not_allowed", client=client) raise XeniaError("auth.client_not_allowed", client=client)
row = sessions.start(db, user, client, request) row = sessions.start(db, user, client, request, replace=replace)
return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user)) return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user))
@@ -104,6 +104,10 @@ def _terminal_login(db: Session, request: Request, *, username, user_id, pin, pa
raise XeniaError("auth.login_mode_not_allowed", mode="password") raise XeniaError("auth.login_mode_not_allowed", mode="password")
if mode == "password" and not password: if mode == "password" and not password:
raise XeniaError("auth.login_mode_not_allowed", mode="pin") raise XeniaError("auth.login_mode_not_allowed", mode="pin")
if sessions.terminal_requires_username(db, device):
if not username:
raise XeniaError("auth.username_required")
user_id = None # usernames only: a picked id isn't enough (6F.7)
q = db.query(User).filter(User.is_active == True) # noqa: E712 q = db.query(User).filter(User.is_active == True) # noqa: E712
user = q.filter(User.username == username).first() if username else ( user = q.filter(User.username == username).first() if username else (
@@ -122,7 +126,7 @@ def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)):
"""POST {client: "manager"|"waiter"|"terminal", username?, user_id?, pin?, password?}. """POST {client: "manager"|"waiter"|"terminal", username?, user_id?, pin?, password?}.
"terminal" = a user on a paired device: send the X-Xenia-Device header.""" "terminal" = a user on a paired device: send the X-Xenia-Device header."""
return do_login(db, request, client=body.client, username=body.username, return do_login(db, request, client=body.client, username=body.username,
user_id=body.user_id, pin=body.pin, password=body.password) user_id=body.user_id, pin=body.pin, password=body.password, replace=body.replace)
@router.post("/refresh", response_model=TokenResponse) @router.post("/refresh", response_model=TokenResponse)
@@ -369,26 +373,26 @@ def update_me(body: UpdateMeRequest, db: Session = Depends(get_db), user: User =
# Password change — requires current_password verification # Password change — requires current_password verification
if body.new_password is not None: if body.new_password is not None:
if not body.current_password: if not body.current_password:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="current_password is required to set a new password") raise XeniaError("auth.password_current_required")
if not user.password_hash: if not user.password_hash:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Account has no password set") raise XeniaError("auth.no_password")
if not bcrypt.checkpw(body.current_password.encode(), user.password_hash.encode()): if not bcrypt.checkpw(body.current_password.encode(), user.password_hash.encode()):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Current password is incorrect") raise XeniaError("auth.password_wrong")
if len(body.new_password) < 6: if len(body.new_password) < 6:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="New password must be at least 6 characters") raise XeniaError("auth.password_too_short", min=6)
user.password_hash = bcrypt.hashpw(body.new_password.encode(), bcrypt.gensalt()).decode() user.password_hash = bcrypt.hashpw(body.new_password.encode(), bcrypt.gensalt()).decode()
# PIN change — no current PIN required (already authenticated) # PIN change — no current PIN required (already authenticated)
if body.new_pin is not None: if body.new_pin is not None:
if len(body.new_pin) < 4: if len(body.new_pin) < 4:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="PIN must be at least 4 digits") raise XeniaError("auth.pin_too_short", min=4)
user.pin_hash = bcrypt.hashpw(body.new_pin.encode(), bcrypt.gensalt()).decode() user.pin_hash = bcrypt.hashpw(body.new_pin.encode(), bcrypt.gensalt()).decode()
# Username change — check uniqueness # Username change — check uniqueness
if body.username is not None and body.username != user.username: if body.username is not None and body.username != user.username:
conflict = db.query(User).filter(User.username == body.username, User.id != user.id).first() conflict = db.query(User).filter(User.username == body.username, User.id != user.id).first()
if conflict: if conflict:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken") raise XeniaError("staff.username_taken")
user.username = body.username user.username = body.username
# Display name # Display name
@@ -421,7 +425,7 @@ def put_my_settings(body: WaiterSettingsPayload, db: Session = Depends(get_db),
try: try:
_json.loads(body.settings) # validate it's valid JSON _json.loads(body.settings) # validate it's valid JSON
except Exception: except Exception:
raise HTTPException(status_code=422, detail="settings must be valid JSON") raise XeniaError("settings.invalid_json")
user.waiter_settings = body.settings user.waiter_settings = body.settings
db.commit() db.commit()
return {"settings": user.waiter_settings} return {"settings": user.waiter_settings}
+50 -151
View File
@@ -1,5 +1,6 @@
from core.access.deps import require
from core.timeutil import business_date_of, parse_api_datetime, utcnow from core.timeutil import business_date_of, parse_api_datetime, utcnow
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, status
from sqlalchemy import func from sqlalchemy import func
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import Optional from typing import Optional
@@ -18,6 +19,7 @@ from schemas.business_day import BusinessDayOut, OpenBusinessDayRequest, CloseBu
from routers.deps import get_current_user, require_manager from routers.deps import get_current_user, require_manager
from models.user import User from models.user import User
from services.license_state import license_state from services.license_state import license_state
from core.errors import XeniaError
router = APIRouter() router = APIRouter()
@@ -42,39 +44,8 @@ def open_business_day(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require_manager),
): ):
existing = db.query(BusinessDay).filter(BusinessDay.status == "open").first() from services.business_days import open_day
if existing: return open_day(db, user_id=user.id, notes=body.notes)
raise HTTPException(status_code=400, detail="A business day is already open")
# Gate: admin lock (already enforced or pending)
if license_state.get("locked") or license_state.get("lock_pending"):
raise HTTPException(
status_code=423,
detail={
"code": "SYSTEM_LOCKED",
"message": "Το σύστημα έχει κλειδωθεί από διαχειριστή. Επικοινωνήστε με την υποστήριξη.",
},
)
# Gate: license expired and expiry grace period also over
if not license_state.get("licensed", True):
expires_at = license_state.get("expires_at", "")
raise HTTPException(
status_code=402,
detail={
"code": "LICENSE_EXPIRED",
"message": "Η άδεια χρήσης έχει λήξει. Ανανεώστε την άδεια ή επικοινωνήστε με την υποστήριξη.",
"expires_at": expires_at,
},
)
opened_at = utcnow()
day = BusinessDay(opened_by_id=user.id, notes=body.notes,
opened_at=opened_at, business_date=business_date_of(opened_at))
db.add(day)
db.commit()
db.refresh(day)
return day
@router.post("/close", response_model=BusinessDayOut) @router.post("/close", response_model=BusinessDayOut)
@@ -83,97 +54,9 @@ def close_business_day(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require_manager),
): ):
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() from services.business_days import close_day
if not day: return close_day(db, user_id=user.id, force=body.force, notes=body.notes,
raise HTTPException(status_code=404, detail="No open business day") store_closing_cash=body.store_closing_cash)
open_orders = db.query(Order).filter(
Order.business_day_id == day.id,
Order.status.in_(["open", "partially_paid"]),
).all()
if open_orders and not body.force:
# Count orders that have at least one active (unpaid) item — covers both
# "open" (fully unpaid) and "partially_paid" (partially unpaid) orders.
with_pending = sum(
1 for o in open_orders
if db.query(OrderItem).filter(
OrderItem.order_id == o.id,
OrderItem.status == "active",
).first() is not None
)
raise HTTPException(
status_code=409,
detail={
"message": f"{len(open_orders)} table(s) still open, {with_pending} with unpaid items.",
"open_orders": len(open_orders),
"partially_paid": with_pending,
},
)
now = utcnow()
# Close all non-terminal orders for this business day (open, partially_paid, paid)
all_unclosed = db.query(Order).filter(
Order.business_day_id == day.id,
Order.status.in_(["open", "partially_paid", "paid"]),
).all()
for order in all_unclosed:
was_unpaid = order.status in ("open", "partially_paid")
order.status = "closed"
order.closed_at = now
order.closed_by = user.id
if was_unpaid:
db.add(OrderAuditLog(
order_id=order.id,
event_type="ORDER_CLOSED",
waiter_id=user.id,
note="Force-closed at end of business day",
))
active_shifts = db.query(WaiterShift).filter(
WaiterShift.business_day_id == day.id,
WaiterShift.ended_at == None,
).all()
for shift in active_shifts:
from routers.shifts import compute_shift_total
shift.total_collected = compute_shift_total(shift.id, db)
shift.ended_at = now
# Clear all table flags and staff messages — fresh slate for the next day
db.query(TableFlagAssignment).delete(synchronize_session=False)
db.query(StaffMessageAck).delete(synchronize_session=False)
db.query(StaffMessage).delete(synchronize_session=False)
day.status = "closed"
day.closed_at = now
day.closed_by_id = user.id
if body.notes:
day.notes = body.notes
# Phase 2E: store-level cash reconciliation
if body.store_closing_cash is not None:
day.store_closing_cash = body.store_closing_cash
# expected = store_opening_cash + sum of all waiter collected amounts this day
all_shifts = db.query(WaiterShift).filter(WaiterShift.business_day_id == day.id).all()
total_collected = sum(s.total_collected or 0.0 for s in all_shifts)
expected_closing = (day.store_opening_cash or 0.0) + total_collected
day.store_cash_discrepancy = round(body.store_closing_cash - expected_closing, 2)
db.commit()
db.refresh(day)
# Deferred lock: if cloud requested a lock while the workday was open,
# enforce it now that the day has closed.
if license_state.get("lock_pending"):
license_state["lock_pending"] = False
license_state["locked"] = True
# Re-evaluate the license now that no workday is open (an expiry whose grace
# ended mid-service takes effect here) — also persists the state
from services.cloud_sync import apply_license
apply_license()
return day
class PatchBusinessDayRequest(BaseModel): class PatchBusinessDayRequest(BaseModel):
@@ -195,18 +78,18 @@ def patch_business_day(
""" """
day = db.query(BusinessDay).filter(BusinessDay.id == day_id).first() day = db.query(BusinessDay).filter(BusinessDay.id == day_id).first()
if not day: if not day:
raise HTTPException(status_code=404, detail="Business day not found") raise XeniaError("business_day.not_found")
if day.status != "closed": if day.status != "closed":
raise HTTPException(status_code=400, detail="Can only edit a closed business day") raise XeniaError("business_day.not_closed")
try: try:
new_closed = parse_api_datetime(body.closed_at) new_closed = parse_api_datetime(body.closed_at)
except (ValueError, TypeError): except (ValueError, TypeError):
raise HTTPException(status_code=422, detail="Invalid datetime format") raise XeniaError("validation.datetime")
now = utcnow() now = utcnow()
if new_closed > now: if new_closed > now:
raise HTTPException(status_code=400, detail="Close time cannot be in the future") raise XeniaError("business_day.close_in_future")
# Must not be earlier than the latest order closed_at in this day # Must not be earlier than the latest order closed_at in this day
last_order_close = ( last_order_close = (
@@ -218,10 +101,7 @@ def patch_business_day(
if last_order_close.tzinfo is None: if last_order_close.tzinfo is None:
last_order_close = last_order_close.replace(tzinfo=timezone.utc) last_order_close = last_order_close.replace(tzinfo=timezone.utc)
if new_closed < last_order_close: if new_closed < last_order_close:
raise HTTPException( raise XeniaError("business_day.close_before_last_order", time=_dt(last_order_close))
status_code=400,
detail=f"Close time cannot be earlier than the last order's close time ({_dt(last_order_close)})"
)
day.closed_at = new_closed day.closed_at = new_closed
db.commit() db.commit()
@@ -232,21 +112,18 @@ def patch_business_day(
def delete_business_day( def delete_business_day(
day_id: int, day_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("core.settings.manage")),
): ):
"""Permanently delete a business day. Only allowed when it has no shifts.""" """Permanently delete a business day. Only allowed when it has no shifts."""
day = db.query(BusinessDay).filter(BusinessDay.id == day_id).first() day = db.query(BusinessDay).filter(BusinessDay.id == day_id).first()
if not day: if not day:
raise HTTPException(status_code=404, detail="Business day not found") raise XeniaError("business_day.not_found")
if day.status == "open": if day.status == "open":
raise HTTPException(status_code=400, detail="Cannot delete an open business day — close it first") raise XeniaError("business_day.delete_open")
shift_count = db.query(WaiterShift).filter(WaiterShift.business_day_id == day_id).count() shift_count = db.query(WaiterShift).filter(WaiterShift.business_day_id == day_id).count()
if shift_count > 0: if shift_count > 0:
raise HTTPException( raise XeniaError("business_day.has_shifts", count=shift_count)
status_code=409,
detail=f"Δεν είναι δυνατή η διαγραφή: η εργάσιμη μέρα έχει {shift_count} βάρδια/ες. Διαγράψτε πρώτα όλες τις βάρδιες.",
)
db.query(Order).filter(Order.business_day_id == day_id).update( db.query(Order).filter(Order.business_day_id == day_id).update(
{"business_day_id": None}, synchronize_session=False {"business_day_id": None}, synchronize_session=False
@@ -266,12 +143,13 @@ def business_day_summary(
if day_id: if day_id:
day = db.query(BusinessDay).filter(BusinessDay.id == day_id).first() day = db.query(BusinessDay).filter(BusinessDay.id == day_id).first()
if not day: if not day:
raise HTTPException(status_code=404, detail="Business day not found") raise XeniaError("business_day.not_found")
else: else:
day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if not day: if not day:
raise HTTPException(status_code=404, detail="No open business day") raise XeniaError("business_day.none_open")
from services.sales import gross # 6.12a: a line's value includes its price change (discounts)
orders = db.query(Order).filter(Order.business_day_id == day.id).all() orders = db.query(Order).filter(Order.business_day_id == day.id).all()
order_ids = [o.id for o in orders] order_ids = [o.id for o in orders]
@@ -316,6 +194,12 @@ def business_day_summary(
"shift_pay": None, "shift_pay": None,
# distinct tables served (not order count) # distinct tables served (not order count)
"tables_served": 0, "tables_served": 0,
# 6.13c: lines this person put on customers' tabs, and tab money they received
"on_tab_items": 0.0,
"on_tab_value": 0.0,
"tab_cash": 0.0,
"tab_card": 0.0,
"tab_other": 0.0,
} }
return waiter_stats[uid] return waiter_stats[uid]
@@ -330,17 +214,18 @@ def business_day_summary(
if o.table_id: if o.table_id:
waiter_tables.setdefault(o.opened_by, set()).add(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: 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 continue
e = _waiter_entry(item.added_by) e = _waiter_entry(item.added_by)
e["items_ordered"] += item.quantity e["items_ordered"] += item.quantity
e["total_items_value"] += item.unit_price * item.quantity e["total_items_value"] += gross(item)
for item in paid_items: for item in paid_items:
if item.paid_by: if item.paid_by:
e = _waiter_entry(item.paid_by) e = _waiter_entry(item.paid_by)
val = item.unit_price * item.quantity val = gross(item)
e["items_paid"] += item.quantity e["items_paid"] += item.quantity
e["total_collected"] += val e["total_collected"] += val
method = (item.payment_method or "cash").lower() method = (item.payment_method or "cash").lower()
@@ -355,6 +240,15 @@ def business_day_summary(
else: else:
e["other"] += val e["other"] += val
# 6.13c: tabs: what went on them and the money received on them, per person and for the day
from services import tab_books
tabs_day = tab_books.for_day(db, day.id, {uid: (u.full_name or u.nickname or u.username) for uid, u in users_map.items()})
for uid, x in tabs_day.pop("by_person").items():
e = _waiter_entry(uid)
e["on_tab_items"] = x["on_tab_items"]
e["on_tab_value"] = x["on_tab_value"]
e["tab_cash"], e["tab_card"], e["tab_other"] = x["received"]["cash"], x["received"]["card"], x["received"]["other"]
from routers.shifts import compute_shift_pay from routers.shifts import compute_shift_pay
for shift in shifts: for shift in shifts:
e = _waiter_entry(shift.waiter_id) e = _waiter_entry(shift.waiter_id)
@@ -416,13 +310,14 @@ def business_day_summary(
for item in o.items: for item in o.items:
if item.status == "cancelled": if item.status == "cancelled":
continue continue
if not is_part(item):
entry["items"] += item.quantity entry["items"] += item.quantity
if item.status == "paid": if item.status == "paid":
entry["revenue"] += item.unit_price * item.quantity entry["revenue"] += gross(item)
# ── Per-printer summary ───────────────────────────────────────────────── # ── Per-printer summary ─────────────────────────────────────────────────
# Build item_id → value lookup for revenue-per-printer calculation # Build item_id → value lookup for revenue-per-printer calculation
items_value_map = {i.id: i.unit_price * i.quantity for i in all_items if i.status != "cancelled"} items_value_map = {i.id: gross(i) for i in all_items if i.status != "cancelled"}
printer_stats: dict = {} printer_stats: dict = {}
if order_ids: if order_ids:
@@ -464,7 +359,7 @@ def business_day_summary(
) )
active_shift_count = sum(1 for s in shifts if s.ended_at is None) active_shift_count = sum(1 for s in shifts if s.ended_at is None)
total_revenue = sum(i.unit_price * i.quantity for i in paid_items) total_revenue = sum(gross(i) for i in paid_items)
total_items_ordered = sum(i.quantity for i in all_items if i.status != "cancelled") total_items_ordered = sum(i.quantity for i in all_items if i.status != "cancelled")
total_orders = sum(1 for o in orders if o.status != "cancelled") total_orders = sum(1 for o in orders if o.status != "cancelled")
@@ -488,7 +383,7 @@ def business_day_summary(
cogs_uncosted_revenue = 0.0 cogs_uncosted_revenue = 0.0
cogs_uncosted_count = 0 cogs_uncosted_count = 0
for item in paid_items: for item in paid_items:
rev = item.unit_price * item.quantity rev = gross(item)
if item.unit_cost is not None: if item.unit_cost is not None:
cogs_trackable += item.unit_cost * item.quantity cogs_trackable += item.unit_cost * item.quantity
else: else:
@@ -518,9 +413,9 @@ def business_day_summary(
expenses_paid_today = round(sum(e.paid_amount for e in expenses_today), 2) expenses_paid_today = round(sum(e.paid_amount for e in expenses_today), 2)
expenses_due = round(expenses_total - expenses_paid_today, 2) expenses_due = round(expenses_total - expenses_paid_today, 2)
# TABBED REVENUE (items moved to tabs — not yet collected) # Lines of today's orders on customers' tabs: sold, not paid (6.13c)
tabbed_items = [i for i in all_items if i.status == "tabbed"] tabbed_items = [i for i in all_items if i.status == "tabbed"]
tabbed_revenue = round(sum(i.unit_price * i.quantity for i in tabbed_items), 2) tabbed_revenue = round(sum(gross(i) for i in tabbed_items), 2)
# NET estimate (revenue - COGS - labor - waste - expenses paid) # NET estimate (revenue - COGS - labor - waste - expenses paid)
net_estimate = round( net_estimate = round(
@@ -569,6 +464,9 @@ def business_day_summary(
"expenses_paid_today": expenses_paid_today, "expenses_paid_today": expenses_paid_today,
"expenses_due": expenses_due, "expenses_due": expenses_due,
"tabbed_revenue": tabbed_revenue, "tabbed_revenue": tabbed_revenue,
# 6.13c: put on tabs today (by anyone), tab money received today (by method; and the part
# received by people with no shift: in no drawer), every tab payment with who received it
"tabs": tabs_day,
"net_estimate": net_estimate, "net_estimate": net_estimate,
"net_has_unknowns": net_has_unknowns, "net_has_unknowns": net_has_unknowns,
} }
@@ -600,6 +498,7 @@ def business_day_history(
"opened_by_name": (w_opener.full_name or w_opener.username) if w_opener else None, "opened_by_name": (w_opener.full_name or w_opener.username) if w_opener else None,
"closed_by_id": day.closed_by_id, "closed_by_id": day.closed_by_id,
"closed_by_name": (w_closer.full_name or w_closer.username) if w_closer else None, "closed_by_name": (w_closer.full_name or w_closer.username) if w_closer else None,
"opened_auto": bool(day.opened_auto), "closed_auto": bool(day.closed_auto), # 6F.8
"notes": day.notes, "notes": day.notes,
"order_count": order_count, "order_count": order_count,
"revenue": round(revenue, 2), "revenue": round(revenue, 2),
+10 -27
View File
@@ -5,7 +5,7 @@ from core.timeutil import utcnow
from datetime import datetime, timezone from datetime import datetime, timezone
from typing import List, Optional from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from database import get_db from database import get_db
@@ -21,6 +21,7 @@ from schemas.chat import (
ParticipantOut, ParticipantOut,
) )
from services.ws_bus import broadcast_sync from services.ws_bus import broadcast_sync
from core.errors import XeniaError
router = APIRouter() router = APIRouter()
@@ -117,10 +118,10 @@ def _require_participant(db: Session, conv_id: int, user: User) -> Conversation:
"""Return the conversation if user is a participant, else 403/404.""" """Return the conversation if user is a participant, else 403/404."""
conv = db.query(Conversation).filter(Conversation.id == conv_id).first() conv = db.query(Conversation).filter(Conversation.id == conv_id).first()
if not conv: if not conv:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Conversation not found") raise XeniaError("chat.not_found")
is_participant = any(p.user_id == user.id for p in conv.participants) is_participant = any(p.user_id == user.id for p in conv.participants)
if not is_participant: if not is_participant:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not a participant") raise XeniaError("chat.not_participant")
return conv return conv
@@ -180,10 +181,7 @@ def create_conversation(
if payload.type == "direct": if payload.type == "direct":
if len(participant_ids) != 2: if len(participant_ids) != 2:
raise HTTPException( raise XeniaError("chat.direct_two")
status_code=status.HTTP_400_BAD_REQUEST,
detail="Direct conversations must have exactly 2 participants",
)
other_id = next(pid for pid in participant_ids if pid != user.id) other_id = next(pid for pid in participant_ids if pid != user.id)
# Check for an existing non-system direct conversation between these two users # Check for an existing non-system direct conversation between these two users
@@ -215,15 +213,9 @@ def create_conversation(
elif payload.type == "group": elif payload.type == "group":
if not payload.name: if not payload.name:
raise HTTPException( raise XeniaError("chat.group_name")
status_code=status.HTTP_400_BAD_REQUEST,
detail="Group conversations require a name",
)
else: else:
raise HTTPException( raise XeniaError("validation.choice", field='type', value=payload.type)
status_code=status.HTTP_400_BAD_REQUEST,
detail="type must be 'direct' or 'group'",
)
# Create the conversation # Create the conversation
conv = Conversation( conv = Conversation(
@@ -292,10 +284,7 @@ def send_message(
conv = _require_participant(db, conv_id, user) conv = _require_participant(db, conv_id, user)
if not payload.body.strip(): if not payload.body.strip():
raise HTTPException( raise XeniaError("chat.empty_message")
status_code=status.HTTP_400_BAD_REQUEST,
detail="Message body cannot be empty",
)
msg = ChatMessage( msg = ChatMessage(
conversation_id=conv_id, conversation_id=conv_id,
@@ -372,15 +361,9 @@ def leave_conversation(
conv = _require_participant(db, conv_id, user) conv = _require_participant(db, conv_id, user)
if conv.is_system: if conv.is_system:
raise HTTPException( raise XeniaError("chat.system_group")
status_code=status.HTTP_403_FORBIDDEN,
detail="Cannot leave the system group conversation",
)
if conv.type == "direct": if conv.type == "direct":
raise HTTPException( raise XeniaError("chat.leave_direct")
status_code=status.HTTP_400_BAD_REQUEST,
detail="Cannot leave a direct conversation — just stop using it",
)
participant = ( participant = (
db.query(ConversationParticipant) db.query(ConversationParticipant)
+25 -2
View File
@@ -27,7 +27,7 @@ import logging
from typing import Literal, Optional from typing import Literal, Optional
import httpx import httpx
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException from fastapi import APIRouter, BackgroundTasks, Depends
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from sqlalchemy.orm import Session, selectinload from sqlalchemy.orm import Session, selectinload
@@ -174,7 +174,7 @@ def get_orders_by_status(status: str, db: Session = Depends(get_db), user=Depend
if status == "history": if status == "history":
return (db.query(Order).filter(Order.source == "online", Order.online_status.in_(FINISHED)) return (db.query(Order).filter(Order.source == "online", Order.online_status.in_(FINISHED))
.order_by(Order.opened_at.desc()).limit(50).all()) .order_by(Order.opened_at.desc()).limit(50).all())
raise HTTPException(status_code=400, detail=f"Unknown status filter '{status}'. Use 'active' or 'history'.") raise XeniaError("validation.choice", field='status', value=status)
@router.get("/orders/incoming", response_model=list[OrderOut]) @router.get("/orders/incoming", response_model=list[OrderOut])
@@ -370,6 +370,29 @@ def arrive_booking(reservation_id: int, body: ArriveRequest, background: Backgro
return booking_out(r) return booking_out(r)
class KeepTableRequest(BaseModel):
table_id: Optional[int] = None
@router.post("/bookings/{reservation_id}/table")
def keep_table(reservation_id: int, body: KeepTableRequest, db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
"""Give a confirmed booking its table ahead (plan step 6.9, from 4.8), or take it back (null).
The table then shows RESERVED when the booking is near (routers/tables) and the pickers say
it's kept; seating them later offers it first. One table can't be kept for two bookings
within two hours of each other."""
from services import online_reservations as svc
r = _booking(db, reservation_id)
if r.status != "pending":
raise XeniaError("reservation.status_changed", current=r.status)
svc.keep_table(db, r, body.table_id)
r.updated_at = utcnow()
db.commit()
db.refresh(r)
broadcast_sync("reservation_updated", {"reservation_id": r.id, "status": r.status, "table_id": r.table_id})
broadcast_sync("table_list_changed", {})
return booking_out(r)
@router.post("/bookings/{reservation_id}/cancel") @router.post("/bookings/{reservation_id}/cancel")
def cancel_booking(reservation_id: int, body: CancelRequest, background: BackgroundTasks, def cancel_booking(reservation_id: int, body: CancelRequest, background: BackgroundTasks,
db: Session = Depends(get_db), user=Depends(_BOOKINGS)): db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
+10 -1
View File
@@ -64,6 +64,7 @@ class IdleBody(BaseModel):
qr_url: Optional[str] = Field(default=None, max_length=300) qr_url: Optional[str] = Field(default=None, max_length=300)
qr_caption: Optional[str] = Field(default=None, max_length=80) qr_caption: Optional[str] = Field(default=None, max_length=80)
theme: Literal["dark", "light"] = "dark" 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") @field_validator("qr_url")
@classmethod @classmethod
@@ -157,7 +158,15 @@ def idle_out(db, look: DisplayLook | None) -> dict:
cfg = config_of(look) cfg = config_of(look)
pics = _pictures(db, [cfg["logo"], cfg["image"], *cfg["slides"]]) 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 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], "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} "qr_link": _qr_link(cfg) if cfg["style"] == "qr" else None}
+92 -38
View File
@@ -1,4 +1,13 @@
from fastapi import APIRouter, Depends, HTTPException, status, Query """Customers (module `crm`; manager page in plan step 6.13b).
Writing and a customer's details need `crm.manage`. The list / search also works with the
dashboard key (attaching a customer to an order, 6.9). Spending and visits are counted by
services/sales.py (refunds off, lines on a tab are sold: 6.13c). Search ignores case and Greek
accents. Changes send `customers.changed`.
"""
import unicodedata
from fastapi import APIRouter, Depends, status, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import List, Optional from typing import List, Optional
@@ -7,21 +16,47 @@ from models.customers import Customer
from models.order import Order, OrderItem from models.order import Order, OrderItem
from models.user import User from models.user import User
from schemas.customers import CustomerCreate, CustomerUpdate, CustomerOut, AssignCustomerRequest from schemas.customers import CustomerCreate, CustomerUpdate, CustomerOut, AssignCustomerRequest
from core.access.deps import require_any from core.access.deps import require, require_any
from routers.deps import require_manager, get_current_user from core.errors import XeniaError
from services.ws_bus import broadcast_sync
router = APIRouter() router = APIRouter()
MANAGE = Depends(require("crm.manage"))
def _customer_out(c: Customer, db: Session) -> dict:
orders = db.query(Order).filter( def _changed():
Order.customer_id == c.id, broadcast_sync("customers.changed", {})
Order.status.in_(["closed", "paid"]),
).all()
total_spent = sum( def _fold(text: str | None) -> str:
sum(i.unit_price * i.quantity for i in o.items if i.status in ("active", "paid")) """Lower case without accents: "Γιώργος" and "γιωργος" match."""
for o in orders t = unicodedata.normalize("NFD", (text or "").casefold())
) return "".join(c for c in t if not unicodedata.combining(c))
def _check(fields: dict):
if "name" in fields and not (fields["name"] or "").strip():
raise XeniaError("validation.missing", field="name")
def _stats(db: Session, customer_ids) -> dict:
"""{customer_id: (visits, spent, last_visit)} from their finished orders, counted by services/sales.py."""
from services import sales
ids = list(customer_ids)
if not ids:
return {}
orders = db.query(Order).filter(Order.customer_id.in_(ids), Order.status.in_(["closed", "paid"])).all()
totals = sales.order_totals(db, orders)
out: dict = {}
for o in orders:
v, s, last = out.get(o.customer_id, (0, 0.0, None))
out[o.customer_id] = (v + 1, s + totals[o.id].takings, max(filter(None, (last, o.opened_at)), default=None))
return out
def _customer_out(c: Customer, db: Session, stats: dict | None = None) -> dict:
visits, spent, last = (stats if stats is not None else _stats(db, [c.id])).get(c.id, (0, 0.0, None))
return { return {
"id": c.id, "id": c.id,
"name": c.name, "name": c.name,
@@ -32,8 +67,9 @@ def _customer_out(c: Customer, db: Session) -> dict:
"is_active": c.is_active, "is_active": c.is_active,
"created_at": c.created_at, "created_at": c.created_at,
"created_by_id": c.created_by_id, "created_by_id": c.created_by_id,
"visit_count": len(orders), "visit_count": visits,
"total_spent": round(total_spent, 2), "total_spent": round(spent, 2),
"last_visit": last,
} }
@@ -42,28 +78,34 @@ def list_customers(
search: Optional[str] = None, search: Optional[str] = None,
include_inactive: bool = False, include_inactive: bool = False,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require_any("crm.manage", "core.dashboard.access")),
): ):
q = db.query(Customer) q = db.query(Customer)
if not include_inactive: if not include_inactive:
q = q.filter(Customer.is_active == True) q = q.filter(Customer.is_active == True)
if search:
term = f"%{search}%"
q = q.filter(
Customer.name.ilike(term) |
Customer.nickname.ilike(term) |
Customer.phone.ilike(term)
)
customers = q.order_by(Customer.name).all() customers = q.order_by(Customer.name).all()
return [_customer_out(c, db) for c in customers] if search:
words = _fold(search).split()
digits = "".join(ch for ch in search if ch.isdigit())
def hit(c):
text = _fold(f"{c.name} {c.nickname or ''} {c.email or ''} {c.notes or ''}")
phone = "".join(ch for ch in (c.phone or "") if ch.isdigit())
return all(w in text for w in words) or (len(digits) >= 3 and digits in phone)
customers = [c for c in customers if hit(c)]
stats = _stats(db, [c.id for c in customers])
return [_customer_out(c, db, stats) for c in customers]
@router.post("/", response_model=CustomerOut, status_code=status.HTTP_201_CREATED) @router.post("/", response_model=CustomerOut, status_code=status.HTTP_201_CREATED)
def create_customer(body: CustomerCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def create_customer(body: CustomerCreate, db: Session = Depends(get_db), user: User = MANAGE):
customer = Customer(**body.model_dump(), created_by_id=user.id) fields = body.model_dump()
_check(fields)
fields["name"] = fields["name"].strip()
customer = Customer(**fields, created_by_id=user.id)
db.add(customer) db.add(customer)
db.commit() db.commit()
db.refresh(customer) db.refresh(customer)
_changed()
return _customer_out(customer, db) return _customer_out(customer, db)
@@ -78,51 +120,63 @@ def lookup_customer(phone: str = Query(..., max_length=40), db: Session = Depend
@router.get("/{customer_id}", response_model=CustomerOut) @router.get("/{customer_id}", response_model=CustomerOut)
def get_customer(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)): def get_customer(customer_id: int, db: Session = Depends(get_db), user: User = MANAGE):
c = db.query(Customer).filter(Customer.id == customer_id).first() c = db.query(Customer).filter(Customer.id == customer_id).first()
if not c: if not c:
raise HTTPException(status_code=404, detail="Customer not found") raise XeniaError("customer.not_found")
return _customer_out(c, db) return _customer_out(c, db)
@router.put("/{customer_id}", response_model=CustomerOut) @router.put("/{customer_id}", response_model=CustomerOut)
def update_customer(customer_id: int, body: CustomerUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def update_customer(customer_id: int, body: CustomerUpdate, db: Session = Depends(get_db), user: User = MANAGE):
c = db.query(Customer).filter(Customer.id == customer_id).first() c = db.query(Customer).filter(Customer.id == customer_id).first()
if not c: if not c:
raise HTTPException(status_code=404, detail="Customer not found") raise XeniaError("customer.not_found")
for field, value in body.model_dump(exclude_none=True).items(): # Fields sent as null are cleared (nickname, phone…); name and is_active only change when given
setattr(c, field, value) fields = body.model_dump(exclude_unset=True)
for k in ("name", "is_active"):
if fields.get(k) is None:
fields.pop(k, None)
_check(fields)
for field, value in fields.items():
setattr(c, field, value.strip() if field == "name" else value)
db.commit() db.commit()
db.refresh(c) db.refresh(c)
_changed()
return _customer_out(c, db) return _customer_out(c, db)
@router.delete("/{customer_id}", status_code=status.HTTP_204_NO_CONTENT) @router.delete("/{customer_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_customer(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)): def delete_customer(customer_id: int, db: Session = Depends(get_db), user: User = MANAGE):
c = db.query(Customer).filter(Customer.id == customer_id).first() c = db.query(Customer).filter(Customer.id == customer_id).first()
if not c: if not c:
raise HTTPException(status_code=404, detail="Customer not found") raise XeniaError("customer.not_found")
c.is_active = False c.is_active = False
db.commit() db.commit()
_changed()
@router.get("/{customer_id}/orders") @router.get("/{customer_id}/orders")
def customer_orders(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)): def customer_orders(customer_id: int, db: Session = Depends(get_db), user: User = MANAGE):
c = db.query(Customer).filter(Customer.id == customer_id).first() c = db.query(Customer).filter(Customer.id == customer_id).first()
if not c: if not c:
raise HTTPException(status_code=404, detail="Customer not found") raise XeniaError("customer.not_found")
from models.table import Table from models.table import Table
from services import sales
orders = db.query(Order).filter(Order.customer_id == customer_id).order_by(Order.opened_at.desc()).all() orders = db.query(Order).filter(Order.customer_id == customer_id).order_by(Order.opened_at.desc()).all()
tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
totals = sales.order_totals(db, orders)
result = [] result = []
for o in orders: for o in orders:
total = sum(i.unit_price * i.quantity for i in o.items if i.status in ("active", "paid")) tot = totals[o.id]
result.append({ result.append({
"id": o.id, "id": o.id,
"table_name": tables_map.get(o.table_id) if o.table_id else None, "table_name": tables_map.get(o.table_id) if o.table_id else None,
"order_type": o.order_type,
"opened_at": o.opened_at, "opened_at": o.opened_at,
"status": o.status, "status": o.status,
"total": round(total, 2), "total": round(tot.takings, 2),
"item_count": sum(i.quantity for i in o.items if i.status in ("active", "paid")), "on_tab": round(tot.on_tab, 2),
"item_count": tot.units,
}) })
return {"orders": result} return {"orders": result}
+42 -15
View File
@@ -1,8 +1,8 @@
from core.timeutil import venue_date, utcnow from core.timeutil import venue_date, utcnow
import json import json
from core import sales_points from core import allergens, menu_languages, sales_points
from datetime import datetime, timezone from datetime import datetime, timezone
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@@ -14,6 +14,7 @@ from models.product import (
from models.table import Table, TableGroup from models.table import Table, TableGroup
from models.user import User from models.user import User
from routers.deps import require_manager from routers.deps import require_manager
from core.errors import XeniaError
router = APIRouter() router = APIRouter()
@@ -21,11 +22,17 @@ EXPORT_VERSION = 1 # tables bundle
CATALOG_EXPORT_VERSION = 2 # catalogue bundle: v2 = products listed in several categories (D-23) CATALOG_EXPORT_VERSION = 2 # catalogue bundle: v2 = products listed in several categories (D-23)
def _names(value):
"""A choice's names per language from a bundle (0042), stored cleaned."""
return menu_languages.dump(menu_languages.normalize_names(value))
def _serialize_product(p: Product) -> dict: def _serialize_product(p: Product) -> dict:
quick_options = [ quick_options = [
{"name": qo.name, "price": qo.price, "allow_multiple": qo.allow_multiple, {"name": qo.name, "price": qo.price, "allow_multiple": qo.allow_multiple,
"sort_order": qo.sort_order, "is_favorite": qo.is_favorite, "sort_order": qo.sort_order, "is_favorite": qo.is_favorite,
"favorite_sort_order": qo.favorite_sort_order, "is_compact": qo.is_compact} "favorite_sort_order": qo.favorite_sort_order, "is_compact": qo.is_compact,
"translations": menu_languages.names_of(qo)}
for qo in p.quick_options for qo in p.quick_options
] ]
options = [] options = []
@@ -33,10 +40,12 @@ def _serialize_product(p: Product) -> dict:
sub = json.loads(opt.sub_choices) if opt.sub_choices else [] sub = json.loads(opt.sub_choices) if opt.sub_choices else []
options.append({"name": opt.name, "extra_cost": opt.extra_cost, options.append({"name": opt.name, "extra_cost": opt.extra_cost,
"allow_multiple": opt.allow_multiple, "sub_choices": sub, "allow_multiple": opt.allow_multiple, "sub_choices": sub,
"is_favorite": opt.is_favorite, "favorite_sort_order": opt.favorite_sort_order}) "is_favorite": opt.is_favorite, "favorite_sort_order": opt.favorite_sort_order,
"translations": menu_languages.names_of(opt)})
ingredients = [ ingredients = [
{"name": ing.name, "extra_cost": ing.extra_cost, {"name": ing.name, "extra_cost": ing.extra_cost,
"is_favorite": ing.is_favorite, "favorite_sort_order": ing.favorite_sort_order} "is_favorite": ing.is_favorite, "favorite_sort_order": ing.favorite_sort_order,
"translations": menu_languages.names_of(ing)}
for ing in p.ingredients for ing in p.ingredients
] ]
preference_sets = [] preference_sets = []
@@ -49,16 +58,20 @@ def _serialize_product(p: Product) -> dict:
default_index = i default_index = i
sub = json.loads(ch.sub_choices) if ch.sub_choices else [] sub = json.loads(ch.sub_choices) if ch.sub_choices else []
choices.append({"name": ch.name, "extra_cost": ch.extra_cost, choices.append({"name": ch.name, "extra_cost": ch.extra_cost,
"sub_choices": sub, "disables_subset": ch.disables_subset}) "sub_choices": sub, "disables_subset": ch.disables_subset,
"translations": menu_languages.names_of(ch)})
preference_sets.append({ preference_sets.append({
"name": ps.name, "choices": choices, "name": ps.name, "choices": choices,
"default_choice_index": default_index, "shared_subset": shared, "default_choice_index": default_index, "shared_subset": shared,
"is_favorite": ps.is_favorite, "favorite_sort_order": ps.favorite_sort_order, "is_favorite": ps.is_favorite, "favorite_sort_order": ps.favorite_sort_order,
"translations": menu_languages.names_of(ps),
}) })
return { return {
"name": p.name, "base_price": p.base_price, "is_available": p.is_available, "name": p.name, "base_price": p.base_price, "is_available": p.is_available,
"lifecycle_status": p.lifecycle_status, "sort_order": p.sort_order, "lifecycle_status": p.lifecycle_status, "sort_order": p.sort_order,
"sold_at": sales_points.sold_at(p), "sold_at": sales_points.sold_at(p),
"allergens": allergens.of(p),
"translations": menu_languages.of(p),
"quick_options": quick_options, "options": options, "quick_options": quick_options, "options": options,
"ingredients": ingredients, "preference_sets": preference_sets, "ingredients": ingredients, "preference_sets": preference_sets,
} }
@@ -75,6 +88,7 @@ def _serialize_category(cat: Category) -> dict:
"name": cat.name, "color": cat.color, "sort_order": cat.sort_order, "name": cat.name, "color": cat.color, "sort_order": cat.sort_order,
"parent_name": cat.parent.name if cat.parent else None, "parent_name": cat.parent.name if cat.parent else None,
"general_sort_order": cat.general_sort_order, "auto_expanded": cat.auto_expanded, "general_sort_order": cat.general_sort_order, "auto_expanded": cat.auto_expanded,
"translations": menu_languages.of(cat),
"products": products, "products": products,
} }
@@ -146,9 +160,9 @@ def export_tables(db: Session = Depends(get_db), user: User = Depends(require_ma
@router.post("/import/catalog") @router.post("/import/catalog")
def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = Depends(require_manager)): def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = Depends(require_manager)):
if payload.get("bundle") != "catalog": if payload.get("bundle") != "catalog":
raise HTTPException(status_code=400, detail="Wrong bundle type. Expected 'catalog'.") raise XeniaError("transfer.wrong_type", expected='catalog')
if payload.get("xenia_export_version", 0) != CATALOG_EXPORT_VERSION: if payload.get("xenia_export_version", 0) != CATALOG_EXPORT_VERSION:
raise HTTPException(status_code=400, detail="Unsupported export version.") raise XeniaError("transfer.version")
data = payload.get("data", {}) data = payload.get("data", {})
categories_data = data.get("categories", []) categories_data = data.get("categories", [])
@@ -163,6 +177,8 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
existing.sort_order = cat_data.get("sort_order", 0) existing.sort_order = cat_data.get("sort_order", 0)
existing.general_sort_order = cat_data.get("general_sort_order", 0) existing.general_sort_order = cat_data.get("general_sort_order", 0)
existing.auto_expanded = cat_data.get("auto_expanded", False) existing.auto_expanded = cat_data.get("auto_expanded", False)
if "translations" in cat_data: # 6.4; older bundles: unchanged
existing.translations = menu_languages.dump(menu_languages.normalize_category(cat_data["translations"]))
db.flush() db.flush()
return existing return existing
else: else:
@@ -173,6 +189,7 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
parent_id=parent_id, parent_id=parent_id,
general_sort_order=cat_data.get("general_sort_order", 0), general_sort_order=cat_data.get("general_sort_order", 0),
auto_expanded=cat_data.get("auto_expanded", False), auto_expanded=cat_data.get("auto_expanded", False),
translations=menu_languages.dump(menu_languages.normalize_category(cat_data.get("translations"))),
) )
db.add(cat) db.add(cat)
db.flush() db.flush()
@@ -187,6 +204,10 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
existing.sort_order = prod_data.get("sort_order", 0) existing.sort_order = prod_data.get("sort_order", 0)
if "sold_at" in prod_data: # phase 3S; older bundles: unchanged if "sold_at" in prod_data: # phase 3S; older bundles: unchanged
existing.sold_at = sales_points.dump(prod_data["sold_at"]) existing.sold_at = sales_points.dump(prod_data["sold_at"])
if "allergens" in prod_data: # 6.3; older bundles: unchanged
existing.allergens = allergens.dump(prod_data["allergens"])
if "translations" in prod_data: # 6.4
existing.translations = menu_languages.dump(menu_languages.normalize_product(prod_data["translations"]))
db.flush() db.flush()
product = existing product = existing
else: else:
@@ -197,6 +218,8 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
lifecycle_status=prod_data.get("lifecycle_status", "active"), lifecycle_status=prod_data.get("lifecycle_status", "active"),
sort_order=prod_data.get("sort_order", 0), sort_order=prod_data.get("sort_order", 0),
sold_at=sales_points.dump(prod_data.get("sold_at", sales_points.ALL)), sold_at=sales_points.dump(prod_data.get("sold_at", sales_points.ALL)),
allergens=allergens.dump(prod_data.get("allergens")),
translations=menu_languages.dump(menu_languages.normalize_product(prod_data.get("translations"))),
) )
db.add(product) db.add(product)
db.flush() db.flush()
@@ -213,7 +236,9 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
db.flush() db.flush()
for qo in prod_data.get("quick_options", []): for qo in prod_data.get("quick_options", []):
db.add(ProductQuickOption(product_id=product.id, **qo)) qo = dict(qo)
names = _names(qo.pop("translations", None))
db.add(ProductQuickOption(product_id=product.id, **qo, translations=names))
for opt in prod_data.get("options", []): for opt in prod_data.get("options", []):
sub_json = json.dumps(opt.get("sub_choices", [])) sub_json = json.dumps(opt.get("sub_choices", []))
@@ -221,11 +246,13 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
product_id=product.id, name=opt["name"], extra_cost=opt.get("extra_cost", 0.0), product_id=product.id, name=opt["name"], extra_cost=opt.get("extra_cost", 0.0),
allow_multiple=opt.get("allow_multiple", False), sub_choices=sub_json, allow_multiple=opt.get("allow_multiple", False), sub_choices=sub_json,
is_favorite=opt.get("is_favorite", False), is_favorite=opt.get("is_favorite", False),
favorite_sort_order=opt.get("favorite_sort_order", 0), favorite_sort_order=opt.get("favorite_sort_order", 0), translations=_names(opt.get("translations")),
)) ))
for ing in prod_data.get("ingredients", []): for ing in prod_data.get("ingredients", []):
db.add(ProductIngredient(product_id=product.id, **ing)) ing = dict(ing)
names = _names(ing.pop("translations", None))
db.add(ProductIngredient(product_id=product.id, **ing, translations=names))
for ps_data in prod_data.get("preference_sets", []): for ps_data in prod_data.get("preference_sets", []):
shared_json = json.dumps(ps_data["shared_subset"]) if ps_data.get("shared_subset") else None shared_json = json.dumps(ps_data["shared_subset"]) if ps_data.get("shared_subset") else None
@@ -233,7 +260,7 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
product_id=product.id, name=ps_data["name"], product_id=product.id, name=ps_data["name"],
shared_subset=shared_json, shared_subset=shared_json,
is_favorite=ps_data.get("is_favorite", False), is_favorite=ps_data.get("is_favorite", False),
favorite_sort_order=ps_data.get("favorite_sort_order", 0), favorite_sort_order=ps_data.get("favorite_sort_order", 0), translations=_names(ps_data.get("translations")),
) )
db.add(ps) db.add(ps)
db.flush() db.flush()
@@ -242,7 +269,7 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
sub_json = json.dumps(ch.get("sub_choices", [])) sub_json = json.dumps(ch.get("sub_choices", []))
choice = ProductPreferenceChoice( choice = ProductPreferenceChoice(
set_id=ps.id, name=ch["name"], extra_cost=ch.get("extra_cost", 0.0), set_id=ps.id, name=ch["name"], extra_cost=ch.get("extra_cost", 0.0),
sub_choices=sub_json, disables_subset=ch.get("disables_subset", False), sub_choices=sub_json, disables_subset=ch.get("disables_subset", False), translations=_names(ch.get("translations")),
) )
db.add(choice) db.add(choice)
db.flush() db.flush()
@@ -299,9 +326,9 @@ def import_catalog(payload: dict, db: Session = Depends(get_db), user: User = De
@router.post("/import/tables") @router.post("/import/tables")
def import_tables(payload: dict, db: Session = Depends(get_db), user: User = Depends(require_manager)): def import_tables(payload: dict, db: Session = Depends(get_db), user: User = Depends(require_manager)):
if payload.get("bundle") != "tables": if payload.get("bundle") != "tables":
raise HTTPException(status_code=400, detail="Wrong bundle type. Expected 'tables'.") raise XeniaError("transfer.wrong_type", expected='tables')
if payload.get("xenia_export_version", 0) != EXPORT_VERSION: if payload.get("xenia_export_version", 0) != EXPORT_VERSION:
raise HTTPException(status_code=400, detail="Unsupported export version.") raise XeniaError("transfer.version")
data = payload.get("data", {}) data = payload.get("data", {})
for group_data in data.get("table_groups", []): for group_data in data.get("table_groups", []):
+4 -3
View File
@@ -1,7 +1,7 @@
from core.timeutil import utcnow from core.timeutil import utcnow
import jwt import jwt
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from fastapi import Depends, HTTPException, Request, status from fastapi import Depends, Request, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@@ -67,7 +67,7 @@ def decode_session(token: str, db: Session | None = None):
except jwt.ExpiredSignatureError: except jwt.ExpiredSignatureError:
raise XeniaError("auth.session_ended") raise XeniaError("auth.session_ended")
except jwt.InvalidTokenError: except jwt.InvalidTokenError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") raise XeniaError("auth.session_ended")
return payload, sessions.validate(payload.get("sid"), db) return payload, sessions.validate(payload.get("sid"), db)
@@ -93,7 +93,7 @@ def user_from_token(token: str, request: Request, db: Session):
return make_support_user(), payload.get("sid") return make_support_user(), payload.get("sid")
user = db.query(User).filter(User.id == int(payload["sub"]), User.is_active == True).first() user = db.query(User).filter(User.id == int(payload["sub"]), User.is_active == True).first()
if not user: if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found") raise XeniaError("auth.session_ended")
set_log_context(user=user.id) set_log_context(user=user.id)
return user, payload.get("sid") return user, payload.get("sid")
@@ -115,6 +115,7 @@ get_current_user.__xenia_access__ = ("signed_in",)
# Kept as aliases so the ~200 existing route signatures stay as they are. New code # Kept as aliases so the ~200 existing route signatures stay as they are. New code
# uses core.access.deps.require("<key>") directly. # uses core.access.deps.require("<key>") directly.
from core.access.deps import require # noqa: E402 from core.access.deps import require # noqa: E402
from core.errors import XeniaError
require_manager = require("core.dashboard.access") require_manager = require("core.dashboard.access")
require_staff_manager = require("core.staff.manage") require_staff_manager = require("core.staff.manage")
+12 -2
View File
@@ -151,6 +151,8 @@ def effective_login_mode(db, device) -> str:
can't use that one, the app's first mode (signage etc.: 'none').""" can't use that one, the app's first mode (signage etc.: 'none')."""
modes = _app(device.app_key).device_app.login_modes modes = _app(device.app_key).device_app.login_modes
mode = device.login_mode or sessions._setting(db, "auth.default_login_mode", "pin") mode = device.login_mode or sessions._setting(db, "auth.default_login_mode", "pin")
if mode == "tap" and sessions.terminal_requires_username(db, device):
mode = next((m for m in ("pin", "password") if m in modes), mode) # usernames: no name to tap (6F.7)
return mode if mode in modes else modes[0] return mode if mode in modes else modes[0]
@@ -175,6 +177,8 @@ def _out(d: Device, db) -> dict:
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key,
"config": _effective_config(d, db) if d.app_key in registry() else {}, "config": _effective_config(d, db) if d.app_key in registry() else {},
"login_mode": d.login_mode, "login_mode": d.login_mode,
"require_username": d.require_username,
"effective_require_username": sessions.terminal_requires_username(db, d),
"effective_login_mode": effective_login_mode(db, d) if d.app_key in registry() else None, "effective_login_mode": effective_login_mode(db, d) if d.app_key in registry() else None,
"linked_device_id": d.linked_device_id, "user_agent": d.user_agent, "linked_device_id": d.linked_device_id, "user_agent": d.user_agent,
"paired_at": iso_z(d.paired_at), "paired_by": d.paired_by, "paired_at": iso_z(d.paired_at), "paired_by": d.paired_by,
@@ -191,6 +195,7 @@ def _self_out(d: Device, db) -> dict:
return { return {
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": _effective_config(d, db), "id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": _effective_config(d, db),
"login_mode": effective_login_mode(db, d), "login_mode": effective_login_mode(db, d),
"require_username": sessions.terminal_requires_username(db, d),
"linked_device": ({"id": linked.id, "uuid": linked.uuid, "name": linked.name, "app_key": linked.app_key} "linked_device": ({"id": linked.id, "uuid": linked.uuid, "name": linked.name, "app_key": linked.app_key}
if linked is not None and linked.revoked_at is None else None), if linked is not None and linked.revoked_at is None else None),
"app_status": status, # "ok" | "module.disabled" | "module.not_licensed": show "app disabled" "app_status": status, # "ok" | "module.disabled" | "module.not_licensed": show "app disabled"
@@ -249,6 +254,7 @@ class PairApprove(BaseModel):
name: str = Field(min_length=1, max_length=60) name: str = Field(min_length=1, max_length=60)
config: Optional[dict] = None config: Optional[dict] = None
login_mode: Optional[str] = None # None/"" = site default login_mode: Optional[str] = None # None/"" = site default
require_username: Optional[bool] = None # None = site default (6F.7)
linked_device_id: Optional[int] = None linked_device_id: Optional[int] = None
@@ -256,6 +262,7 @@ class DevicePatch(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=60) name: Optional[str] = Field(None, min_length=1, max_length=60)
config: Optional[dict] = None config: Optional[dict] = None
login_mode: Optional[str] = None # "" or null = back to the site default login_mode: Optional[str] = None # "" or null = back to the site default
require_username: Optional[bool] = None # null = back to the site default (6F.7)
linked_device_id: Optional[int] = None # null/0 = unlink linked_device_id: Optional[int] = None # null/0 = unlink
@@ -285,6 +292,7 @@ def approve_device(body: PairApprove, db: Session = Depends(get_db), user=Depend
d = Device(uuid=uuidlib.uuid4().hex, name=body.name.strip(), app_key=body.app_key, d = Device(uuid=uuidlib.uuid4().hex, name=body.name.strip(), app_key=body.app_key,
config=_config(body.app_key, body.config, db), config=_config(body.app_key, body.config, db),
login_mode=_check_mode(body.app_key, body.login_mode), login_mode=_check_mode(body.app_key, body.login_mode),
require_username=body.require_username,
linked_device_id=_check_link(db, None, body.linked_device_id), linked_device_id=_check_link(db, None, body.linked_device_id),
user_agent=row.user_agent, paired_at=now, paired_by=getattr(user, "id", None) or None) user_agent=row.user_agent, paired_at=now, paired_by=getattr(user, "id", None) or None)
db.add(d) db.add(d)
@@ -307,8 +315,8 @@ def device_users(db: Session = Depends(get_db), device=Depends(require_device())
"""Who can log in on this device (holders of '<app>.access'), for the name picker.""" """Who can log in on this device (holders of '<app>.access'), for the name picker."""
from core.access.queries import users_with_key from core.access.queries import users_with_key
from models.user import User from models.user import User
if effective_login_mode(db, device) == "none": if effective_login_mode(db, device) == "none" or sessions.terminal_requires_username(db, device):
return [] return [] # usernames on (6F.7): nobody is listed, the screen asks for a username
users = users_with_key(db, f"{device.app_key}.access").order_by(User.full_name).all() users = users_with_key(db, f"{device.app_key}.access").order_by(User.full_name).all()
return [{"id": u.id, "full_name": u.full_name, "nickname": u.nickname, "avatar_url": u.avatar_url} return [{"id": u.id, "full_name": u.full_name, "nickname": u.nickname, "avatar_url": u.avatar_url}
for u in users if u.role != "superadmin"] for u in users if u.role != "superadmin"]
@@ -357,6 +365,8 @@ def update_device(device_id: int, body: DevicePatch, db: Session = Depends(get_d
d.config = _config(d.app_key, body.config, db) d.config = _config(d.app_key, body.config, db)
if "login_mode" in sent: if "login_mode" in sent:
d.login_mode = _check_mode(d.app_key, body.login_mode) d.login_mode = _check_mode(d.app_key, body.login_mode)
if "require_username" in sent:
d.require_username = body.require_username
if "linked_device_id" in sent: if "linked_device_id" in sent:
d.linked_device_id = _check_link(db, d.id, body.linked_device_id) d.linked_device_id = _check_link(db, d.id, body.linked_device_id)
db.commit() db.commit()
+202 -28
View File
@@ -1,24 +1,102 @@
from core.timeutil import utcnow """Expenses and the supplier book (module `expenses`; manager pages in plan step 6.13a).
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, HTTPException, status, Query Every route needs `expenses.manage`; reading the list also works with `reports.view` (the
expenses report). Changes send the live event `expenses.changed` so open pages refresh.
An expense is entered once (total, category, maybe a supplier and a date it's due) and paid
in one or more payments; it is "due", "partial" or "paid" from what was paid. A payment can't
be more than what is still due, and the total can't drop below what was already paid.
"""
from datetime import date
from decimal import ROUND_HALF_UP, Decimal
from fastapi import APIRouter, Depends, File, Query, UploadFile, status
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import List, Optional from typing import List, Optional
from database import get_db from database import get_db
from models.expenses import Contact, Expense, ExpensePayment from models.expenses import Contact, Expense, ExpenseDocument, ExpenseLine, ExpensePayment
from models.user import User from models.user import User
from schemas.expenses import ( from schemas.expenses import (
ContactCreate, ContactUpdate, ContactOut, ContactCreate, ContactUpdate, ContactOut,
ExpenseCreate, ExpenseUpdate, ExpenseOut, ExpenseCreate, ExpenseUpdate, ExpenseOut,
ExpensePaymentCreate, ExpensePaymentOut, ExpensePaymentCreate, ExpensePaymentOut,
) )
from routers.deps import require_manager from core.access.deps import require, require_any
from core.errors import XeniaError
from core.timeutil import venue_day_window
from services import expense_docs
from services.ws_bus import broadcast_sync
contacts_router = APIRouter() contacts_router = APIRouter()
expenses_router = APIRouter() expenses_router = APIRouter()
MANAGE = Depends(require("expenses.manage"))
CATEGORIES = ("supplier", "utilities", "rent", "maintenance", "staff", "equipment", "other")
CONTACT_TYPES = ("supplier", "staff", "utility", "other")
def _changed():
broadcast_sync("expenses.changed", {})
def _check_contact(fields: dict):
if "type" in fields and fields["type"] not in CONTACT_TYPES:
raise XeniaError("validation.choice", field="type", value=fields["type"])
if "name" in fields and not (fields["name"] or "").strip():
raise XeniaError("validation.missing", field="name")
def _line_money(ln) -> tuple[float, float, float]:
"""(net, vat, total) of a line, rounded to cents."""
q = ln["quantity"] if isinstance(ln, dict) else ln.quantity
p = ln["unit_price"] if isinstance(ln, dict) else ln.unit_price
r = ln["vat_rate"] if isinstance(ln, dict) else ln.vat_rate
cents = Decimal("0.01")
net = (Decimal(str(q or 0)) * Decimal(str(p or 0))).quantize(cents, ROUND_HALF_UP)
vat = (net * Decimal(str(r or 0)) / 100).quantize(cents, ROUND_HALF_UP) # as on a Greek invoice: half up
return float(net), float(vat), float(net + vat)
def _take_lines(fields: dict) -> list | None:
"""The lines sent (checked), and the total they make into fields["total_amount"]."""
lines = fields.pop("lines", None)
if lines is None:
return None
out = []
for ln in lines:
d = (ln.get("description") or "").strip()
if not d:
raise XeniaError("validation.missing", field="lines.description")
if ln.get("quantity") is None or ln["quantity"] <= 0:
raise XeniaError("validation.positive", field="lines.quantity")
if ln.get("unit_price") is None or ln["unit_price"] < 0:
raise XeniaError("validation.positive", field="lines.unit_price")
if (ln.get("vat_rate") or 0) < 0 or (ln.get("vat_rate") or 0) > 100:
raise XeniaError("validation.choice", field="lines.vat_rate", value=ln.get("vat_rate"))
out.append({**ln, "description": d[:200], "vat_rate": ln.get("vat_rate") or 0.0})
if out:
fields["total_amount"] = round(sum(_line_money(ln)[2] for ln in out), 2)
return out
def _set_lines(expense: Expense, lines: list | None):
if lines is None:
return
expense.lines = [ExpenseLine(position=i, **ln) for i, ln in enumerate(lines)]
def _check_expense(db: Session, fields: dict, paid: float = 0.0):
if "description" in fields and not (fields["description"] or "").strip():
raise XeniaError("validation.missing", field="description")
if "category" in fields and fields["category"] not in CATEGORIES:
raise XeniaError("validation.choice", field="category", value=fields["category"])
if "total_amount" in fields:
if fields["total_amount"] is None or fields["total_amount"] <= 0:
raise XeniaError("validation.positive", field="total_amount")
if fields["total_amount"] < paid - 0.005:
raise XeniaError("expense.below_paid", paid=f"{paid:.2f}")
if fields.get("contact_id") and not db.query(Contact).filter(Contact.id == fields["contact_id"]).first():
raise XeniaError("contact.not_found")
def _expense_status(total: float, paid: float) -> str: def _expense_status(total: float, paid: float) -> str:
if paid >= total: if paid >= total:
@@ -67,6 +145,11 @@ def _expense_out(e: Expense) -> dict:
"created_at": e.created_at, "created_at": e.created_at,
"notes": e.notes, "notes": e.notes,
"payments": payments_out, "payments": payments_out,
"lines": [{"id": ln.id, "description": ln.description, "quantity": ln.quantity, "unit_price": ln.unit_price,
"vat_rate": ln.vat_rate, **dict(zip(("net", "vat", "total"), _line_money(ln)))} for ln in e.lines],
"net_amount": round(sum(_line_money(ln)[0] for ln in e.lines), 2) if e.lines else None,
"vat_amount": round(sum(_line_money(ln)[1] for ln in e.lines), 2) if e.lines else None,
"documents": [expense_docs.out(d) for d in e.documents],
} }
@@ -76,7 +159,7 @@ def _expense_out(e: Expense) -> dict:
def list_contacts( def list_contacts(
include_inactive: bool = False, include_inactive: bool = False,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = MANAGE,
): ):
q = db.query(Contact) q = db.query(Contact)
if not include_inactive: if not include_inactive:
@@ -85,33 +168,45 @@ def list_contacts(
@contacts_router.post("/", response_model=ContactOut, status_code=status.HTTP_201_CREATED) @contacts_router.post("/", response_model=ContactOut, status_code=status.HTTP_201_CREATED)
def create_contact(body: ContactCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def create_contact(body: ContactCreate, db: Session = Depends(get_db), user: User = MANAGE):
contact = Contact(**body.model_dump()) fields = body.model_dump()
_check_contact(fields)
fields["name"] = fields["name"].strip()
contact = Contact(**fields)
db.add(contact) db.add(contact)
db.commit() db.commit()
db.refresh(contact) db.refresh(contact)
_changed()
return contact return contact
@contacts_router.put("/{contact_id}", response_model=ContactOut) @contacts_router.put("/{contact_id}", response_model=ContactOut)
def update_contact(contact_id: int, body: ContactUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def update_contact(contact_id: int, body: ContactUpdate, db: Session = Depends(get_db), user: User = MANAGE):
contact = db.query(Contact).filter(Contact.id == contact_id).first() contact = db.query(Contact).filter(Contact.id == contact_id).first()
if not contact: if not contact:
raise HTTPException(status_code=404, detail="Contact not found") raise XeniaError("contact.not_found")
for field, value in body.model_dump(exclude_none=True).items(): # Fields sent as null are cleared (phone, e-mail...); name and type only change when given
setattr(contact, field, value) fields = body.model_dump(exclude_unset=True)
for k in ("name", "type", "is_active"):
if fields.get(k) is None:
fields.pop(k, None)
_check_contact(fields)
for field, value in fields.items():
setattr(contact, field, value.strip() if field == "name" else value)
db.commit() db.commit()
db.refresh(contact) db.refresh(contact)
_changed()
return contact return contact
@contacts_router.delete("/{contact_id}", status_code=status.HTTP_204_NO_CONTENT) @contacts_router.delete("/{contact_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_contact(contact_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)): def delete_contact(contact_id: int, db: Session = Depends(get_db), user: User = MANAGE):
contact = db.query(Contact).filter(Contact.id == contact_id).first() contact = db.query(Contact).filter(Contact.id == contact_id).first()
if not contact: if not contact:
raise HTTPException(status_code=404, detail="Contact not found") raise XeniaError("contact.not_found")
contact.is_active = False contact.is_active = False
db.commit() db.commit()
_changed()
# ── Expenses ────────────────────────────────────────────────────────────────── # ── Expenses ──────────────────────────────────────────────────────────────────
@@ -119,7 +214,7 @@ def delete_contact(contact_id: int, db: Session = Depends(get_db), user: User =
@expenses_router.get("/summary") @expenses_router.get("/summary")
def expense_summary( def expense_summary(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = MANAGE,
): ):
expenses = db.query(Expense).all() expenses = db.query(Expense).all()
total_due = sum(max(0.0, e.total_amount - e.paid_amount) for e in expenses if e.paid_amount < e.total_amount) total_due = sum(max(0.0, e.total_amount - e.paid_amount) for e in expenses if e.paid_amount < e.total_amount)
@@ -145,10 +240,18 @@ def list_expenses(
category: Optional[str] = None, category: Optional[str] = None,
contact_id: Optional[int] = None, contact_id: Optional[int] = None,
business_day_id: Optional[int] = None, business_day_id: Optional[int] = None,
date_from: Optional[date] = Query(default=None, alias="from"),
date_to: Optional[date] = Query(default=None, alias="to"),
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require_any("expenses.manage", "reports.view")),
): ):
expenses = db.query(Expense).order_by(Expense.created_at.desc()).all() """Newest first. `from` / `to` are venue dates (inclusive) of the day each was entered."""
q = db.query(Expense)
if date_from:
q = q.filter(Expense.created_at >= venue_day_window(date_from)[0])
if date_to:
q = q.filter(Expense.created_at < venue_day_window(date_to)[1])
expenses = q.order_by(Expense.created_at.desc()).all()
result = [_expense_out(e) for e in expenses] result = [_expense_out(e) for e in expenses]
if expense_status: if expense_status:
result = [e for e in result if e["status"] == expense_status] result = [e for e in result if e["status"] == expense_status]
@@ -162,33 +265,54 @@ def list_expenses(
@expenses_router.post("/", response_model=ExpenseOut, status_code=status.HTTP_201_CREATED) @expenses_router.post("/", response_model=ExpenseOut, status_code=status.HTTP_201_CREATED)
def create_expense(body: ExpenseCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def create_expense(body: ExpenseCreate, db: Session = Depends(get_db), user: User = MANAGE):
expense = Expense(**body.model_dump(), created_by_id=user.id) fields = body.model_dump()
lines = _take_lines(fields)
if fields.get("total_amount") is None:
raise XeniaError("validation.positive", field="total_amount")
_check_expense(db, fields)
fields["description"] = fields["description"].strip()
expense = Expense(**fields, created_by_id=user.id)
_set_lines(expense, lines)
db.add(expense) db.add(expense)
db.commit() db.commit()
db.refresh(expense) db.refresh(expense)
_changed()
return _expense_out(expense) return _expense_out(expense)
@expenses_router.put("/{expense_id}", response_model=ExpenseOut) @expenses_router.put("/{expense_id}", response_model=ExpenseOut)
def update_expense(expense_id: int, body: ExpenseUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def update_expense(expense_id: int, body: ExpenseUpdate, db: Session = Depends(get_db), user: User = MANAGE):
expense = db.query(Expense).filter(Expense.id == expense_id).first() expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense: if not expense:
raise HTTPException(status_code=404, detail="Expense not found") raise XeniaError("expense.not_found")
for field, value in body.model_dump(exclude_none=True).items(): # Fields sent as null are cleared (supplier, due date, notes); the rest only change when given
setattr(expense, field, value) fields = body.model_dump(exclude_unset=True)
if fields.get("lines") is None:
fields.pop("lines", None)
lines = _take_lines(fields)
for k in ("description", "category", "total_amount"):
if fields.get(k) is None:
fields.pop(k, None)
_check_expense(db, fields, paid=expense.paid_amount)
for field, value in fields.items():
setattr(expense, field, value.strip() if field == "description" else value)
_set_lines(expense, lines)
db.commit() db.commit()
db.refresh(expense) db.refresh(expense)
_changed()
return _expense_out(expense) return _expense_out(expense)
@expenses_router.delete("/{expense_id}", status_code=status.HTTP_204_NO_CONTENT) @expenses_router.delete("/{expense_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_expense(expense_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)): def delete_expense(expense_id: int, db: Session = Depends(get_db), user: User = MANAGE):
expense = db.query(Expense).filter(Expense.id == expense_id).first() expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense: if not expense:
raise HTTPException(status_code=404, detail="Expense not found") raise XeniaError("expense.not_found")
db.delete(expense) db.delete(expense)
db.commit() db.commit()
expense_docs.remove_all(expense_id)
_changed()
@expenses_router.post("/{expense_id}/pay", response_model=ExpenseOut) @expenses_router.post("/{expense_id}/pay", response_model=ExpenseOut)
@@ -196,13 +320,16 @@ def record_payment(
expense_id: int, expense_id: int,
body: ExpensePaymentCreate, body: ExpensePaymentCreate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = MANAGE,
): ):
expense = db.query(Expense).filter(Expense.id == expense_id).first() expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense: if not expense:
raise HTTPException(status_code=404, detail="Expense not found") raise XeniaError("expense.not_found")
if body.amount <= 0: if body.amount <= 0:
raise HTTPException(status_code=400, detail="Payment amount must be positive") raise XeniaError("validation.positive", field='amount')
due = round(max(0.0, expense.total_amount - expense.paid_amount), 2)
if body.amount > due + 0.005:
raise XeniaError("expense.over_due", due=f"{due:.2f}")
payment = ExpensePayment( payment = ExpensePayment(
expense_id=expense_id, expense_id=expense_id,
amount=body.amount, amount=body.amount,
@@ -216,4 +343,51 @@ def record_payment(
expense.paid_amount = round(sum(p.amount for p in all_payments), 2) expense.paid_amount = round(sum(p.amount for p in all_payments), 2)
db.commit() db.commit()
db.refresh(expense) db.refresh(expense)
_changed()
return _expense_out(expense)
# ── Documents: the invoice / receipt kept with an expense (2026-11-20) ────────────
def _expense(db: Session, expense_id: int) -> Expense:
expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense:
raise XeniaError("expense.not_found")
return expense
@expenses_router.post("/{expense_id}/documents", response_model=ExpenseOut, status_code=status.HTTP_201_CREATED)
def upload_document(expense_id: int, file: UploadFile = File(...), db: Session = Depends(get_db), user: User = MANAGE):
"""A PDF or a photo (JPG, PNG, WebP, HEIC), at most 15 MB."""
expense = _expense(db, expense_id)
stored, content_type, size = expense_docs.save(expense_id, file)
expense.documents.append(ExpenseDocument(filename=(file.filename or "document")[:200], stored_name=stored,
content_type=content_type, size=size, uploaded_by_id=user.id))
db.commit()
db.refresh(expense)
_changed()
return _expense_out(expense)
@expenses_router.get("/{expense_id}/documents/{doc_id}")
def get_document(expense_id: int, doc_id: int, db: Session = Depends(get_db),
user: User = Depends(require_any("expenses.manage", "reports.view"))):
doc = db.query(ExpenseDocument).filter(ExpenseDocument.id == doc_id, ExpenseDocument.expense_id == expense_id).first()
path = expense_docs.path(doc) if doc else None
if not path:
raise XeniaError("expense.document_not_found")
return FileResponse(path, media_type=doc.content_type, filename=doc.filename, content_disposition_type="inline")
@expenses_router.delete("/{expense_id}/documents/{doc_id}", response_model=ExpenseOut)
def delete_document(expense_id: int, doc_id: int, db: Session = Depends(get_db), user: User = MANAGE):
expense = _expense(db, expense_id)
doc = next((d for d in expense.documents if d.id == doc_id), None)
if not doc:
raise XeniaError("expense.document_not_found")
expense_docs.remove(doc)
expense.documents.remove(doc)
db.commit()
db.refresh(expense)
_changed()
return _expense_out(expense) return _expense_out(expense)
+7 -9
View File
@@ -1,4 +1,4 @@
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import List from typing import List
@@ -8,6 +8,7 @@ from schemas.flag import FlagDefCreate, FlagDefUpdate, FlagDefOut, FlagAssignmen
from routers.deps import get_current_user, require_manager from routers.deps import get_current_user, require_manager
from models.user import User from models.user import User
from services.ws_bus import broadcast_sync from services.ws_bus import broadcast_sync
from core.errors import XeniaError
router = APIRouter() router = APIRouter()
@@ -48,7 +49,7 @@ def update_flag_def(
): ):
flag = db.query(TableFlagDef).filter(TableFlagDef.id == flag_id).first() flag = db.query(TableFlagDef).filter(TableFlagDef.id == flag_id).first()
if not flag: if not flag:
raise HTTPException(status_code=404, detail="Flag not found") raise XeniaError("flag.not_found")
for k, v in body.model_dump(exclude_unset=True).items(): for k, v in body.model_dump(exclude_unset=True).items():
setattr(flag, k, v) setattr(flag, k, v)
db.commit() db.commit()
@@ -64,7 +65,7 @@ def toggle_flag_active(
): ):
flag = db.query(TableFlagDef).filter(TableFlagDef.id == flag_id).first() flag = db.query(TableFlagDef).filter(TableFlagDef.id == flag_id).first()
if not flag: if not flag:
raise HTTPException(status_code=404, detail="Flag not found") raise XeniaError("flag.not_found")
flag.is_active = not flag.is_active flag.is_active = not flag.is_active
db.commit() db.commit()
db.refresh(flag) db.refresh(flag)
@@ -79,13 +80,10 @@ def delete_flag_def(
): ):
flag = db.query(TableFlagDef).filter(TableFlagDef.id == flag_id).first() flag = db.query(TableFlagDef).filter(TableFlagDef.id == flag_id).first()
if not flag: if not flag:
raise HTTPException(status_code=404, detail="Flag not found") raise XeniaError("flag.not_found")
in_use = db.query(TableFlagAssignment).filter(TableFlagAssignment.flag_id == flag_id).count() in_use = db.query(TableFlagAssignment).filter(TableFlagAssignment.flag_id == flag_id).count()
if in_use: if in_use:
raise HTTPException( raise XeniaError("flag.in_use", count=in_use)
status_code=status.HTTP_409_CONFLICT,
detail=f"Η σήμανση χρησιμοποιείται σε {in_use} τραπέζι{'α' if in_use != 1 else ''}. Αφαιρέστε την πρώτα.",
)
db.delete(flag) db.delete(flag)
db.commit() db.commit()
@@ -129,7 +127,7 @@ def set_table_flags(
TableFlagDef.is_active == True, TableFlagDef.is_active == True,
).count() ).count()
if valid != len(body.flag_ids): if valid != len(body.flag_ids):
raise HTTPException(status_code=400, detail="One or more flag IDs are invalid") raise XeniaError("flag.invalid_ids")
# Delete existing assignments for this table # Delete existing assignments for this table
db.query(TableFlagAssignment).filter( db.query(TableFlagAssignment).filter(
+247
View File
@@ -0,0 +1,247 @@
"""Floor plans (plan step 6.8, owner decisions D-31; models/floor_plan.py).
Setting them up (catalog.tables.manage), in Management → Tables → Floor plans:
GET /api/floor-plans every plan with its items, and every active table with its place
POST /api/floor-plans a new plan {name, group_id, width, height, …}
PUT /api/floor-plans/{id} its settings: name, zone, size, outline, grid, background
PUT /api/floor-plans/{id}/layout where everything stands: {tables: [...], items: [...]}
(the tables listed are placed on it; the ones it had and
that aren't listed leave it)
DELETE /api/floor-plans/{id} its tables stay, off any plan
Every change sends `floor_plans.changed`.
The map in the apps (any signed-in person; the phones see their zones' tables only):
GET /api/floor-plans/live the plans they can see, and their tables with each one's
state now (services/floor_live.py)
"""
from __future__ import annotations
import math
from typing import List, Literal, Optional
from fastapi import APIRouter, Depends, status
from pydantic import BaseModel, Field, field_validator, model_validator
from sqlalchemy.orm import Session, selectinload
from core.access.deps import require
from core.errors import XeniaError
from database import get_db
from models.floor_plan import FloorItem, FloorPlan
from models.table import Table, TableGroup
from routers.deps import get_current_user
router = APIRouter()
MANAGE = "catalog.tables.manage"
# ── bodies ────────────────────────────────────────────────────────────────────
class PlanBody(BaseModel):
name: str = Field(min_length=1, max_length=60)
group_id: Optional[int] = None
width: int = Field(1200, ge=200, le=6000)
height: int = Field(800, ge=200, le=6000)
outline: Optional[List[List[float]]] = None
grid_on: bool = False
grid_size: int = Field(40, ge=10, le=400)
media_id: Optional[int] = None
background_opacity: float = Field(0.6, ge=0.0, le=1.0)
sort_order: Optional[int] = None
@field_validator("name")
@classmethod
def _name(cls, v):
v = v.strip()
if not v:
raise ValueError("empty")
return v
@model_validator(mode="after")
def _outline(self):
o = self.outline
if o is not None:
if len(o) == 0:
self.outline = None
elif len(o) < 3 or len(o) > 100 or any(len(p) != 2 for p in o):
raise XeniaError("floor_plan.bad_outline")
elif any(not (0 <= x <= self.width and 0 <= y <= self.height) for x, y in o):
raise XeniaError("floor_plan.bad_outline")
return self
class PlacedTable(BaseModel):
id: int
x: float
y: float
width: float = Field(gt=0, le=2000)
height: float = Field(gt=0, le=2000)
rotation: float = 0.0
shape: Literal["round", "square", "long"] = "square"
seats: Optional[int] = Field(None, ge=0, le=99)
class PlacedItem(BaseModel):
kind: Literal["wall", "bar", "label", "area"]
x: float
y: float
width: float = Field(gt=0, le=6000)
height: float = Field(gt=0, le=6000)
rotation: float = 0.0
text: Optional[str] = Field(None, max_length=60)
color: Optional[str] = Field(None, pattern=r"^#[0-9a-fA-F]{6}$") # an area's colour (2026-11-20)
class LayoutBody(BaseModel):
tables: List[PlacedTable] = Field(default_factory=list, max_length=500)
items: List[PlacedItem] = Field(default_factory=list, max_length=500)
# ── out ───────────────────────────────────────────────────────────────────────
def _rot(v) -> float:
return round(((v or 0.0) % 360 + 360) % 360, 2)
def plan_out(p: FloorPlan) -> dict:
from services import media as media_store
return {
"id": p.id, "name": p.name, "group_id": p.group_id, "sort_order": p.sort_order,
"width": p.width, "height": p.height, "outline": p.outline or None,
"grid_on": bool(p.grid_on), "grid_size": p.grid_size,
"media_id": p.media_id, "background": media_store.image_of(p.media) if p.media_id else None,
"background_opacity": p.background_opacity,
"items": [{"id": i.id, "kind": i.kind, "x": i.x, "y": i.y, "width": i.width, "height": i.height,
"rotation": i.rotation, "text": i.text, "color": i.color} for i in p.items],
}
def place_out(t: Table) -> dict:
"""A table's place (or none): what the map draws, whatever its state."""
from services.table_qr import label
return {"id": t.id, "name": label(t), "number": t.number, "group_id": t.group_id, "seats": t.seat_count,
"plan_id": t.plan_id, "x": t.floor_x, "y": t.floor_y, "width": t.width, "height": t.height,
"rotation": t.rotation or 0.0, "shape": t.shape or "square"}
def _plans(db: Session):
return (db.query(FloorPlan).options(selectinload(FloorPlan.items), selectinload(FloorPlan.media))
.order_by(FloorPlan.sort_order, FloorPlan.id).all())
def _changed() -> None:
from services.ws_bus import broadcast_sync
broadcast_sync("floor_plans.changed", {})
def _plan(db: Session, plan_id: int) -> FloorPlan:
p = db.get(FloorPlan, plan_id)
if p is None:
raise XeniaError("floor_plan.not_found")
return p
def _check_refs(db: Session, body: PlanBody) -> None:
if body.group_id is not None and db.get(TableGroup, body.group_id) is None:
raise XeniaError("floor_plan.bad_zone")
if body.media_id is not None:
from models.media import Media
m = db.get(Media, body.media_id)
if m is None or m.kind != "image":
raise XeniaError("floor_plan.bad_background")
# ── set-up ────────────────────────────────────────────────────────────────────
@router.get("")
def list_plans(db: Session = Depends(get_db), user=Depends(require(MANAGE))):
tables = db.query(Table).filter(Table.is_active.is_(True)).order_by(Table.group_id, Table.number).all()
return {"plans": [plan_out(p) for p in _plans(db)], "tables": [place_out(t) for t in tables]}
@router.post("", status_code=status.HTTP_201_CREATED)
def create_plan(body: PlanBody, db: Session = Depends(get_db), user=Depends(require(MANAGE))):
_check_refs(db, body)
last = db.query(FloorPlan).order_by(FloorPlan.sort_order.desc()).first()
p = FloorPlan(**body.model_dump(exclude={"sort_order"}), sort_order=body.sort_order if body.sort_order is not None else (last.sort_order + 1 if last else 0))
db.add(p)
db.commit()
_changed()
return plan_out(p)
@router.put("/{plan_id}")
def update_plan(plan_id: int, body: PlanBody, db: Session = Depends(get_db), user=Depends(require(MANAGE))):
p = _plan(db, plan_id)
_check_refs(db, body)
for k, v in body.model_dump(exclude={"sort_order"}).items():
setattr(p, k, v)
if body.sort_order is not None:
p.sort_order = body.sort_order
# a smaller canvas: whatever stood outside comes back inside
for t in db.query(Table).filter(Table.plan_id == p.id).all():
t.floor_x = min(max(t.floor_x or 0, 0), p.width)
t.floor_y = min(max(t.floor_y or 0, 0), p.height)
for i in p.items:
i.x, i.y = min(max(i.x, 0), p.width), min(max(i.y, 0), p.height)
db.commit()
_changed()
return plan_out(p)
@router.put("/{plan_id}/layout")
def save_layout(plan_id: int, body: LayoutBody, db: Session = Depends(get_db), user=Depends(require(MANAGE))):
p = _plan(db, plan_id)
ids = [t.id for t in body.tables]
if len(set(ids)) != len(ids):
raise XeniaError("floor_plan.bad_layout")
found = {t.id: t for t in db.query(Table).filter(Table.id.in_(ids)).all()} if ids else {}
if len(found) != len(ids):
raise XeniaError("table.not_found")
from sqlalchemy import true
for t in db.query(Table).filter(Table.plan_id == p.id, ~Table.id.in_(ids) if ids else true()).all():
t.plan_id = None # taken off this plan
for pt in body.tables:
t = found[pt.id]
t.plan_id = p.id
t.floor_x, t.floor_y = _inside(pt.x, p.width), _inside(pt.y, p.height)
t.width, t.height = round(pt.width, 1), round(pt.height, 1)
t.rotation, t.shape = _rot(pt.rotation), pt.shape
if pt.seats is not None:
t.seat_count = pt.seats or None
p.items.clear()
db.flush()
for it in body.items:
p.items.append(FloorItem(kind=it.kind, x=_inside(it.x, p.width), y=_inside(it.y, p.height), width=round(it.width, 1),
height=round(it.height, 1), rotation=_rot(it.rotation), text=(it.text or "").strip() or None,
color=it.color if it.kind == "area" else None))
db.commit()
db.refresh(p)
_changed()
from services.ws_bus import broadcast_sync
broadcast_sync("table_list_changed", {}) # the lists show seats too
return plan_out(p)
def _inside(v: float, most: float) -> float:
if not math.isfinite(v):
raise XeniaError("floor_plan.bad_layout")
return round(min(max(v, 0.0), float(most)), 1)
@router.delete("/{plan_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_plan(plan_id: int, db: Session = Depends(get_db), user=Depends(require(MANAGE))):
p = _plan(db, plan_id)
for t in db.query(Table).filter(Table.plan_id == p.id).all():
t.plan_id = None
db.delete(p)
db.commit()
_changed()
# ── the map in the apps ───────────────────────────────────────────────────────
@router.get("/live")
def live(db: Session = Depends(get_db), user=Depends(get_current_user)):
from services.floor_live import live_tables, visible_plans
tables = live_tables(db, user)
return {"plans": [plan_out(p) for p in visible_plans(db, user, _plans(db), tables)], "tables": tables}
+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)
+15 -15
View File
@@ -40,7 +40,7 @@ from core.access.queries import holders_filter
from core.errors import XeniaError from core.errors import XeniaError
from core.timeutil import utcnow from core.timeutil import utcnow
import json import json
from fastapi import APIRouter, Depends, HTTPException, Query, Request from fastapi import APIRouter, Depends, Query, Request
from datetime import datetime, timezone from datetime import datetime, timezone
from sqlalchemy.orm import Session, joinedload from sqlalchemy.orm import Session, joinedload
from pydantic import BaseModel from pydantic import BaseModel
@@ -367,11 +367,11 @@ def update_order_kds_status(
kitchen screen with a prep zone only that zone's items change (3.2c), and the order's kitchen screen with a prep zone only that zone's items change (3.2c), and the order's
status then follows all its items.""" status then follows all its items."""
if body.status not in VALID_KDS_STATUSES: if body.status not in VALID_KDS_STATUSES:
raise HTTPException(status_code=400, detail=f"Invalid status '{body.status}'") raise XeniaError("validation.choice", field='status', value=body.status)
order = db.query(Order).filter(Order.id == order_id).first() order = db.query(Order).filter(Order.id == order_id).first()
if not order: if not order:
raise HTTPException(status_code=404, detail="Order not found") raise XeniaError("order.not_found", order_id=order_id)
zone_id = _device_zone_id(request, db) zone_id = _device_zone_id(request, db)
if body.status != order.kds_status and zone_id is None: if body.status != order.kds_status and zone_id is None:
@@ -410,14 +410,14 @@ def update_item_kds_status(
user: User = Depends(get_current_user), user: User = Depends(get_current_user),
): ):
if body.status not in VALID_KDS_STATUSES: if body.status not in VALID_KDS_STATUSES:
raise HTTPException(status_code=400, detail=f"Invalid status '{body.status}'") raise XeniaError("validation.choice", field='status', value=body.status)
item = db.query(OrderItem).filter( item = db.query(OrderItem).filter(
OrderItem.id == item_id, OrderItem.id == item_id,
OrderItem.order_id == order_id, OrderItem.order_id == order_id,
).first() ).first()
if not item: if not item:
raise HTTPException(status_code=404, detail="Item not found") raise XeniaError("order.item_not_found")
item.kds_status = body.status item.kds_status = body.status
@@ -451,11 +451,11 @@ def update_order_type(
user: User = Depends(get_current_user), user: User = Depends(get_current_user),
): ):
if body.order_type not in VALID_ORDER_TYPES: if body.order_type not in VALID_ORDER_TYPES:
raise HTTPException(status_code=400, detail=f"Invalid order_type '{body.order_type}'") raise XeniaError("validation.choice", field='order_type', value=body.order_type)
order = db.query(Order).filter(Order.id == order_id).first() order = db.query(Order).filter(Order.id == order_id).first()
if not order: if not order:
raise HTTPException(status_code=404, detail="Order not found") raise XeniaError("order.not_found", order_id=order_id)
order.order_type = body.order_type order.order_type = body.order_type
db.commit() db.commit()
@@ -477,7 +477,7 @@ def mark_items_served(
"""Mark a list of items as served (kds_status=served). Works on active and paid items.""" """Mark a list of items as served (kds_status=served). Works on active and paid items."""
order = db.query(Order).filter(Order.id == order_id).first() order = db.query(Order).filter(Order.id == order_id).first()
if not order: if not order:
raise HTTPException(status_code=404, detail="Order not found") raise XeniaError("order.not_found", order_id=order_id)
updated = [] updated = []
ids_set = set(body.item_ids) ids_set = set(body.item_ids)
@@ -507,7 +507,7 @@ def mark_all_items_served(
"""Mark all non-pending items in an order as served.""" """Mark all non-pending items in an order as served."""
order = db.query(Order).filter(Order.id == order_id).first() order = db.query(Order).filter(Order.id == order_id).first()
if not order: if not order:
raise HTTPException(status_code=404, detail="Order not found") raise XeniaError("order.not_found", order_id=order_id)
updated = [] updated = []
for item in order.items: for item in order.items:
@@ -591,7 +591,7 @@ def decline_order(
"""Mark all active items on an order as declined.""" """Mark all active items on an order as declined."""
order = db.query(Order).filter(Order.id == order_id).first() order = db.query(Order).filter(Order.id == order_id).first()
if not order: if not order:
raise HTTPException(status_code=404, detail="Order not found") raise XeniaError("order.not_found", order_id=order_id)
zone_id = _device_zone_id(request, db) # a zone screen declines only its own items (3.2c) zone_id = _device_zone_id(request, db) # a zone screen declines only its own items (3.2c)
for item in order.items: for item in order.items:
@@ -628,7 +628,7 @@ def decline_item(
OrderItem.order_id == order_id, OrderItem.order_id == order_id,
).first() ).first()
if not item: if not item:
raise HTTPException(status_code=404, detail="Item not found") raise XeniaError("order.item_not_found")
item.kds_status = "declined" item.kds_status = "declined"
item.decline_note = body.decline_note item.decline_note = body.decline_note
@@ -717,7 +717,7 @@ def kds_notify_order_complete(
joinedload(Order.waiters), joinedload(Order.waiters),
).filter(Order.id == order_id).first() ).filter(Order.id == order_id).first()
if not order: if not order:
raise HTTPException(status_code=404, detail="Order not found") raise XeniaError("order.not_found", order_id=order_id)
waiter_ids = _waiter_ids_for_order(order) waiter_ids = _waiter_ids_for_order(order)
if not waiter_ids: if not waiter_ids:
@@ -758,7 +758,7 @@ def kds_notify_items_ready(
joinedload(Order.waiters), joinedload(Order.waiters),
).filter(Order.id == order_id).first() ).filter(Order.id == order_id).first()
if not order: if not order:
raise HTTPException(status_code=404, detail="Order not found") raise XeniaError("order.not_found", order_id=order_id)
waiter_ids = _waiter_ids_for_order(order) waiter_ids = _waiter_ids_for_order(order)
if not waiter_ids: if not waiter_ids:
@@ -793,7 +793,7 @@ def kds_call_waiter_order(
joinedload(Order.waiters), joinedload(Order.waiters),
).filter(Order.id == order_id).first() ).filter(Order.id == order_id).first()
if not order: if not order:
raise HTTPException(status_code=404, detail="Order not found") raise XeniaError("order.not_found", order_id=order_id)
waiter_ids = _waiter_ids_for_order(order) waiter_ids = _waiter_ids_for_order(order)
if not waiter_ids: if not waiter_ids:
@@ -824,7 +824,7 @@ def kds_call_waiter_general(
): ):
"""Call one or more on-shift waiters to the prep zone.""" """Call one or more on-shift waiters to the prep zone."""
if not body.waiter_ids: if not body.waiter_ids:
raise HTTPException(status_code=400, detail="waiter_ids must not be empty") raise XeniaError("validation.missing", field='waiter_ids')
zone = _sender(request, db, body.kds_zone) zone = _sender(request, db, body.kds_zone)
msg_body = f"Κλήση από {zone}" msg_body = f"Κλήση από {zone}"
+108 -8
View File
@@ -6,8 +6,9 @@
GET /api/media/{id} one item, with what uses it GET /api/media/{id} one item, with what uses it
PATCH /api/media/{id} rename PATCH /api/media/{id} rename
DELETE /api/media/{id} refused with `media.in_use` while something uses it DELETE /api/media/{id} refused with `media.in_use` while something uses it
GET /api/media/file/{sha}/{variant} the bytes: thumb | card | full (images, WebP) GET /api/media/file/{sha}/{variant} the bytes: thumb | card | full (WebP: a picture,
| original. Public (LAN, like the customer display's or a video's still frame) | original | play (a video's
version every screen plays, step 5.4e). Public (LAN, like the customer display's
images), cached for a year: a URL never changes meaning. images), cached for a year: a URL never changes meaning.
Whoever manages the menu, the customer display, signage or the menu tablets manages the Whoever manages the menu, the customer display, signage or the menu tablets manages the
@@ -28,8 +29,9 @@ from core.access.deps import public, require_any
from core.errors import XeniaError from core.errors import XeniaError
from database import get_db from database import get_db
from datetime import datetime from datetime import datetime
from models.media import Media from models.media import Media, MediaFolder
from services import media as store from services import media as store
from services import video
router = APIRouter() router = APIRouter()
MANAGE = ("catalog.menu.manage", "customer_display.manage", "signage.manage", "menu_tablet.manage") MANAGE = ("catalog.menu.manage", "customer_display.manage", "signage.manage", "menu_tablet.manage")
@@ -53,6 +55,9 @@ class MediaOut(BaseModel):
uploaded_by_name: Optional[str] = None uploaded_by_name: Optional[str] = None
created_at: datetime created_at: datetime
builtin: bool = False 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) urls: dict = Field(default_factory=dict)
@@ -71,17 +76,53 @@ class MediaPage(BaseModel):
class RenameBody(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") @field_validator("name")
@classmethod @classmethod
def _strip(cls, v): def _strip(cls, v):
if v is None:
return v
v = v.strip() v = v.strip()
if not v: if not v:
raise ValueError("empty") raise ValueError("empty")
return v 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): def _out(item: Media, cls=MediaOut, **extra):
return cls.model_validate(item).model_copy(update={"urls": store.urls(item), **extra}) return cls.model_validate(item).model_copy(update={"urls": store.urls(item), **extra})
@@ -101,9 +142,14 @@ def _name_from(filename: str | None) -> str:
@router.get("", response_model=MediaPage) @router.get("", response_model=MediaPage)
def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str] = None, 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))): 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) 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: if kind:
query = query.filter(Media.kind == kind) query = query.filter(Media.kind == kind)
if q and q.strip(): if q and q.strip():
@@ -118,11 +164,13 @@ def list_media(kind: Optional[Literal["image", "video"]] = None, q: Optional[str
@router.post("", response_model=UploadOut, status_code=201) @router.post("", response_model=UploadOut, status_code=201)
def upload_media(response: Response, file: UploadFile = File(...), name: Optional[str] = Form(None), 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))): 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. # The type comes from the bytes; the browser's content type only picks the size limit.
declared = (file.content_type or "").lower() declared = (file.content_type or "").lower()
limit = store.VIDEO_MAX_BYTES if declared.startswith("video/") else store.IMAGE_MAX_BYTES limit = store.VIDEO_MAX_BYTES if declared.startswith("video/") else store.IMAGE_MAX_BYTES
tmp, sha, size = store.receive(file.file, limit) tmp, sha, size = store.receive(file.file, limit)
folder = _folder(db, folder_id)
existing = db.query(Media).filter(Media.sha256 == sha).first() existing = db.query(Media).filter(Media.sha256 == sha).first()
if existing is not None: if existing is not None:
store._remove(tmp) store._remove(tmp)
@@ -130,7 +178,10 @@ def upload_media(response: Response, file: UploadFile = File(...), name: Optiona
return _out(existing, UploadOut, existing=True) return _out(existing, UploadOut, existing=True)
info = store.ingest(tmp, sha, size) info = store.ingest(tmp, sha, size)
item = Media(name=(name or "").strip()[:120] or _name_from(file.filename), 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: try:
db.add(item) db.add(item)
db.commit() db.commit()
@@ -138,6 +189,8 @@ def upload_media(response: Response, file: UploadFile = File(...), name: Optiona
store.delete_files(sha) store.delete_files(sha)
raise raise
db.refresh(item) db.refresh(item)
if item.processing:
video.wake()
return _out(item, UploadOut) return _out(item, UploadOut)
@@ -149,10 +202,10 @@ def media_file(sha: str, variant: str, request: Request, db: Session = Depends(g
path = store.ensure_variant(item, variant) if item is not None else None path = store.ensure_variant(item, variant) if item is not None else None
if not path or not os.path.exists(path): if not path or not os.path.exists(path):
raise XeniaError("media.not_found", media_id=sha) raise XeniaError("media.not_found", media_id=sha)
ctype = item.content_type if variant == "original" else "image/webp" ctype = item.content_type if variant == "original" else "video/mp4" if variant == "play" else "image/webp"
headers = {"Cache-Control": CACHE, "Accept-Ranges": "bytes"} headers = {"Cache-Control": CACHE, "Accept-Ranges": "bytes"}
rng = request.headers.get("range") rng = request.headers.get("range")
if rng and variant == "original": if rng and variant in ("original", "play"):
return _ranged(path, ctype, rng, headers) return _ranged(path, ctype, rng, headers)
return FileResponse(path, media_type=ctype, headers=headers) return FileResponse(path, media_type=ctype, headers=headers)
@@ -187,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)}) **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) @router.get("/{media_id}", response_model=MediaDetail)
def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))): def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
item = _get(db, media_id) item = _get(db, media_id)
@@ -196,9 +293,12 @@ def get_media(media_id: int, db: Session = Depends(get_db), user=Depends(require
@router.patch("/{media_id}", response_model=MediaOut) @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))): def rename_media(media_id: int, body: RenameBody, db: Session = Depends(get_db), user=Depends(require_any(*MANAGE))):
item = _get(db, media_id) item = _get(db, media_id)
if "name" in body.model_fields_set and body.name is not None:
if item.builtin: if item.builtin:
raise XeniaError("media.builtin") raise XeniaError("media.builtin")
item.name = body.name 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.commit()
db.refresh(item) db.refresh(item)
return _out(item) return _out(item)
+406
View File
@@ -0,0 +1,406 @@
"""The menu tablet (plan step 5.7a): the venue's menu on a tablet, for staff ("how much is the
steak?") and for guests (a menu at the entrance, later a digital menu at the table). Just the
products and their categories: no ordering, no tables, no sign-in.
GET /api/menu-tablet/menu (a paired menu tablet) the categories in the catalogue's order
(sub-categories after their parent), each with its products in its
own order (a product listed in several categories shows in each),
the products once with name, description, tags, photo, the price
of the tablet's sales point and whether it is available; the
tablet's settings (device config) and the venue's name.
POST /api/menu-tablet/call (a tablet set at a table, 5.7b) call a waiter: a message to the
table's waiters (its order's, else the zone's), once a minute at most.
Ordering at the table (6.6, D-30, services/tablet_orders.py), a tablet at a table with
"Guests can order" on:
POST /quote {lines} the cart priced by the server (the counter's lines by id)
POST /order {lines, note} sent to the kitchen, or waiting for a waiter (the rules)
GET /order/{id} what happened to one of this tablet's orders
GET /bill · POST /bill the table's bill so far · ask for the bill (a message)
Staff (phones): GET /requests?table_id=, POST /requests/{id}/accept | decline (waiting orders).
The venue's rules: GET / PUT /ordering (menu_tablet.manage).
How it looks is the tablet's device config (modules/menu_tablet/manifest.py): view, photos,
descriptions, grouping, whose prices, sold-out style, search, one category or all, languages,
idle reset, light / dark. Any menu change sends `menu_tablet.changed` to every tablet (main.py).
"""
from __future__ import annotations
import json
import threading
import time
from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
from typing import List, Optional
from sqlalchemy.orm import Session
from core import allergens, menu_languages, sales_points
from core.access.deps import require
from services import tablet_orders
from core.access.deps import require_device
from core.errors import XeniaError
from database import get_db
router = APIRouter()
CALL_EVERY_S = 60
_calls: dict[int, float] = {} # tablet id → its last call (monotonic)
_lock = threading.Lock()
def _config(dev) -> dict:
from core.modules.device_config import effective, for_app
return effective(for_app("menu_tablet"), dev.config)
def tablets(db) -> list[int]:
from models.device import Device
return [i for (i,) in db.query(Device.id).filter(Device.app_key == "menu_tablet", Device.revoked_at.is_(None))]
def menu_changed(db) -> None:
"""Products, categories or prices changed (main.py): every tablet reads its menu again."""
from services.ws_bus import broadcast_sync
ids = tablets(db)
if ids:
broadcast_sync("menu_tablet.changed", {}, device_ids=ids)
def _tags(p) -> list[str]:
raw = getattr(p, "tags", None)
if isinstance(raw, str):
try:
raw = json.loads(raw)
except ValueError:
raw = []
return [t for t in (raw or []) if isinstance(t, str)]
@router.get("/menu")
def menu(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
from models.product import Category, Product, ProductCategory
from models.settings import PosSettings
from services import media as media_store
from services.pos_cart import unit_prices
cfg = _config(dev)
cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
by_parent: dict = {}
for c in cats:
by_parent.setdefault(c.parent_id, []).append(c)
ordered = [] # parents, each followed by its sub-categories
def walk(parent_id, depth):
for c in by_parent.get(parent_id, []):
ordered.append((c, depth))
walk(c.id, depth + 1)
walk(None, 0)
if cfg.get("category"):
root = next(((c, d) for c, d in ordered if c.id == cfg["category"]), None)
keep = set()
if root:
stack = [root[0].id]
while stack:
cid = stack.pop()
keep.add(cid)
stack.extend(x.id for x in by_parent.get(cid, []))
ordered = [(c, d) for c, d in ordered if c.id in keep]
point = None if cfg["sales_point"] == "none" else cfg["sales_point"]
products = db.query(Product).filter(Product.lifecycle_status == "active", Product.system_key.is_(None)).all()
if point:
products = [p for p in products if sales_points.is_sold_at(p, point)]
if cfg["sold_out"] == "hide":
products = [p for p in products if p.is_available]
by_id = {p.id: p for p in products}
members = db.query(ProductCategory).order_by(ProductCategory.sort_order).all()
in_cat: dict = {}
for m in members:
if m.product_id in by_id:
in_cat.setdefault(m.category_id, []).append(m.product_id)
out_cats, used = [], set()
for c, depth in ordered:
ids = in_cat.get(c.id, [])
has_sub = any(in_cat.get(x.id) for x in by_parent.get(c.id, []))
if ids or has_sub:
out_cats.append({"id": c.id, "name": c.name, "names": menu_languages.texts(c.name, menu_languages.of(c), "name"),
"parent_id": c.parent_id, "depth": depth, "products": ids})
used.update(ids)
shown = [by_id[i] for i in by_id if i in used]
prices = dict(zip([p.id for p in shown], unit_prices(db, shown, point))) if point and shown else {}
name_row = db.query(PosSettings).filter(PosSettings.key == "venue.name").first()
table = _table(db, cfg)
ordering = bool(table and cfg.get("ordering"))
choices = {}
if ordering: # what a guest can choose (the counter's shape)
from routers.pos import _product_out
order_prices = dict(zip([p.id for p in shown], unit_prices(db, shown, tablet_orders.POINT))) if shown else {}
choices = {str(p.id): _product_out(p, order_prices.get(p.id, p.base_price)) for p in shown
if p.is_available and sales_points.is_sold_at(p, tablet_orders.POINT)}
return {
"venue": {"name": (name_row.value if name_row else "") or None},
"table": {"id": table.id, "name": _label(table), "can_call": bool(cfg.get("call_waiter")),
"can_order": ordering, "can_see_bill": bool(cfg.get("bill"))} if table else None,
"ordering": {**tablet_orders.rules(db, cfg), "choices": choices} if ordering else None,
"config": cfg,
"categories": out_cats,
"products": {str(p.id): {"id": p.id, "name": p.name, "description": p.description or None, "tags": _tags(p),
"allergens": allergens.of(p), **menu_languages.product_texts(p, customer=False),
"price": round(prices[p.id], 2) if p.id in prices else None, "available": bool(p.is_available),
"image": media_store.image_of(p.media)} for p in shown},
}
# ── calling a waiter from a tablet at a table (5.7b) ──────────────────────────
def _table(db, cfg):
from models.table import Table
t = db.get(Table, cfg["table"]) if cfg.get("table") else None
return t if t is not None and t.is_active else None
def _label(table) -> str:
from services.table_qr import label
return label(table)
def _waiters(db, table) -> list[int]:
"""The table's waiters: its open order's, else the waiters whose zone covers the table."""
from models.order import Order
from services.qr_orders import waiters_for
order = db.query(Order).filter(Order.table_id == table.id, Order.status.in_(("open", "partially_paid", "paid"))).first()
class _NoOrder:
waiters = []
return waiters_for(db, order or _NoOrder(), table)
@router.post("/call")
def call_waiter(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
"""A guest at the table asks for a waiter. The message reaches the table's waiters' phones."""
from core.access.queries import holders_filter
from core.i18n import t, venue_language
from models.user import User
from routers.kds import _save_and_broadcast_message
cfg = _config(dev)
table = _table(db, cfg)
if table is None or not cfg.get("call_waiter"):
raise XeniaError("menu_tablet.no_table")
now = time.monotonic()
with _lock:
last = _calls.get(dev.id)
if last is not None and now - last < CALL_EVERY_S:
raise XeniaError("menu_tablet.call_too_soon", seconds=int(CALL_EVERY_S - (now - last)) + 1)
_calls[dev.id] = now
sender = db.query(User).filter(holders_filter("core.dashboard.access")).first()
lang = venue_language()
waiters = _waiters(db, table)
_save_and_broadcast_message(db, sender.id if sender else 1, t("tablet.call_message", lang, table=_label(table)), waiters,
"table_call", t("tablet.sender", lang), table_ids=[table.id])
return {"table": {"id": table.id, "name": _label(table)}, "waiters": len(waiters), "again_in": CALL_EVERY_S}
def reset_calls() -> None:
with _lock:
_calls.clear()
# ── ordering at the table (6.6, D-30) ─────────────────────────────────────────
class LinesBody(BaseModel):
lines: List[dict] = Field(min_length=1, max_length=100)
note: Optional[str] = Field(default=None, max_length=300)
def _ordering_table(db, dev):
cfg = _config(dev)
table = _table(db, cfg)
if table is None or not cfg.get("ordering"):
raise XeniaError("menu_tablet.no_ordering")
return cfg, table
def _lines(db, body: LinesBody):
"""The guest's lines, resolved and checked by the server; never a discount or a price."""
from services import pos_cart
out = []
for n, raw in enumerate(body.lines):
raw = {k: v for k, v in (raw if isinstance(raw, dict) else {}).items() if k in ("product_id", "quantity", "quick", "options", "prefs", "removed", "notes")}
line = pos_cart.resolve_line(db, raw, n)
if not line.product.is_available or not sales_points.is_sold_at(line.product, tablet_orders.POINT):
raise XeniaError("order.product_unavailable", product_id=line.product.id)
out.append(line)
return out
@router.post("/quote")
def quote(body: LinesBody, db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
from services import pos_cart
_ordering_table(db, dev)
return pos_cart.quote(db, _lines(db, body), "here", point=tablet_orders.POINT)
@router.post("/order")
def send_order(body: LinesBody, db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
"""The guests' order: on the table's order and in the kitchen, or waiting for a waiter."""
from models.tablet_order import TabletOrder
from services import pos_cart
cfg, table = _ordering_table(db, dev)
rules = tablet_orders.rules(db, cfg)
lines = _lines(db, body)
tablet_orders.check(db, dev.id, lines, rules)
if rules["no_order"] == "refuse" and tablet_orders.open_order_of(db, table) is None:
raise XeniaError("menu_tablet.table_closed")
priced = pos_cart.quote(db, lines, "here", point=tablet_orders.POINT)
row = TabletOrder(device_id=dev.id, table_id=table.id, note=(body.note or "").strip() or None, total=priced["total"],
lines=[{**{k: v for k, v in raw.items() if k in ("product_id", "quantity", "quick", "options", "prefs", "removed", "notes")},
"name": q["name"], "quantity": q["quantity"], "total": q["total"],
"entries": [e["name"] for e in q["entries"]], "removed_names": q["removed"]}
for raw, q in zip(body.lines, priced["lines"])],
status="waiting")
db.add(row)
db.commit()
actor = tablet_orders.system_user(db)
count = sum(line.quantity for line in lines)
if rules["confirm"] == "kitchen":
try:
tablet_orders.place(db, row, table, lines, actor=actor, no_order=rules["no_order"])
except XeniaError:
db.delete(row)
db.commit()
raise
tablet_orders.tell_waiters(db, table, "tablet.order_sent", actor.id, count=count)
else:
tablet_orders.tell_waiters(db, table, "tablet.order_waiting", actor.id, count=count)
tablet_orders.announce(row)
return tablet_orders.out(db, row)
@router.get("/order/{order_id}")
def tablet_order(order_id: int, db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
from models.tablet_order import TabletOrder
row = db.get(TabletOrder, order_id)
if row is None or row.device_id != dev.id:
raise XeniaError("menu_tablet.order_not_found")
return tablet_orders.out(db, row)
@router.get("/bill")
def bill(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
"""The table's bill so far: the open order's lines (cancelled ones left out) and what's left to pay."""
cfg = _config(dev)
table = _table(db, cfg)
if table is None or not cfg.get("bill"):
raise XeniaError("menu_tablet.no_table")
order = tablet_orders.open_order_of(db, table)
if order is None:
return {"lines": [], "total": 0, "paid": 0, "due": 0}
lines = []
for i in order.items:
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 {}
lines.append({"name": i.product_name or (i.product.name if i.product else ""), "names": texts.get("names"),
"quantity": i.quantity, "total": round(unit * i.quantity, 2), "paid": i.status == "paid"})
total = round(sum(x["total"] for x in lines), 2)
paid = round(sum(x["total"] for x in lines if x["paid"]), 2)
return {"lines": lines, "total": total, "paid": paid, "due": round(total - paid, 2)}
_bills: dict[int, float] = {}
@router.post("/bill")
def ask_for_bill(db: Session = Depends(get_db), dev=Depends(require_device("menu_tablet"))):
"""The guests ask for the bill: a message to the table's waiters, once a minute at most."""
cfg = _config(dev)
table = _table(db, cfg)
if table is None or not cfg.get("bill"):
raise XeniaError("menu_tablet.no_table")
now = time.monotonic()
with _lock:
last = _bills.get(dev.id)
if last is not None and now - last < CALL_EVERY_S:
raise XeniaError("menu_tablet.call_too_soon", seconds=int(CALL_EVERY_S - (now - last)) + 1)
_bills[dev.id] = now
actor = tablet_orders.system_user(db)
from core.i18n import t, venue_language
from routers.kds import _save_and_broadcast_message
lang = venue_language()
_save_and_broadcast_message(db, actor.id, t("tablet.bill_message", lang, table=_label(table)), tablet_orders.waiters(db, table),
"table_call", t("tablet.sender", lang), table_ids=[table.id])
return {"again_in": CALL_EVERY_S}
# ── staff: the orders that wait for a waiter ──────────────────────────────────
class DeclineBody(BaseModel):
reason: Optional[str] = Field(default=None, max_length=200)
@router.get("/requests")
def waiting(table_id: Optional[int] = None, db: Session = Depends(get_db), user=Depends(require("ordering.orders.open"))):
from models.tablet_order import TabletOrder
tablet_orders.expire_waiting(db)
q = db.query(TabletOrder).filter(TabletOrder.status == "waiting")
if table_id is not None:
q = q.filter(TabletOrder.table_id == table_id)
return [tablet_orders.out(db, r) for r in q.order_by(TabletOrder.created_at).all()]
def _waiting(db, request_id: int):
from models.tablet_order import TabletOrder
row = db.get(TabletOrder, request_id)
if row is None:
raise XeniaError("menu_tablet.order_not_found")
if row.status != "waiting":
raise XeniaError("menu_tablet.order_answered")
return row
@router.post("/requests/{request_id}/accept")
def accept(request_id: int, db: Session = Depends(get_db), user=Depends(require("ordering.orders.open"))):
"""A waiter confirms the guests' order: on the table's order and in the kitchen."""
from core.timeutil import utcnow
from models.device import Device
from models.table import Table
from services import pos_cart
row = _waiting(db, request_id)
table = db.get(Table, row.table_id) if row.table_id else None
if table is None or not table.is_active:
raise XeniaError("menu_tablet.no_table")
dev = db.get(Device, row.device_id) if row.device_id else None
rules = tablet_orders.rules(db, _config(dev) if dev is not None else {})
lines = [pos_cart.resolve_line(db, {k: v for k, v in raw.items() if k in ("product_id", "quantity", "quick", "options", "prefs", "removed", "notes")}, n)
for n, raw in enumerate(row.lines)]
row.decided_by_id, row.decided_at = user.id, utcnow()
# the waiter accepts on the table's behalf: opening the table is theirs (refuse only stops guests)
tablet_orders.place(db, row, table, lines, actor=user, no_order="open" if rules["no_order"] == "refuse" else rules["no_order"])
tablet_orders.announce(row)
return tablet_orders.out(db, row)
@router.post("/requests/{request_id}/decline")
def decline(request_id: int, body: DeclineBody, db: Session = Depends(get_db), user=Depends(require("ordering.orders.open"))):
from core.timeutil import utcnow
row = _waiting(db, request_id)
row.status, row.reason = "declined", (body.reason or "").strip() or None
row.decided_by_id, row.decided_at = user.id, utcnow()
db.commit()
tablet_orders.announce(row)
return tablet_orders.out(db, row)
# ── the venue's rules ────────────────────────────────────────────────────────
@router.get("/ordering")
def ordering_rules(db: Session = Depends(get_db), user=Depends(require("menu_tablet.manage"))):
return tablet_orders.venue_rules(db)
@router.put("/ordering")
def save_ordering_rules(body: tablet_orders.Rules, db: Session = Depends(get_db), user=Depends(require("menu_tablet.manage"))):
return tablet_orders.save_venue_rules(db, body)
+5 -4
View File
@@ -1,5 +1,5 @@
import json import json
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session, joinedload from sqlalchemy.orm import Session, joinedload
from typing import List from typing import List
@@ -12,6 +12,7 @@ from schemas.message import (
) )
from routers.deps import get_current_user, require_manager from routers.deps import get_current_user, require_manager
from services.ws_bus import broadcast_sync from services.ws_bus import broadcast_sync
from core.errors import XeniaError
router = APIRouter() router = APIRouter()
@@ -78,7 +79,7 @@ def update_template(
): ):
t = db.query(QuickMessageTemplate).filter(QuickMessageTemplate.id == template_id).first() t = db.query(QuickMessageTemplate).filter(QuickMessageTemplate.id == template_id).first()
if not t: if not t:
raise HTTPException(status_code=404, detail="Template not found") raise XeniaError("staff_message.template_not_found")
for k, v in body.model_dump(exclude_unset=True).items(): for k, v in body.model_dump(exclude_unset=True).items():
setattr(t, k, v) setattr(t, k, v)
db.commit() db.commit()
@@ -94,7 +95,7 @@ def delete_template(
): ):
t = db.query(QuickMessageTemplate).filter(QuickMessageTemplate.id == template_id).first() t = db.query(QuickMessageTemplate).filter(QuickMessageTemplate.id == template_id).first()
if not t: if not t:
raise HTTPException(status_code=404, detail="Template not found") raise XeniaError("staff_message.template_not_found")
t.is_active = False t.is_active = False
db.commit() db.commit()
@@ -194,7 +195,7 @@ def ack_message(
): ):
msg = db.query(StaffMessage).filter(StaffMessage.id == message_id).first() msg = db.query(StaffMessage).filter(StaffMessage.id == message_id).first()
if not msg: if not msg:
raise HTTPException(status_code=404, detail="Message not found") raise XeniaError("staff_message.not_found")
existing = db.query(StaffMessageAck).filter( existing = db.query(StaffMessageAck).filter(
StaffMessageAck.message_id == message_id, StaffMessageAck.message_id == message_id,
StaffMessageAck.waiter_id == user.id, StaffMessageAck.waiter_id == user.id,
+43 -19
View File
@@ -1,6 +1,6 @@
from core.timeutil import utcnow from core.timeutil import utcnow
from datetime import datetime, timezone from datetime import datetime, timezone
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import List from typing import List
@@ -8,10 +8,25 @@ from database import get_db
from models.notes import SiteNote, SiteTodo from models.notes import SiteNote, SiteTodo
from models.user import User from models.user import User
from schemas.notes import NoteCreate, NoteUpdate, NoteOut, TodoCreate, TodoUpdate, TodoOut from schemas.notes import NoteCreate, NoteUpdate, NoteOut, TodoCreate, TodoUpdate, TodoOut
from routers.deps import require_manager from core.access.deps import require
from core.errors import XeniaError
from services.ws_bus import broadcast_sync
router = APIRouter() router = APIRouter()
USE = Depends(require("notes.use"))
PRIORITIES = ("normal", "high")
def _changed():
broadcast_sync("notes.changed", {})
def _text(body: str | None) -> str:
if not (body or "").strip():
raise XeniaError("validation.missing", field="body")
return body.strip()
@@ -54,7 +69,7 @@ def _todo_out(t: SiteTodo) -> dict:
# ── Notes ───────────────────────────────────────────────────────────────────── # ── Notes ─────────────────────────────────────────────────────────────────────
@router.get("/", response_model=List[NoteOut]) @router.get("/", response_model=List[NoteOut])
def list_notes(db: Session = Depends(get_db), user: User = Depends(require_manager)): def list_notes(db: Session = Depends(get_db), user: User = USE):
notes = db.query(SiteNote).order_by( notes = db.query(SiteNote).order_by(
SiteNote.is_pinned.desc(), SiteNote.updated_at.desc() SiteNote.is_pinned.desc(), SiteNote.updated_at.desc()
).all() ).all()
@@ -62,42 +77,44 @@ def list_notes(db: Session = Depends(get_db), user: User = Depends(require_manag
@router.post("/", response_model=NoteOut, status_code=status.HTTP_201_CREATED) @router.post("/", response_model=NoteOut, status_code=status.HTTP_201_CREATED)
def create_note(body: NoteCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def create_note(body: NoteCreate, db: Session = Depends(get_db), user: User = USE):
note = SiteNote(body=body.body, is_pinned=body.is_pinned, created_by_id=user.id) note = SiteNote(body=_text(body.body), is_pinned=body.is_pinned, created_by_id=user.id)
db.add(note) db.add(note)
db.commit() db.commit()
db.refresh(note) db.refresh(note)
_changed()
return _note_out(note) return _note_out(note)
@router.put("/{note_id}", response_model=NoteOut) @router.put("/{note_id}", response_model=NoteOut)
def update_note(note_id: int, body: NoteUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def update_note(note_id: int, body: NoteUpdate, db: Session = Depends(get_db), user: User = USE):
note = db.query(SiteNote).filter(SiteNote.id == note_id).first() note = db.query(SiteNote).filter(SiteNote.id == note_id).first()
if not note: if not note:
raise HTTPException(status_code=404, detail="Note not found") raise XeniaError("note.not_found")
if body.body is not None: if body.body is not None:
note.body = body.body note.body = _text(body.body)
if body.is_pinned is not None: if body.is_pinned is not None:
note.is_pinned = body.is_pinned note.is_pinned = body.is_pinned
note.updated_at = utcnow()
db.commit() db.commit()
db.refresh(note) db.refresh(note)
_changed()
return _note_out(note) return _note_out(note)
@router.delete("/{note_id}", status_code=status.HTTP_204_NO_CONTENT) @router.delete("/{note_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_note(note_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)): def delete_note(note_id: int, db: Session = Depends(get_db), user: User = USE):
note = db.query(SiteNote).filter(SiteNote.id == note_id).first() note = db.query(SiteNote).filter(SiteNote.id == note_id).first()
if not note: if not note:
raise HTTPException(status_code=404, detail="Note not found") raise XeniaError("note.not_found")
db.delete(note) db.delete(note)
db.commit() db.commit()
_changed()
# ── Todos ───────────────────────────────────────────────────────────────────── # ── Todos ─────────────────────────────────────────────────────────────────────
@router.get("/todos", response_model=List[TodoOut]) @router.get("/todos", response_model=List[TodoOut])
def list_todos(done: bool = None, db: Session = Depends(get_db), user: User = Depends(require_manager)): def list_todos(done: bool = None, db: Session = Depends(get_db), user: User = USE):
q = db.query(SiteTodo) q = db.query(SiteTodo)
if done is not None: if done is not None:
q = q.filter(SiteTodo.is_done == done) q = q.filter(SiteTodo.is_done == done)
@@ -111,22 +128,27 @@ def list_todos(done: bool = None, db: Session = Depends(get_db), user: User = De
@router.post("/todos", response_model=TodoOut, status_code=status.HTTP_201_CREATED) @router.post("/todos", response_model=TodoOut, status_code=status.HTTP_201_CREATED)
def create_todo(body: TodoCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def create_todo(body: TodoCreate, db: Session = Depends(get_db), user: User = USE):
todo = SiteTodo(body=body.body, priority=body.priority, created_by_id=user.id) if body.priority not in PRIORITIES:
raise XeniaError("validation.choice", field="priority", value=body.priority)
todo = SiteTodo(body=_text(body.body), priority=body.priority, created_by_id=user.id)
db.add(todo) db.add(todo)
db.commit() db.commit()
db.refresh(todo) db.refresh(todo)
_changed()
return _todo_out(todo) return _todo_out(todo)
@router.put("/todos/{todo_id}", response_model=TodoOut) @router.put("/todos/{todo_id}", response_model=TodoOut)
def update_todo(todo_id: int, body: TodoUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def update_todo(todo_id: int, body: TodoUpdate, db: Session = Depends(get_db), user: User = USE):
todo = db.query(SiteTodo).filter(SiteTodo.id == todo_id).first() todo = db.query(SiteTodo).filter(SiteTodo.id == todo_id).first()
if not todo: if not todo:
raise HTTPException(status_code=404, detail="Todo not found") raise XeniaError("todo.not_found")
if body.body is not None: if body.body is not None:
todo.body = body.body todo.body = _text(body.body)
if body.priority is not None: if body.priority is not None:
if body.priority not in PRIORITIES:
raise XeniaError("validation.choice", field="priority", value=body.priority)
todo.priority = body.priority todo.priority = body.priority
if body.is_done is not None: if body.is_done is not None:
todo.is_done = body.is_done todo.is_done = body.is_done
@@ -138,13 +160,15 @@ def update_todo(todo_id: int, body: TodoUpdate, db: Session = Depends(get_db), u
todo.done_by_id = None todo.done_by_id = None
db.commit() db.commit()
db.refresh(todo) db.refresh(todo)
_changed()
return _todo_out(todo) return _todo_out(todo)
@router.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT) @router.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(todo_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)): def delete_todo(todo_id: int, db: Session = Depends(get_db), user: User = USE):
todo = db.query(SiteTodo).filter(SiteTodo.id == todo_id).first() todo = db.query(SiteTodo).filter(SiteTodo.id == todo_id).first()
if not todo: if not todo:
raise HTTPException(status_code=404, detail="Todo not found") raise XeniaError("todo.not_found")
db.delete(todo) db.delete(todo)
db.commit() db.commit()
_changed()
+2 -1
View File
@@ -21,7 +21,8 @@ router = APIRouter()
def _live(user): def _live(user):
now = utcnow() now = utcnow()
return (visible_filter(user), (Notification.expires_at.is_(None)) | (Notification.expires_at > now)) return (visible_filter(user), (Notification.expires_at.is_(None)) | (Notification.expires_at > now),
Notification.resolved_at.is_(None))
def _text(n, lang) -> str: def _text(n, lang) -> str:
File diff suppressed because it is too large Load Diff
+112 -20
View File
@@ -76,35 +76,50 @@ def pos_session(db: Session = Depends(get_db), user=Depends(require(ACCESS))):
# ── menu ──────────────────────────────────────────────────────────────────── # ── menu ────────────────────────────────────────────────────────────────────
def _tr(x) -> dict:
"""A choice's names per language {lang: text} (6R.L: the counter shows them in the cashier's
language; display only, lines keep ids and the venue's names). A row or a sub-choice's dict."""
from core.menu_languages import _load, names_of
if isinstance(x, dict):
return {k: v for k, v in _load(x.get("translations")).items() if isinstance(v, str)}
return names_of(x)
def _subs_out(raw): def _subs_out(raw):
return [{"name": s["name"], "price": round(float(s.get("extra_cost") or 0.0), 2), "is_default": bool(s.get("is_default"))} return [{"name": s["name"], "price": round(float(s.get("extra_cost") or 0.0), 2), "is_default": bool(s.get("is_default")),
"translations": _tr(s)}
for s in pos_cart._subs(raw)] for s in pos_cart._subs(raw)]
def _product_out(p, price: float, prices: dict | None = None) -> dict: def _product_out(p, price: float, prices: dict | None = None) -> dict:
shared = lambda ps: pos_cart._shared(ps.shared_subset) # noqa: E731 shared = lambda ps: pos_cart._shared(ps.shared_subset) # noqa: E731
from core import sales_points from core import allergens, sales_points
from core.menu_languages import of as product_tr
return { return {
"id": p.id, "name": p.name, "description": p.description, "image_url": p.image_url, "id": p.id, "name": p.name, "description": p.description, "image_url": p.image_url,
"translations": product_tr(p), # 6R.L: {lang: {name, description}}; every choice below has its own
"price": round(price, 2), "prices": {k: round(v, 2) for k, v in (prices or {}).items()}, "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], "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", "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), "tags": _tags(p.tags),
"allergens": allergens.of(p),
"primary_category_id": p.primary_category_id, "primary_category_id": p.primary_category_id,
"categories": [{"category_id": m.category_id, "sort_order": m.sort_order} for m in p.memberships], "categories": [{"category_id": m.category_id, "sort_order": m.sort_order} for m in p.memberships],
"sort_order": p.sort_order, "sort_order": p.sort_order,
"quick": [{"id": q.id, "name": q.name, "price": round(q.price or 0.0, 2), "allow_multiple": bool(q.allow_multiple)} "quick": [{"id": q.id, "name": q.name, "price": round(q.price or 0.0, 2), "allow_multiple": bool(q.allow_multiple),
"translations": _tr(q)}
for q in sorted(p.quick_options, key=lambda q: q.sort_order)], for q in sorted(p.quick_options, key=lambda q: q.sort_order)],
"options": [{"id": o.id, "name": o.name, "price": round(o.extra_cost or 0.0, 2), "allow_multiple": bool(o.allow_multiple), "options": [{"id": o.id, "name": o.name, "price": round(o.extra_cost or 0.0, 2), "allow_multiple": bool(o.allow_multiple),
"multi_select": bool(o.multi_select), "subs": _subs_out(o.sub_choices)} "multi_select": bool(o.multi_select), "subs": _subs_out(o.sub_choices), "translations": _tr(o)}
for o in p.options], for o in p.options],
"prefs": [{"id": ps.id, "name": ps.name, "default_choice_id": ps.default_choice_id, "multi": bool(ps.allow_multi_select), "prefs": [{"id": ps.id, "name": ps.name, "translations": _tr(ps), "default_choice_id": ps.default_choice_id, "multi": bool(ps.allow_multi_select),
"shared": ({"name": shared(ps)["name"], "subs": _subs_out(shared(ps)["choices"])} if shared(ps) else None), "shared": ({"name": shared(ps)["name"], "translations": _tr(shared(ps)), "subs": _subs_out(shared(ps)["choices"])} if shared(ps) else None),
"choices": [{"id": c.id, "name": c.name, "price": round(c.extra_cost or 0.0, 2), "choices": [{"id": c.id, "name": c.name, "price": round(c.extra_cost or 0.0, 2),
"disables_shared": bool(c.disables_subset), "subs": _subs_out(c.sub_choices)} "disables_shared": bool(c.disables_subset), "subs": _subs_out(c.sub_choices), "translations": _tr(c)}
for c in ps.choices]} for c in ps.choices]}
for ps in p.preference_sets], for ps in p.preference_sets],
"ingredients": [{"id": i.id, "name": i.name} for i in p.ingredients], "ingredients": [{"id": i.id, "name": i.name, "translations": _tr(i)} for i in p.ingredients],
} }
@@ -139,9 +154,15 @@ 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} 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"]) default = pos_cart.point_for(settings["default_order_type"])
cats = db.query(Category).order_by(Category.sort_order, Category.name).all() cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
from services import price_changes, split_bills
from core.menu_languages import of as product_tr
return { return {
"settings": settings, # + the venue's switch for prices changed by hand (6F.3): 'off' hides the line discount
"categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order} "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,
"translations": product_tr(c)}
for c in cats], for c in cats],
"products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON}) "products": [_product_out(p, by_point[default][i], {sp: by_point[sp][i] for sp in sales_points.IN_PERSON})
for i, p in enumerate(products)], for i, p in enumerate(products)],
@@ -176,14 +197,25 @@ class Payment(BaseModel):
lines: Optional[List[int]] = None # indexes into `lines`; None = all of them 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): class SaleBody(BaseModel):
order_type: Literal["takeaway", "here"] = "takeaway" order_type: Literal["takeaway", "here"] = "takeaway"
lines: List[dict] = Field(min_length=1, max_length=200) 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) cash_given: Optional[float] = Field(default=None, ge=0, le=100000)
def _payment_groups(body: SaleBody, n: int) -> list: 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: if len(body.payments) == 1 and body.payments[0].lines is None:
return [(body.payments[0].method, list(range(n)))] return [(body.payments[0].method, list(range(n)))]
seen = [i for pay in body.payments for i in (pay.lines or [])] seen = [i for pay in body.payments for i in (pay.lines or [])]
@@ -207,17 +239,19 @@ def pos_sale(body: SaleBody, request: Request, db: Session = Depends(get_db), us
_require_shift(db, user) _require_shift(db, user)
orders_api._need(request, db, user, "ordering.orders.close", target="pos sale") # 4.3: taking payment is a key 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)] 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)) groups = _payment_groups(body, len(lines)) if body.split is None else []
_check_discounts(request, db, user, lines) approved_by = _check_discounts(request, db, user, lines)
_check_fiscal(db, {line.product for line in lines}) _check_fiscal(db, {line.product for line in lines})
priced = pos_cart.price_lines(db, lines, body.order_type) 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)] 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)] 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) 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) _check_cash(body.cash_given, cash_due)
order = orders_api.open_order(OrderCreate(table_id=None, order_type=body.order_type), db, user) 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()] item_ids = [i.id for i in db.query(OrderItem).filter(OrderItem.order_id == order.id).order_by(OrderItem.id).all()]
paid, fiscal = [], None paid, fiscal = [], None
for method, idx in groups: for method, idx in groups:
@@ -235,6 +269,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) ───────────────────────────────────────────────── # ── shared checks (3.3b, 3.3c) ─────────────────────────────────────────────────
def _require_shift(db, user): def _require_shift(db, user):
@@ -246,9 +327,16 @@ def _require_shift(db, user):
def _check_discounts(request, db, user, lines): 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 core.access.context import authorize
from services import price_changes
if any(line.discount_pct for line in lines): 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): def _check_fiscal(db, products):
@@ -264,14 +352,17 @@ def _check_cash(cash_given, cash_due):
raise XeniaError("pos.payment_invalid", reason="cash_short") 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 """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 from schemas.order import OrderItemInput, SelectedOptionInput
return [OrderItemInput( return [OrderItemInput(
product_id=line.product.id, quantity=line.quantity, product_id=line.product.id, quantity=line.quantity,
selected_options=[SelectedOptionInput(**e) for e in line.entries] or None, 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", 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)] ) for line, adj in zip(lines, adjs)]
@@ -406,13 +497,13 @@ def pos_table_items(table_id: int, body: TableItemsBody, request: Request, db: S
elif not _in_zones(db, user, table): elif not _in_zones(db, user, table):
raise XeniaError("pos.table_not_yours", table=_table_name(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)] 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 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) 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)] adjs = [pos_cart.discount_adjustment(unit, line.discount_pct) for line, (unit, _) in zip(lines, priced)]
if order is None: if order is None:
order = orders_api.open_order(OrderCreate(table_id=table_id, order_type="here"), db, user) 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", [])} return {"order_id": order.id, "print_results": added.get("print_results", []), "deal_offers": added.get("deal_offers", [])}
@@ -444,7 +535,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()} 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()): if len(items) != len(wanted) or any(i.status not in UNPAID for i in items.values()):
raise XeniaError("pos.items_changed") 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} 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) cash_due = amount.get("cash", 0.0)
_check_cash(body.cash_given, cash_due) _check_cash(body.cash_given, cash_due)
+11 -6
View File
@@ -8,7 +8,8 @@ DELETE /api/prep-zones/{id} delete a prep zone
""" """
import json import json
from core.i18n import normalize_language from core.i18n import normalize_language
from fastapi import APIRouter, Depends, HTTPException from core.access.deps import require
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from pydantic import BaseModel from pydantic import BaseModel
from typing import List, Optional from typing import List, Optional
@@ -18,6 +19,7 @@ from models.prep_zone import PrepZone
from models.printer import Printer from models.printer import Printer
from routers.deps import require_manager from routers.deps import require_manager
from models.user import User from models.user import User
from core.errors import XeniaError
router = APIRouter() router = APIRouter()
@@ -113,11 +115,14 @@ def list_prep_zones(
return [_zone_out(z) for z in zones] return [_zone_out(z) for z in zones]
_MENU = require("catalog.menu.manage") # 6.10: like the nav entry
@router.post("") @router.post("")
def create_prep_zone( def create_prep_zone(
body: PrepZoneCreate, body: PrepZoneCreate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(_MENU),
): ):
zone = PrepZone( zone = PrepZone(
name=body.name, name=body.name,
@@ -151,11 +156,11 @@ def update_prep_zone(
zone_id: int, zone_id: int,
body: PrepZoneUpdate, body: PrepZoneUpdate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(_MENU),
): ):
zone = db.query(PrepZone).filter(PrepZone.id == zone_id).first() zone = db.query(PrepZone).filter(PrepZone.id == zone_id).first()
if not zone: if not zone:
raise HTTPException(status_code=404, detail="Prep zone not found") raise XeniaError("prep_zone.not_found")
if body.name is not None: if body.name is not None:
zone.name = body.name zone.name = body.name
@@ -212,11 +217,11 @@ def update_prep_zone(
def delete_prep_zone( def delete_prep_zone(
zone_id: int, zone_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(_MENU),
): ):
zone = db.query(PrepZone).filter(PrepZone.id == zone_id).first() zone = db.query(PrepZone).filter(PrepZone.id == zone_id).first()
if not zone: if not zone:
raise HTTPException(status_code=404, detail="Prep zone not found") raise XeniaError("prep_zone.not_found")
db.delete(zone) db.delete(zone)
db.commit() db.commit()
return {"ok": True} return {"ok": True}
+259 -41
View File
@@ -3,7 +3,7 @@ import json
from datetime import datetime, timezone from datetime import datetime, timezone
from typing import List, Optional from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from database import get_db from database import get_db
@@ -20,11 +20,21 @@ from schemas.pricing import (
WaiterDiscountSettingsIn, WaiterDiscountSettingsOut, WaiterDiscountSettingsIn, WaiterDiscountSettingsOut,
PriceEventOut, PriceEventOut,
) )
from routers.deps import get_current_user, require_manager from routers.deps import get_current_user
from core.access.deps import require
from models.user import User from models.user import User
from core.errors import XeniaError
router = APIRouter() router = APIRouter()
MANAGE = "pricing.manage" # setting up price groups, modifiers, deals and the discount limits (6.7)
def _changed() -> None:
"""Tell the manager's pricing pages (and the counters' quotes) that the rules changed."""
from services.ws_bus import broadcast_sync
broadcast_sync("pricing.changed", {})
@@ -44,7 +54,7 @@ def list_price_groups(
def create_price_group( def create_price_group(
body: PriceGroupCreate, body: PriceGroupCreate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
pg = PriceGroup( pg = PriceGroup(
name=body.name, name=body.name,
@@ -58,6 +68,7 @@ def create_price_group(
) )
db.add(pg) db.add(pg)
db.commit() db.commit()
_changed()
db.refresh(pg) db.refresh(pg)
return pg return pg
@@ -67,11 +78,11 @@ def update_price_group(
group_id: int, group_id: int,
body: PriceGroupUpdate, body: PriceGroupUpdate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first() pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
if not pg: if not pg:
raise HTTPException(status_code=404, detail="Price group not found") raise XeniaError("price_group.not_found")
pg.name = body.name pg.name = body.name
pg.description = body.description pg.description = body.description
pg.color = body.color pg.color = body.color
@@ -80,6 +91,7 @@ def update_price_group(
pg.auto_disable_time = body.auto_disable_time pg.auto_disable_time = body.auto_disable_time
pg.auto_days = json.dumps(body.auto_days) if body.auto_days is not None else None pg.auto_days = json.dumps(body.auto_days) if body.auto_days is not None else None
db.commit() db.commit()
_changed()
db.refresh(pg) db.refresh(pg)
return pg return pg
@@ -88,13 +100,14 @@ def update_price_group(
def toggle_price_group( def toggle_price_group(
group_id: int, group_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first() pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
if not pg: if not pg:
raise HTTPException(status_code=404, detail="Price group not found") raise XeniaError("price_group.not_found")
pg.is_active = 0 if pg.is_active else 1 pg.is_active = 0 if pg.is_active else 1
db.commit() db.commit()
_changed()
db.refresh(pg) db.refresh(pg)
return pg return pg
@@ -103,13 +116,14 @@ def toggle_price_group(
def delete_price_group( def delete_price_group(
group_id: int, group_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first() pg = db.query(PriceGroup).filter(PriceGroup.id == group_id).first()
if not pg: if not pg:
raise HTTPException(status_code=404, detail="Price group not found") raise XeniaError("price_group.not_found")
db.delete(pg) db.delete(pg)
db.commit() db.commit()
_changed()
# ============================================================================= # =============================================================================
@@ -149,7 +163,7 @@ def list_favorite_modifiers(
def create_modifier( def create_modifier(
body: PriceModifierCreate, body: PriceModifierCreate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
m = PriceModifier( m = PriceModifier(
name=body.name, name=body.name,
@@ -171,6 +185,7 @@ def create_modifier(
_sync_conditions(m, body.conditions, db, model="modifier") _sync_conditions(m, body.conditions, db, model="modifier")
_sync_modifier_targets(m, body.targets, db) _sync_modifier_targets(m, body.targets, db)
db.commit() db.commit()
_changed()
db.refresh(m) db.refresh(m)
return m return m
@@ -180,11 +195,11 @@ def update_modifier(
modifier_id: int, modifier_id: int,
body: PriceModifierUpdate, body: PriceModifierUpdate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first() m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
if not m: if not m:
raise HTTPException(status_code=404, detail="Modifier not found") raise XeniaError("modifier.not_found")
m.name = body.name m.name = body.name
m.description = body.description m.description = body.description
m.color = body.color m.color = body.color
@@ -208,6 +223,7 @@ def update_modifier(
_sync_conditions(m, body.conditions, db, model="modifier") _sync_conditions(m, body.conditions, db, model="modifier")
_sync_modifier_targets(m, body.targets, db) _sync_modifier_targets(m, body.targets, db)
db.commit() db.commit()
_changed()
db.refresh(m) db.refresh(m)
return m return m
@@ -216,15 +232,16 @@ def update_modifier(
def toggle_modifier( def toggle_modifier(
modifier_id: int, modifier_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first() m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
if not m: if not m:
raise HTTPException(status_code=404, detail="Modifier not found") raise XeniaError("modifier.not_found")
m.is_active = 0 if m.is_active else 1 m.is_active = 0 if m.is_active else 1
m.updated_at = utcnow() m.updated_at = utcnow()
m.updated_by = user.id m.updated_by = user.id
db.commit() db.commit()
_changed()
db.refresh(m) db.refresh(m)
return m return m
@@ -233,13 +250,14 @@ def toggle_modifier(
def reorder_modifiers( def reorder_modifiers(
body: PriceModifierReorderRequest, body: PriceModifierReorderRequest,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
for item in body.items: for item in body.items:
db.query(PriceModifier).filter(PriceModifier.id == item.id).update( db.query(PriceModifier).filter(PriceModifier.id == item.id).update(
{"sort_order": item.sort_order} {"sort_order": item.sort_order}
) )
db.commit() db.commit()
_changed()
return {"ok": True} return {"ok": True}
@@ -247,13 +265,14 @@ def reorder_modifiers(
def delete_modifier( def delete_modifier(
modifier_id: int, modifier_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first() m = db.query(PriceModifier).filter(PriceModifier.id == modifier_id).first()
if not m: if not m:
raise HTTPException(status_code=404, detail="Modifier not found") raise XeniaError("modifier.not_found")
db.delete(m) db.delete(m)
db.commit() db.commit()
_changed()
# ============================================================================= # =============================================================================
@@ -272,7 +291,7 @@ def list_deals(
def create_deal( def create_deal(
body: DealCreate, body: DealCreate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
d = Deal( d = Deal(
name=body.name, name=body.name,
@@ -297,6 +316,7 @@ def create_deal(
_sync_conditions(d, body.conditions, db, model="deal") _sync_conditions(d, body.conditions, db, model="deal")
_sync_deal_targets(d, body.targets, db) _sync_deal_targets(d, body.targets, db)
db.commit() db.commit()
_changed()
db.refresh(d) db.refresh(d)
return d return d
@@ -306,11 +326,11 @@ def update_deal(
deal_id: int, deal_id: int,
body: DealUpdate, body: DealUpdate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
d = db.query(Deal).filter(Deal.id == deal_id).first() d = db.query(Deal).filter(Deal.id == deal_id).first()
if not d: if not d:
raise HTTPException(status_code=404, detail="Deal not found") raise XeniaError("deal.not_found")
d.name = body.name d.name = body.name
d.description = body.description d.description = body.description
d.color = body.color d.color = body.color
@@ -334,6 +354,7 @@ def update_deal(
_sync_conditions(d, body.conditions, db, model="deal") _sync_conditions(d, body.conditions, db, model="deal")
_sync_deal_targets(d, body.targets, db) _sync_deal_targets(d, body.targets, db)
db.commit() db.commit()
_changed()
db.refresh(d) db.refresh(d)
return d return d
@@ -342,13 +363,14 @@ def update_deal(
def toggle_deal( def toggle_deal(
deal_id: int, deal_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
d = db.query(Deal).filter(Deal.id == deal_id).first() d = db.query(Deal).filter(Deal.id == deal_id).first()
if not d: if not d:
raise HTTPException(status_code=404, detail="Deal not found") raise XeniaError("deal.not_found")
d.is_active = 0 if d.is_active else 1 d.is_active = 0 if d.is_active else 1
db.commit() db.commit()
_changed()
db.refresh(d) db.refresh(d)
return d return d
@@ -357,13 +379,14 @@ def toggle_deal(
def delete_deal( def delete_deal(
deal_id: int, deal_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
d = db.query(Deal).filter(Deal.id == deal_id).first() d = db.query(Deal).filter(Deal.id == deal_id).first()
if not d: if not d:
raise HTTPException(status_code=404, detail="Deal not found") raise XeniaError("deal.not_found")
db.delete(d) db.delete(d)
db.commit() db.commit()
_changed()
# ============================================================================= # =============================================================================
@@ -373,7 +396,7 @@ def delete_deal(
@router.get("/discount-settings/global") @router.get("/discount-settings/global")
def get_global_discount_settings( def get_global_discount_settings(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
from models.settings import PosSettings from models.settings import PosSettings
keys = [ keys = [
@@ -386,33 +409,48 @@ def get_global_discount_settings(
row_map = {r.key.split(".", 1)[1]: r.value for r in rows} row_map = {r.key.split(".", 1)[1]: r.value for r in rows}
# Coerce types so frontend toggle/number fields work correctly # Coerce types so frontend toggle/number fields work correctly
def _coerce(k, v): def _coerce(k, v):
if v is None: if v is None or v == "" or v == "None":
return None return None if k != "enabled" else True
if k == "enabled": if k == "enabled":
return v.lower() in ("true", "1", "yes") return v.lower() in ("true", "1", "yes")
try: try:
return float(v) if "." in str(v) else int(v) return float(v) if "." in str(v) else int(v)
except Exception: except Exception:
return v return v
return {k: _coerce(k, v) for k, v in row_map.items()} out = {k: None for k in ("max_total_value_workday", "max_total_value_shift", "max_items_per_shift")}
out["enabled"] = True
out.update({k: _coerce(k, v) for k, v in row_map.items()})
return out
@router.put("/discount-settings/global") @router.put("/discount-settings/global")
def set_global_discount_settings( def set_global_discount_settings(
body: dict, body: dict,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
from models.settings import PosSettings from models.settings import PosSettings
allowed = { allowed = {
"enabled", "max_total_value_workday", "enabled", "max_total_value_workday",
"max_total_value_shift", "max_items_per_shift", "max_total_value_shift", "max_items_per_shift",
} }
now = utcnow().isoformat() now = utcnow() # was .isoformat(): saving failed on platform v2
for k, v in body.items(): for k, v in body.items():
if k not in allowed: if k not in allowed:
continue continue
full_key = f"discounts.{k}" full_key = f"discounts.{k}"
if k == "enabled":
v = "true" if v in (True, "true", "1", 1) else "false"
elif v is None or v == "":
v = "" # no limit
else:
try:
v = float(v)
except (TypeError, ValueError):
raise XeniaError("pricing.bad_limit", key=k)
if v < 0:
raise XeniaError("pricing.bad_limit", key=k)
v = int(v) if k == "max_items_per_shift" or v.is_integer() else v
row = db.query(PosSettings).filter(PosSettings.key == full_key).first() row = db.query(PosSettings).filter(PosSettings.key == full_key).first()
if row: if row:
row.value = str(v) row.value = str(v)
@@ -420,6 +458,7 @@ def set_global_discount_settings(
else: else:
db.add(PosSettings(key=full_key, value=str(v), updated_at=now)) db.add(PosSettings(key=full_key, value=str(v), updated_at=now))
db.commit() db.commit()
_changed()
return {"ok": True} return {"ok": True}
@@ -440,7 +479,7 @@ def get_my_discount_settings(
def get_waiter_discount_settings( def get_waiter_discount_settings(
user_id: int, user_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
s = db.query(WaiterDiscountSettings).filter( s = db.query(WaiterDiscountSettings).filter(
WaiterDiscountSettings.user_id == user_id WaiterDiscountSettings.user_id == user_id
@@ -456,7 +495,7 @@ def set_waiter_discount_settings(
user_id: int, user_id: int,
body: WaiterDiscountSettingsIn, body: WaiterDiscountSettingsIn,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("pricing.manage")),
): ):
s = db.query(WaiterDiscountSettings).filter( s = db.query(WaiterDiscountSettings).filter(
WaiterDiscountSettings.user_id == user_id WaiterDiscountSettings.user_id == user_id
@@ -473,6 +512,7 @@ def set_waiter_discount_settings(
s.max_items_per_workday = body.max_items_per_workday s.max_items_per_workday = body.max_items_per_workday
s.max_items_per_order = body.max_items_per_order s.max_items_per_order = body.max_items_per_order
db.commit() db.commit()
_changed()
db.refresh(s) db.refresh(s)
return s return s
@@ -487,12 +527,11 @@ def get_order_price_events(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(get_current_user), user: User = Depends(get_current_user),
): ):
events = ( from services import price_changes
db.query(PriceEventLog) q = db.query(PriceEventLog).filter(PriceEventLog.order_id == order_id)
.filter(PriceEventLog.order_id == order_id) if not price_changes.can_view(user): # prices changed by hand: ordering.prices.view_changes (6F.3)
.order_by(PriceEventLog.applied_at) q = q.filter(PriceEventLog.event_type != price_changes.EVENT)
.all() events = q.order_by(PriceEventLog.applied_at).all()
)
result = [] result = []
for ev in events: for ev in events:
out = PriceEventOut.model_validate(ev) out = PriceEventOut.model_validate(ev)
@@ -501,7 +540,9 @@ def get_order_price_events(
if ev.deal: if ev.deal:
out.deal_name = ev.deal.name out.deal_name = ev.deal.name
if ev.applied_by: 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) result.append(out)
return result return result
@@ -535,11 +576,11 @@ def accept_deal_offer(
deal = db.query(Deal).filter(Deal.id == deal_id).first() deal = db.query(Deal).filter(Deal.id == deal_id).first()
if not deal: if not deal:
raise HTTPException(status_code=404, detail="Deal not found") raise XeniaError("deal.not_found")
order = db.query(Order).filter(Order.id == order_id).first() order = db.query(Order).filter(Order.id == order_id).first()
if not order: if not order:
raise HTTPException(status_code=404, detail="Order not found") raise XeniaError("order.not_found", order_id=order_id)
added_item_ids = [] added_item_ids = []
@@ -642,8 +683,52 @@ def dismiss_deal_offer(
# Internal helpers # Internal helpers
# ============================================================================= # =============================================================================
def _condition_ok(ctype: str, p: dict) -> bool:
"""A condition the price engine can evaluate (an incomplete one used to break the POS)."""
import re
from datetime import date
def hhmm(v):
return isinstance(v, str) and re.fullmatch(r"([01]\d|2[0-3]):[0-5]\d", v) is not None
def day(v):
try:
date.fromisoformat(v)
return True
except (TypeError, ValueError):
return False
def num(v, low):
return isinstance(v, (int, float)) and not isinstance(v, bool) and v >= low
if ctype == "time_range":
return hhmm(p.get("from")) and hhmm(p.get("to")) and p["from"] != p["to"]
if ctype == "date_range":
return day(p.get("from")) and day(p.get("to")) and p["from"] <= p["to"]
if ctype == "specific_date":
return bool(p.get("dates")) and all(day(d) for d in p["dates"])
if ctype == "day_of_week":
return bool(p.get("days")) and all(isinstance(d, int) and 0 <= d <= 6 for d in p["days"])
if ctype == "min_item_quantity":
return num(p.get("min", 1), 1)
if ctype == "min_category_qty":
return isinstance(p.get("category_id"), int) and num(p.get("min", 1), 1)
if ctype == "min_order_value":
return num(p.get("min", 0), 0)
if ctype == "order_channel":
return bool(p.get("channels"))
if ctype == "price_group_active":
return isinstance(p.get("price_group_id"), int)
if ctype == "scene_active":
return isinstance(p.get("scene_id"), int) and not isinstance(p.get("scene_id"), bool)
return ctype in ("user_tier", "low_stock") # old placeholders: kept, never added
def _sync_conditions(parent, conditions_in, db: Session, model: str): def _sync_conditions(parent, conditions_in, db: Session, model: str):
"""Write condition rows for a modifier or deal.""" """Write condition rows for a modifier or deal."""
for c in conditions_in:
if not _condition_ok(c.condition_type, c.params or {}):
raise XeniaError("pricing.bad_condition", type=c.condition_type)
for c in conditions_in: for c in conditions_in:
if model == "modifier": if model == "modifier":
db.add(PriceModifierCondition( db.add(PriceModifierCondition(
@@ -681,3 +766,136 @@ def _sync_deal_targets(deal, targets_in, db: Session):
target_ids=json.dumps(t.target_ids) if t.target_ids else None, target_ids=json.dumps(t.target_ids) if t.target_ids else None,
target_tags=json.dumps(t.target_tags) if t.target_tags else None, target_tags=json.dumps(t.target_tags) if t.target_tags else None,
)) ))
# =============================================================================
# ORDER CHANNEL PRICES (2026-11-20, services/channel_prices.py)
# =============================================================================
from pydantic import BaseModel as _Base # noqa: E402
class ChannelPriceIn(_Base):
name: Optional[str] = None
sales_points: List[str]
product_ids: List[int] = []
category_ids: List[int] = []
action_type: str
value: float
round_to: Optional[str] = None
is_active: bool = True
class ProductChannelPriceIn(_Base):
"""The product editor's quick edit: per sales point, its own rule or null (no own rule)."""
points: dict[str, Optional[dict]]
def _cp_fields(body: ChannelPriceIn) -> dict:
from services import channel_prices as cp
f = body.model_dump()
f["name"] = (f.get("name") or "").strip()[:120] or None
f["round_to"] = f.get("round_to") or None
cp.check(f)
return f
def _cp_store(row, f: dict, user) -> None:
from core.timeutil import utcnow as _now
row.name = f["name"]
row.sales_points = json.dumps(list(dict.fromkeys(f["sales_points"])))
row.product_ids = json.dumps(sorted(set(f["product_ids"])))
row.category_ids = json.dumps(sorted(set(f["category_ids"])))
row.action_type = f["action_type"]
row.value = f["value"]
row.round_to = f["round_to"]
row.is_active = f["is_active"]
row.updated_at = _now()
row.updated_by = user.id
@router.get("/channel-prices")
def list_channel_prices(db: Session = Depends(get_db), user: User = Depends(require(MANAGE))):
from models.pricing import ChannelPrice
from services import channel_prices as cp
return [cp.out(r) for r in db.query(ChannelPrice).order_by(ChannelPrice.id).all()]
@router.post("/channel-prices", status_code=status.HTTP_201_CREATED)
def create_channel_price(body: ChannelPriceIn, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))):
from models.pricing import ChannelPrice
from services import channel_prices as cp
f = _cp_fields(body)
row = ChannelPrice()
_cp_store(row, f, user)
db.add(row)
db.commit()
_changed()
return cp.out(row)
@router.put("/channel-prices/{rule_id}")
def update_channel_price(rule_id: int, body: ChannelPriceIn, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))):
from models.pricing import ChannelPrice
from services import channel_prices as cp
row = db.query(ChannelPrice).filter(ChannelPrice.id == rule_id).first()
if not row:
raise XeniaError("channel_price.not_found")
_cp_store(row, _cp_fields(body), user)
db.commit()
_changed()
return cp.out(row)
@router.delete("/channel-prices/{rule_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_channel_price(rule_id: int, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))):
from models.pricing import ChannelPrice
row = db.query(ChannelPrice).filter(ChannelPrice.id == rule_id).first()
if not row:
raise XeniaError("channel_price.not_found")
db.delete(row)
db.commit()
_changed()
@router.get("/channel-prices/product/{product_id}")
def product_channel_prices(product_id: int, db: Session = Depends(get_db), user: User = Depends(require(MANAGE))):
"""Per sales point the product is sold at: the default price, the price there and why."""
from models.product import Product
from services import channel_prices as cp
p = db.query(Product).filter(Product.id == product_id).first()
if not p:
raise XeniaError("product.not_found")
return {"product_id": p.id, "base_price": p.base_price, "points": cp.product_view(db, p)}
@router.put("/channel-prices/product/{product_id}")
def set_product_channel_prices(product_id: int, body: ProductChannelPriceIn, db: Session = Depends(get_db),
user: User = Depends(require(MANAGE))):
"""The product's own price per sales point: {action_type, value, round_to} sets it, null
removes it (the category's or the channel's rule, or the default price, counts again)."""
from models.pricing import ChannelPrice
from models.product import Product
from services import channel_prices as cp
p = db.query(Product).filter(Product.id == product_id).first()
if not p:
raise XeniaError("product.not_found")
every = db.query(ChannelPrice).order_by(ChannelPrice.id).all()
for point, spec in body.points.items():
own = cp.own_rule(every, p.id, point)
if spec is None:
if own is not None:
db.delete(own)
continue
f = {"name": None, "sales_points": [point], "product_ids": [p.id], "category_ids": [],
"action_type": spec.get("action_type"), "value": spec.get("value"), "round_to": spec.get("round_to") or None,
"is_active": True}
cp.check(f)
if own is None:
own = ChannelPrice()
db.add(own)
_cp_store(own, f, user)
db.commit()
_changed()
return {"product_id": p.id, "base_price": p.base_price, "points": cp.product_view(db, p)}
+40
View File
@@ -0,0 +1,40 @@
"""Printing problems (plan step 6.10, services/print_problems.py): the tickets that didn't
print, for whoever may act on their orders (the managers see all), and the three ways out:
print again, send to another printer, mark as handled. Live event: `print.problems`."""
from __future__ import annotations
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from sqlalchemy.orm import Session
from core.access.deps import require_any
from database import get_db
from services import print_problems as svc
router = APIRouter()
_STAFF = require_any("ordering.orders.open", "core.dashboard.access")
@router.get("")
def list_problems(db: Session = Depends(get_db), user=Depends(_STAFF)):
"""{problems: [...oldest first], printers: [{id, name}]} (the printers a ticket can go to)."""
return {"problems": svc.problems(db, user), "printers": svc.printers(db)}
@router.post("/{job_id}/retry")
def retry(job_id: int, db: Session = Depends(get_db), user=Depends(_STAFF)):
return svc.retry(db, job_id, user)
class RedirectBody(BaseModel):
printer_id: int
@router.post("/{job_id}/redirect")
def redirect(job_id: int, body: RedirectBody, db: Session = Depends(get_db), user=Depends(_STAFF)):
return svc.redirect(db, job_id, body.printer_id, user)
@router.post("/{job_id}/handled")
def handled(job_id: int, db: Session = Depends(get_db), user=Depends(_STAFF)):
return svc.handled(db, job_id, user)
+75 -28
View File
@@ -1,11 +1,11 @@
from core.access.check import holds from core.access.check import holds
import json import json
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, status
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import List from typing import List
from core import sales_points from core import allergens, menu_languages, sales_points
from database import get_db from database import get_db
from models.product import Product, Category, ProductCategory, ProductOption, ProductQuickOption, ProductIngredient, ProductPreferenceSet, ProductPreferenceChoice, ProductModifierGroup from models.product import Product, Category, ProductCategory, ProductOption, ProductQuickOption, ProductIngredient, ProductPreferenceSet, ProductPreferenceChoice, ProductModifierGroup
from models.prep_zone import PrepZone from models.prep_zone import PrepZone
@@ -26,6 +26,35 @@ from core.errors import XeniaError
router = APIRouter() router = APIRouter()
def _sub_dump(sub) -> dict:
"""A sub-choice (or a shared sub-set) as stored: its names per language cleaned (0042)."""
d = sub.model_dump()
d["translations"] = menu_languages.normalize_names(d.get("translations"))
if "choices" in d:
d["choices"] = [_sub_dump(c) for c in sub.choices]
return d
def _check_names(body) -> None:
"""Every choice's names valid before anything is replaced (a refusal changes nothing)."""
subs = lambda xs: [menu_languages.normalize_names(x.translations) for x in xs or []] # noqa: E731
for g in body.modifier_groups or []:
menu_languages.normalize_names(g.translations)
for x in [*(body.quick_options or []), *(body.ingredients or [])]:
menu_languages.normalize_names(x.translations)
for o in body.options or []:
menu_languages.normalize_names(o.translations)
subs(o.sub_choices)
for ps in body.preference_sets or []:
menu_languages.normalize_names(ps.translations)
for c in ps.choices:
menu_languages.normalize_names(c.translations)
subs(c.sub_choices)
if ps.shared_subset:
menu_languages.normalize_names(ps.shared_subset.translations)
subs(ps.shared_subset.choices)
def _broadcast_products_changed(): def _broadcast_products_changed():
broadcast_sync("products_changed", {}) broadcast_sync("products_changed", {})
@@ -43,6 +72,7 @@ def _replace_modifier_groups(db, product, groups):
modifier_type=g.modifier_type, modifier_type=g.modifier_type,
name=g.name, name=g.name,
sort_order=i, sort_order=i,
translations=menu_languages.dump(menu_languages.normalize_names(g.translations)),
) )
db.add(new_g) db.add(new_g)
db.flush() db.flush()
@@ -64,6 +94,7 @@ def _replace_quick_options(db, product, quick_options):
is_favorite=qo.is_favorite, is_favorite=qo.is_favorite,
favorite_sort_order=qo.favorite_sort_order, favorite_sort_order=qo.favorite_sort_order,
is_compact=qo.is_compact, is_compact=qo.is_compact,
translations=menu_languages.dump(menu_languages.normalize_names(qo.translations)),
)) ))
@@ -72,7 +103,7 @@ def _replace_options(db, product, options, group_id_map=None):
db.delete(opt) db.delete(opt)
db.flush() db.flush()
for opt in options: for opt in options:
sub_json = json.dumps([s.model_dump() for s in opt.sub_choices]) if opt.sub_choices else None sub_json = json.dumps([_sub_dump(s) for s in opt.sub_choices], ensure_ascii=False) if opt.sub_choices else None
resolved_group = group_id_map[opt.group_id] if (group_id_map and opt.group_id is not None and opt.group_id < len(group_id_map)) else None resolved_group = group_id_map[opt.group_id] if (group_id_map and opt.group_id is not None and opt.group_id < len(group_id_map)) else None
db.add(ProductOption( db.add(ProductOption(
product_id=product.id, product_id=product.id,
@@ -85,6 +116,7 @@ def _replace_options(db, product, options, group_id_map=None):
favorite_sort_order=opt.favorite_sort_order, favorite_sort_order=opt.favorite_sort_order,
is_compact=opt.is_compact, is_compact=opt.is_compact,
group_id=resolved_group, group_id=resolved_group,
translations=menu_languages.dump(menu_languages.normalize_names(opt.translations)),
)) ))
@@ -94,7 +126,8 @@ def _replace_ingredients(db, product, ingredients, group_id_map=None):
db.flush() db.flush()
for ing in ingredients: for ing in ingredients:
resolved_group = group_id_map[ing.group_id] if (group_id_map and ing.group_id is not None and ing.group_id < len(group_id_map)) else None resolved_group = group_id_map[ing.group_id] if (group_id_map and ing.group_id is not None and ing.group_id < len(group_id_map)) else None
db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id'}), group_id=resolved_group)) db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id', 'translations'}), group_id=resolved_group,
translations=menu_languages.dump(menu_languages.normalize_names(ing.translations))))
def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group_id_map=None): def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group_id_map=None):
@@ -102,7 +135,7 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
db.delete(ps) db.delete(ps)
db.flush() db.flush()
for ps in sets: for ps in sets:
shared_json = json.dumps(ps.shared_subset.model_dump()) if ps.shared_subset else None shared_json = json.dumps(_sub_dump(ps.shared_subset), ensure_ascii=False) if ps.shared_subset else None
resolved_group = group_id_map[ps.group_id] if (group_id_map and ps.group_id is not None and ps.group_id < len(group_id_map)) else None resolved_group = group_id_map[ps.group_id] if (group_id_map and ps.group_id is not None and ps.group_id < len(group_id_map)) else None
new_set = ProductPreferenceSet( new_set = ProductPreferenceSet(
product_id=product.id, product_id=product.id,
@@ -113,12 +146,13 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
group_id=resolved_group, group_id=resolved_group,
allow_multi_select=ps.allow_multi_select, allow_multi_select=ps.allow_multi_select,
allow_choice_quantity=ps.allow_choice_quantity, allow_choice_quantity=ps.allow_choice_quantity,
translations=menu_languages.dump(menu_languages.normalize_names(ps.translations)),
) )
db.add(new_set) db.add(new_set)
db.flush() db.flush()
created_choices = [] created_choices = []
for ch in ps.choices: for ch in ps.choices:
sub_json = json.dumps([s.model_dump() for s in ch.sub_choices]) if ch.sub_choices else None sub_json = json.dumps([_sub_dump(s) for s in ch.sub_choices], ensure_ascii=False) if ch.sub_choices else None
choice = ProductPreferenceChoice( choice = ProductPreferenceChoice(
set_id=new_set.id, set_id=new_set.id,
name=ch.name, name=ch.name,
@@ -126,6 +160,7 @@ def _replace_preference_sets(db, product, sets: List[PreferenceSetCreate], group
sub_choices=sub_json, sub_choices=sub_json,
disables_subset=ch.disables_subset, disables_subset=ch.disables_subset,
is_compact=ch.is_compact, is_compact=ch.is_compact,
translations=menu_languages.dump(menu_languages.normalize_names(ch.translations)),
) )
db.add(choice) db.add(choice)
db.flush() db.flush()
@@ -192,6 +227,7 @@ def create_category(body: CategoryCreate, db: Session = Depends(get_db), user: U
parent_id=body.parent_id, parent_id=body.parent_id,
general_sort_order=body.general_sort_order, general_sort_order=body.general_sort_order,
media_id=_picture(db, body.media_id), media_id=_picture(db, body.media_id),
translations=menu_languages.dump(menu_languages.normalize_category(body.translations)),
) )
db.add(cat) db.add(cat)
db.commit() db.commit()
@@ -239,19 +275,19 @@ def reparent_category(category_id: int, body: CategoryReparentRequest, db: Sessi
""" """
cat = db.query(Category).filter(Category.id == category_id).first() cat = db.query(Category).filter(Category.id == category_id).first()
if not cat: if not cat:
raise HTTPException(status_code=404, detail="Category not found") raise XeniaError("catalog.category_not_found")
if body.parent_id is not None: if body.parent_id is not None:
new_parent = db.query(Category).filter(Category.id == body.parent_id).first() new_parent = db.query(Category).filter(Category.id == body.parent_id).first()
if not new_parent: if not new_parent:
raise HTTPException(status_code=404, detail="Target parent category not found") raise XeniaError("catalog.parent_not_found")
if new_parent.parent_id is not None: if new_parent.parent_id is not None:
raise HTTPException(status_code=400, detail="Cannot nest more than two levels deep") raise XeniaError("catalog.too_deep")
if body.parent_id == category_id: if body.parent_id == category_id:
raise HTTPException(status_code=400, detail="A category cannot be its own parent") raise XeniaError("catalog.own_parent")
# If cat currently has children and is being made a sub, block it # If cat currently has children and is being made a sub, block it
has_children = db.query(Category).filter(Category.parent_id == category_id).count() > 0 has_children = db.query(Category).filter(Category.parent_id == category_id).count() > 0
if has_children and body.parent_id is not None: if has_children and body.parent_id is not None:
raise HTTPException(status_code=400, detail="Cannot nest a category that has subcategories") raise XeniaError("catalog.nest_has_children")
# Assign new sort_order at the end of the destination level # Assign new sort_order at the end of the destination level
sibling_count = db.query(Category).filter(Category.parent_id == body.parent_id).count() sibling_count = db.query(Category).filter(Category.parent_id == body.parent_id).count()
cat.parent_id = body.parent_id cat.parent_id = body.parent_id
@@ -266,9 +302,11 @@ def reparent_category(category_id: int, body: CategoryReparentRequest, db: Sessi
def update_category(category_id: int, body: CategoryUpdate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)): def update_category(category_id: int, body: CategoryUpdate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
cat = db.query(Category).filter(Category.id == category_id).first() cat = db.query(Category).filter(Category.id == category_id).first()
if not cat: if not cat:
raise HTTPException(status_code=404, detail="Category not found") raise XeniaError("catalog.category_not_found")
for field, value in body.model_dump(exclude_none=True, exclude={"media_id"}).items(): for field, value in body.model_dump(exclude_none=True, exclude={"media_id", "translations"}).items():
setattr(cat, field, value) setattr(cat, field, value)
if body.translations is not None:
cat.translations = menu_languages.dump(menu_languages.normalize_category(body.translations))
if "media_id" in body.model_fields_set: if "media_id" in body.model_fields_set:
cat.media_id = _picture(db, body.media_id) cat.media_id = _picture(db, body.media_id)
db.commit() db.commit()
@@ -281,7 +319,7 @@ def update_category(category_id: int, body: CategoryUpdate, db: Session = Depend
def delete_category(category_id: int, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)): def delete_category(category_id: int, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
cat = db.query(Category).filter(Category.id == category_id).first() cat = db.query(Category).filter(Category.id == category_id).first()
if not cat: if not cat:
raise HTTPException(status_code=404, detail="Category not found") raise XeniaError("catalog.category_not_found")
from services.catalog import remove_category from services.catalog import remove_category
remove_category(db, category_id) # its listings go; products whose main category it was get their next one remove_category(db, category_id) # its listings go; products whose main category it was get their next one
db.delete(cat) db.delete(cat)
@@ -368,13 +406,16 @@ def reorder_products(items: List[ProductReorderItem], db: Session = Depends(get_
@router.post("/", response_model=ProductOut, status_code=status.HTTP_201_CREATED) @router.post("/", response_model=ProductOut, status_code=status.HTTP_201_CREATED)
def create_product(body: ProductCreate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)): def create_product(body: ProductCreate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
_check_names(body)
data = body.model_dump(exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", data = body.model_dump(exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags",
"category_id", "primary_category_id", "category_ids"}) "category_id", "primary_category_id", "category_ids", "allergens", "translations"})
if data.get("sort_order") == 0: if data.get("sort_order") == 0:
data["sort_order"] = db.query(Product).count() data["sort_order"] = db.query(Product).count()
if body.cost_breakdown is not None: if body.cost_breakdown is not None:
data["cost_breakdown"] = json.dumps([item.model_dump() for item in body.cost_breakdown]) data["cost_breakdown"] = json.dumps([item.model_dump() for item in body.cost_breakdown])
data["tags"] = json.dumps(body.tags) if body.tags is not None else None data["tags"] = json.dumps(body.tags) if body.tags is not None else None
data["allergens"] = allergens.dump(body.allergens)
data["translations"] = menu_languages.dump(menu_languages.normalize_product(body.translations))
data["sold_at"] = sales_points.dump(body.sold_at) data["sold_at"] = sales_points.dump(body.sold_at)
data["media_id"] = _picture(db, body.media_id) data["media_id"] = _picture(db, body.media_id)
product = Product(**data) product = Product(**data)
@@ -395,11 +436,12 @@ def create_product(body: ProductCreate, db: Session = Depends(get_db), user: Use
is_favorite=qo.is_favorite, is_favorite=qo.is_favorite,
favorite_sort_order=qo.favorite_sort_order, favorite_sort_order=qo.favorite_sort_order,
is_compact=qo.is_compact, is_compact=qo.is_compact,
translations=menu_languages.dump(menu_languages.normalize_names(qo.translations)),
)) ))
created_groups = _replace_modifier_groups(db, product, body.modifier_groups) created_groups = _replace_modifier_groups(db, product, body.modifier_groups)
group_id_map = [g.id for g in created_groups] group_id_map = [g.id for g in created_groups]
for opt in body.options: for opt in body.options:
sub_json = json.dumps([s.model_dump() for s in opt.sub_choices]) if opt.sub_choices else None sub_json = json.dumps([_sub_dump(s) for s in opt.sub_choices], ensure_ascii=False) if opt.sub_choices else None
resolved_group = group_id_map[opt.group_id] if (opt.group_id is not None and opt.group_id < len(group_id_map)) else None resolved_group = group_id_map[opt.group_id] if (opt.group_id is not None and opt.group_id < len(group_id_map)) else None
db.add(ProductOption( db.add(ProductOption(
product_id=product.id, product_id=product.id,
@@ -412,10 +454,12 @@ def create_product(body: ProductCreate, db: Session = Depends(get_db), user: Use
favorite_sort_order=opt.favorite_sort_order, favorite_sort_order=opt.favorite_sort_order,
is_compact=opt.is_compact, is_compact=opt.is_compact,
group_id=resolved_group, group_id=resolved_group,
translations=menu_languages.dump(menu_languages.normalize_names(opt.translations)),
)) ))
for ing in body.ingredients: for ing in body.ingredients:
resolved_group = group_id_map[ing.group_id] if (ing.group_id is not None and ing.group_id < len(group_id_map)) else None resolved_group = group_id_map[ing.group_id] if (ing.group_id is not None and ing.group_id < len(group_id_map)) else None
db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id'}), group_id=resolved_group)) db.add(ProductIngredient(product_id=product.id, **ing.model_dump(exclude={'group_id', 'translations'}), group_id=resolved_group,
translations=menu_languages.dump(menu_languages.normalize_names(ing.translations))))
_replace_preference_sets(db, product, body.preference_sets, group_id_map) _replace_preference_sets(db, product, body.preference_sets, group_id_map)
db.commit() db.commit()
db.refresh(product) db.refresh(product)
@@ -428,11 +472,12 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
# system products (the delivery fee line, S.5) are not part of the catalogue # system products (the delivery fee line, S.5) are not part of the catalogue
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first() product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
if not product: if not product:
raise HTTPException(status_code=404, detail="Product not found") raise XeniaError("product.not_found")
_check_names(body)
scalar_fields = body.model_dump( scalar_fields = body.model_dump(
exclude_none=True, exclude_none=True,
exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups", exclude={"quick_options", "options", "ingredients", "preference_sets", "cost_breakdown", "prep_zone_ids", "tags", "modifier_groups",
"category_id", "primary_category_id", "category_ids", "media_id"}, "category_id", "primary_category_id", "category_ids", "media_id", "allergens", "translations"},
) )
if "media_id" in body.model_fields_set: if "media_id" in body.model_fields_set:
product.media_id = _picture(db, body.media_id) product.media_id = _picture(db, body.media_id)
@@ -454,6 +499,10 @@ def update_product(product_id: int, body: ProductUpdate, db: Session = Depends(g
product.tags = json.dumps(body.tags) product.tags = json.dumps(body.tags)
elif "tags" in body.model_fields_set: elif "tags" in body.model_fields_set:
product.tags = None product.tags = None
if body.allergens is not None:
product.allergens = allergens.dump(body.allergens)
if body.translations is not None:
product.translations = menu_languages.dump(menu_languages.normalize_product(body.translations))
if body.quick_options is not None: if body.quick_options is not None:
_replace_quick_options(db, product, body.quick_options) _replace_quick_options(db, product, body.quick_options)
# Modifier groups must be recreated before items so we have the ID map # Modifier groups must be recreated before items so we have the ID map
@@ -485,8 +534,9 @@ def create_modifier_group(product_id: int, body: ModifierGroupCreate, db: Sessio
# system products (the delivery fee line, S.5) are not part of the catalogue # system products (the delivery fee line, S.5) are not part of the catalogue
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first() product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
if not product: if not product:
raise HTTPException(status_code=404, detail="Product not found") raise XeniaError("product.not_found")
g = ProductModifierGroup(product_id=product_id, modifier_type=body.modifier_type, name=body.name, sort_order=body.sort_order) g = ProductModifierGroup(product_id=product_id, modifier_type=body.modifier_type, name=body.name, sort_order=body.sort_order,
translations=menu_languages.dump(menu_languages.normalize_names(body.translations)))
db.add(g) db.add(g)
db.commit() db.commit()
db.refresh(g) db.refresh(g)
@@ -498,7 +548,7 @@ def create_modifier_group(product_id: int, body: ModifierGroupCreate, db: Sessio
def update_modifier_group(product_id: int, group_id: int, body: ModifierGroupCreate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)): def update_modifier_group(product_id: int, group_id: int, body: ModifierGroupCreate, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
g = db.query(ProductModifierGroup).filter(ProductModifierGroup.id == group_id, ProductModifierGroup.product_id == product_id).first() g = db.query(ProductModifierGroup).filter(ProductModifierGroup.id == group_id, ProductModifierGroup.product_id == product_id).first()
if not g: if not g:
raise HTTPException(status_code=404, detail="Group not found") raise XeniaError("catalog.group_not_found")
g.name = body.name g.name = body.name
g.sort_order = body.sort_order g.sort_order = body.sort_order
db.commit() db.commit()
@@ -511,7 +561,7 @@ def update_modifier_group(product_id: int, group_id: int, body: ModifierGroupCre
def delete_modifier_group(product_id: int, group_id: int, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)): def delete_modifier_group(product_id: int, group_id: int, db: Session = Depends(get_db), user: User = Depends(require_menu_manager)):
g = db.query(ProductModifierGroup).filter(ProductModifierGroup.id == group_id, ProductModifierGroup.product_id == product_id).first() g = db.query(ProductModifierGroup).filter(ProductModifierGroup.id == group_id, ProductModifierGroup.product_id == product_id).first()
if not g: if not g:
raise HTTPException(status_code=404, detail="Group not found") raise XeniaError("catalog.group_not_found")
# Un-group all items in this group before deleting # Un-group all items in this group before deleting
db.query(ProductOption).filter(ProductOption.group_id == group_id).update({"group_id": None}) db.query(ProductOption).filter(ProductOption.group_id == group_id).update({"group_id": None})
db.query(ProductIngredient).filter(ProductIngredient.group_id == group_id).update({"group_id": None}) db.query(ProductIngredient).filter(ProductIngredient.group_id == group_id).update({"group_id": None})
@@ -526,14 +576,11 @@ def delete_product(product_id: int, hard: bool = False, db: Session = Depends(ge
# system products (the delivery fee line, S.5) are not part of the catalogue # system products (the delivery fee line, S.5) are not part of the catalogue
product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first() product = db.query(Product).filter(Product.id == product_id, Product.system_key.is_(None)).first()
if not product: if not product:
raise HTTPException(status_code=404, detail="Product not found") raise XeniaError("product.not_found")
if hard: if hard:
has_orders = db.query(OrderItem).filter(OrderItem.product_id == product_id).first() has_orders = db.query(OrderItem).filter(OrderItem.product_id == product_id).first()
if has_orders: if has_orders:
raise HTTPException( raise XeniaError("product.in_past_orders")
status_code=400,
detail="Cannot permanently delete a product that appears in past orders. Archive it instead."
)
db.delete(product) db.delete(product)
else: else:
# If product has order history, archive it; otherwise hard delete # If product has order history, archive it; otherwise hard delete
+258 -327
View File
@@ -2,14 +2,15 @@ from core.access.queries import holders_filter
from core.errors import XeniaError from core.errors import XeniaError
from core.modules.entitlements import clamp_start, history_floor, history_since, limit 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 core.timeutil import business_date_of, business_date_window, parse_api_datetime, venue_strftime, to_venue, utcnow
from services import split_bills, tab_books # split_bills: 6F.6, settled lines count, parts never
import csv import csv
import io import io
import json import json
from fastapi import APIRouter, Depends, Query, HTTPException, BackgroundTasks, Request from fastapi import APIRouter, Depends, Query, BackgroundTasks, Request
from fastapi.responses import StreamingResponse from fastapi.responses import StreamingResponse
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session, contains_eager, selectinload
from sqlalchemy import func from sqlalchemy import func
from datetime import date, datetime, timedelta, timezone from datetime import date, datetime, timedelta, timezone
from typing import Optional, List from typing import Optional, List
@@ -64,6 +65,7 @@ history_router = APIRouter(dependencies=[Depends(_business_day_guard("history"))
from services.refunds import day_refunds # noqa: E402 (3.3e: refunds shown apart from revenue) from services.refunds import day_refunds # noqa: E402 (3.3e: refunds shown apart from revenue)
from services import csv_export, sales # noqa: E402 (6.12a: one way to count sales; exports for Excel)
def _item_val(item) -> float: def _item_val(item) -> float:
@@ -162,7 +164,8 @@ def shift_orders_summary(
user: User = Depends(require_reports), user: User = Depends(require_reports),
): ):
"""Items sent (added) per waiter — regardless of payment status.""" """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: if business_day_id:
q = q.join(Order).filter(Order.business_day_id == business_day_id) q = q.join(Order).filter(Order.business_day_id == business_day_id)
else: else:
@@ -208,7 +211,10 @@ def shift_orders_summary(
hours_by_waiter[wid] = hours_by_waiter.get(wid, 0.0) + delta hours_by_waiter[wid] = hours_by_waiter.get(wid, 0.0) + delta
summary: dict[int, dict] = {} summary: dict[int, dict] = {}
for item in items: for line in sales.lines(db, items): # 6.12a: net of refunds, the delivery fee left out
if line.fee or not line.kept:
continue
item = line.item
wid = item.added_by wid = item.added_by
if wid not in summary: if wid not in summary:
w = waiters_db.get(wid) w = waiters_db.get(wid)
@@ -221,8 +227,8 @@ def shift_orders_summary(
"cancellations": 0, "cancellations": 0,
"order_data": {}, "order_data": {},
} }
summary[wid]["items"] += item.quantity summary[wid]["items"] += line.quantity
val = _item_val(item) val = line.value
summary[wid]["total"] += val summary[wid]["total"] += val
oid = item.order_id oid = item.order_id
@@ -239,7 +245,7 @@ def shift_orders_summary(
summary[wid]["order_data"][oid]["total"] += val summary[wid]["order_data"][oid]["total"] += val
product_name = item.product_name product_name = item.product_name
summary[wid]["order_data"][oid]["items"].append( summary[wid]["order_data"][oid]["items"].append(
{"name": product_name, "quantity": item.quantity} {"name": product_name, "quantity": line.quantity}
) )
for item in cancelled_items: for item in cancelled_items:
@@ -262,9 +268,11 @@ def shift_orders_summary(
entry["orders"] = len(entry["order_data"]) entry["orders"] = len(entry["order_data"])
entry["order_data"] = list(entry["order_data"].values()) entry["order_data"] = list(entry["order_data"].values())
entry["hours_worked"] = round(hours_by_waiter.get(entry["waiter_id"], 0.0), 2) entry["hours_worked"] = round(hours_by_waiter.get(entry["waiter_id"], 0.0), 2)
entry["items"] = round(entry["items"], 3)
entry["total"] = round(entry["total"], 2)
result.append(entry) result.append(entry)
return {"from": start.isoformat(), "to": end.isoformat(), "waiters": result} return {"from": _dt(start), "to": _dt(end), "waiters": result}
@history_router.get("/orders/history") @history_router.get("/orders/history")
@@ -346,6 +354,7 @@ def order_history(
return None return None
return (dt.isoformat() + "Z") if dt.tzinfo is None else dt.isoformat() return (dt.isoformat() + "Z") if dt.tzinfo is None else dt.isoformat()
per_order = sales.order_totals(db, orders) # 6.12a: products net of refunds, fees apart
result = [] result = []
for o in orders: for o in orders:
items_out = [] items_out = []
@@ -362,6 +371,7 @@ def order_history(
"unit_price": float(item.unit_price), "unit_price": float(item.unit_price),
"price_adjustment": float(item.price_adjustment or 0.0), "price_adjustment": float(item.price_adjustment or 0.0),
"status": item.status, "status": item.status,
"system_key": item.system_key,
"paid_by": item.paid_by, "paid_by": item.paid_by,
"paid_by_name": _wname(item.paid_by), "paid_by_name": _wname(item.paid_by),
"paid_at": _dt_local(item.paid_at), "paid_at": _dt_local(item.paid_at),
@@ -402,6 +412,7 @@ def order_history(
"notes": o.notes, "notes": o.notes,
"business_day_id": o.business_day_id, "business_day_id": o.business_day_id,
"items": items_out, "items": items_out,
"totals": per_order[o.id].out(),
"waiters": [{"waiter_id": w.waiter_id} for w in o.waiters], "waiters": [{"waiter_id": w.waiter_id} for w in o.waiters],
"audit_logs": audit_out, "audit_logs": audit_out,
}) })
@@ -485,7 +496,7 @@ def printer_totals(
item_ids = [] item_ids = []
for item_id in item_ids: for item_id in item_ids:
item = db.query(OrderItem).filter(OrderItem.id == item_id).first() 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 summary[pid]["items"] += item.quantity
val = _item_val(item) val = _item_val(item)
summary[pid]["total"] += val summary[pid]["total"] += val
@@ -554,7 +565,7 @@ def _build_printer_block(printer_id: int, printer_name: str, logs, tables, db, m
item_ids = [] item_ids = []
for item_id in item_ids: for item_id in item_ids:
item = db.query(OrderItem).filter(OrderItem.id == item_id).first() 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 items_count += item.quantity
val = _item_val(item) val = _item_val(item)
grand_total += val grand_total += val
@@ -601,7 +612,7 @@ def print_waiter(
): ):
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
if not printer: if not printer:
raise HTTPException(status_code=404, detail="Printer not found or inactive") raise XeniaError("printer.not_found")
from_dt = history_since(body.from_dt, 'reports') from_dt = history_since(body.from_dt, 'reports')
to_dt = parse_api_datetime(body.to_dt) to_dt = parse_api_datetime(body.to_dt)
@@ -622,7 +633,7 @@ def print_waiter(
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
order_data = [] order_data = []
for o in orders: 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) total = sum(_item_val(i) for i in active_items)
order_data.append({ order_data.append({
"id": o.id, "id": o.id,
@@ -637,7 +648,7 @@ def print_waiter(
}) })
items_count = sum( 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) grand_total = sum(d["total"] for d in order_data)
@@ -665,7 +676,7 @@ def print_printer_totals(
# The physical printer that will receive the paper # The physical printer that will receive the paper
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
if not printer: if not printer:
raise HTTPException(status_code=404, detail="Printer not found or inactive") raise XeniaError("printer.not_found")
tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
@@ -762,12 +773,12 @@ def print_products(
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
if not printer: if not printer:
raise HTTPException(status_code=404, detail="Printer not found or inactive") raise XeniaError("printer.not_found")
period_label, period_is_workday = _analytics_period(body, db) period_label, period_is_workday = _analytics_period(body, db)
# Build sold-item summary # 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: if body.business_day_id:
q = q.join(Order).filter(Order.business_day_id == 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: elif body.from_dt and body.to_dt:
@@ -777,15 +788,10 @@ def print_products(
) )
items = q.all() items = q.all()
sold: dict = {} # 6.12a: the screen's numbers (net of refunds, the delivery fee left out), names as sold (D-18)
for item in items: per_product = sales.products(db, items)
pid = item.product_id sold = {pid: {"qty": round(v["qty_sold"], 3), "revenue": v["revenue"]} for pid, v in per_product.items()}
if pid not in sold: sold_names = {pid: v["product_name"] for pid, v in per_product.items()}
sold[pid] = {"qty": 0, "revenue": 0.0}
sold[pid]["qty"] += item.quantity
sold[pid]["revenue"] += _item_val(item)
sold_names, _ = _names_as_sold(items) # names as sold (D-18)
if body.mode == "full": if body.mode == "full":
# All active products, 0-sold included (unsold ones under their current name), # All active products, 0-sold included (unsold ones under their current name),
# plus anything sold that's no longer active # plus anything sold that's no longer active
@@ -827,11 +833,11 @@ def print_categories(
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
if not printer: if not printer:
raise HTTPException(status_code=404, detail="Printer not found or inactive") raise XeniaError("printer.not_found")
period_label, period_is_workday = _analytics_period(body, db) 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: if body.business_day_id:
q = q.join(Order).filter(Order.business_day_id == 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: elif body.from_dt and body.to_dt:
@@ -841,20 +847,10 @@ def print_categories(
) )
items = q.all() items = q.all()
prod_names, cat_names = _names_as_sold(items) # 6.12a: the screen's numbers (net of refunds, fees left out), as sold (D-18)
# summary[cid] = {name, units_sold, revenue, products: {pid: {name, qty, revenue}}} summary: dict = {cid: {"name": v["category_name"], "units_sold": round(v["units_sold"], 3), "revenue": v["revenue"],
summary: dict = {} "products": {pid: {**p, "qty": round(p["qty"], 3)} for pid, p in v["products"].items()}}
for item in items: for cid, v in sales.categories(db, items).items()}
cid = item.category_id # as sold (D-18)
pid = item.product_id
if cid not in summary:
summary[cid] = {"name": cat_names.get(cid) or "—", "units_sold": 0, "revenue": 0.0, "products": {}}
summary[cid]["units_sold"] += item.quantity
summary[cid]["revenue"] += _item_val(item)
if pid not in summary[cid]["products"]:
summary[cid]["products"][pid] = {"name": prod_names[pid], "qty": 0, "revenue": 0.0}
summary[cid]["products"][pid]["qty"] += item.quantity
summary[cid]["products"][pid]["revenue"] += _item_val(item)
total_rev = sum(v["revenue"] for v in summary.values()) total_rev = sum(v["revenue"] for v in summary.values())
total_qty = sum(v["units_sold"] for v in summary.values()) total_qty = sum(v["units_sold"] for v in summary.values())
@@ -899,7 +895,7 @@ def print_tables(
): ):
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
if not printer: if not printer:
raise HTTPException(status_code=404, detail="Printer not found or inactive") raise XeniaError("printer.not_found")
period_label, period_is_workday = _analytics_period(body, db) period_label, period_is_workday = _analytics_period(body, db)
@@ -913,28 +909,9 @@ def print_tables(
) )
orders = q.all() orders = q.all()
tables_db = {t.id: t for t in db.query(Table).all()} # 6.12a: the screen's numbers
summary: dict = {} table_list = [{"name": t["table_name"] or "—", "order_count": t["order_count"], "revenue": t["revenue"],
for order in orders: "avg_duration_minutes": t["avg_duration_minutes"]} for t in _table_summary(db, orders)]
tid = order.table_id
if tid not in summary:
t = tables_db.get(tid)
summary[tid] = {
"name": (t.label or f"T{t.number}") if t else f"#{tid}",
"order_count": 0, "revenue": 0.0, "durations": [],
}
summary[tid]["order_count"] += 1
summary[tid]["revenue"] += sum(_item_val(i) for i in order.items if i.status in ("active", "paid"))
if order.closed_at and order.opened_at:
summary[tid]["durations"].append((order.closed_at - order.opened_at).total_seconds() / 60)
table_list = []
for entry in summary.values():
durations = entry.pop("durations")
entry["avg_duration_minutes"] = round(sum(durations) / len(durations), 1) if durations else None
entry["revenue"] = round(entry["revenue"], 2)
table_list.append(entry)
table_list.sort(key=lambda x: x["revenue"], reverse=True)
report = { report = {
"mode": body.mode, "mode": body.mode,
@@ -997,7 +974,7 @@ def product_performance(
from models.product import Product from models.product import Product
from models.waste import WasteLog 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') _since = history_since(from_dt, 'reports')
if _since: if _since:
q = q.filter(OrderItem.added_at >= _since) q = q.filter(OrderItem.added_at >= _since)
@@ -1027,37 +1004,8 @@ def product_performance(
waste_by_product[pid]["waste_qty"] += w.quantity waste_by_product[pid]["waste_qty"] += w.quantity
waste_by_product[pid]["waste_cost"] += w.total_cost or 0.0 waste_by_product[pid]["waste_cost"] += w.total_cost or 0.0
sold_names, _ = _names_as_sold(items) # 6.12a: net of refunds, the delivery fee left out (services/sales.py); the category it was sold in (D-18)
summary: dict = {} summary: dict = sales.products(db, items, category_id)
for item in items:
pid = item.product_id
if category_id and item.category_id != category_id: # the category it was sold in (D-18)
continue
if pid not in summary:
summary[pid] = {
"product_id": pid,
"product_name": sold_names[pid],
"category_id": item.category_id,
"qty_sold": 0,
"revenue": 0.0,
"total_cost": 0.0,
"trackable_profit": 0.0,
"uncosted_revenue": 0.0,
"uncosted_items": 0,
"order_ids": set(),
}
qty = item.quantity
revenue = _item_val(item)
summary[pid]["qty_sold"] += qty
summary[pid]["revenue"] += revenue
summary[pid]["order_ids"].add(item.order_id)
if item.unit_cost is not None:
cost = item.unit_cost * qty
summary[pid]["total_cost"] += cost
summary[pid]["trackable_profit"] += revenue - cost
else:
summary[pid]["uncosted_revenue"] += revenue
summary[pid]["uncosted_items"] += qty
# Also include products that only have waste (not sold) in the period # Also include products that only have waste (not sold) in the period
for pid, wdata in waste_by_product.items(): for pid, wdata in waste_by_product.items():
@@ -1069,7 +1017,7 @@ def product_performance(
"product_id": pid, "product_id": pid,
"product_name": product.name if product else f"#{pid}", "product_name": product.name if product else f"#{pid}",
"category_id": product.primary_category_id if product else None, "category_id": product.primary_category_id if product else None,
"qty_sold": 0, "revenue": 0.0, "total_cost": 0.0, "trackable_profit": 0.0, "qty_sold": 0, "revenue": 0.0, "refunded": 0.0, "total_cost": 0.0, "trackable_profit": 0.0,
"uncosted_revenue": 0.0, "uncosted_items": 0, "order_ids": set(), "uncosted_revenue": 0.0, "uncosted_items": 0, "order_ids": set(),
} }
@@ -1078,7 +1026,10 @@ def product_performance(
pid = entry["product_id"] pid = entry["product_id"]
wdata = waste_by_product.get(pid, {"waste_qty": 0.0, "waste_cost": 0.0}) wdata = waste_by_product.get(pid, {"waste_qty": 0.0, "waste_cost": 0.0})
entry["order_count"] = len(entry.pop("order_ids")) entry["order_count"] = len(entry.pop("order_ids"))
entry["qty_sold"] = round(entry["qty_sold"], 3)
entry["uncosted_items"] = round(entry["uncosted_items"], 3)
entry["revenue"] = round(entry["revenue"], 2) entry["revenue"] = round(entry["revenue"], 2)
entry["refunded"] = round(entry["refunded"], 2)
entry["total_cost"] = round(entry["total_cost"], 2) entry["total_cost"] = round(entry["total_cost"], 2)
entry["trackable_profit"] = round(entry["trackable_profit"], 2) entry["trackable_profit"] = round(entry["trackable_profit"], 2)
entry["uncosted_revenue"] = round(entry["uncosted_revenue"], 2) entry["uncosted_revenue"] = round(entry["uncosted_revenue"], 2)
@@ -1113,38 +1064,34 @@ def table_performance(
q = q.filter(Order.business_day_id == business_day_id) q = q.filter(Order.business_day_id == business_day_id)
orders = q.all() orders = q.all()
tables_db = {t.id: t for t in db.query(Table).all()} return {"tables": _table_summary(db, orders)}
def _table_summary(db, orders) -> list[dict]:
"""Per table: orders, revenue (products, net of refunds) and fees, average time (6.12a)."""
tables_db = {t.id: t for t in db.query(Table).all()}
per_order = sales.order_totals(db, orders)
summary: dict = {} summary: dict = {}
for order in orders: for order in orders:
tid = order.table_id tid = order.table_id
if tid not in summary: if tid not in summary:
t = tables_db.get(tid) t = tables_db.get(tid)
summary[tid] = { summary[tid] = {"table_id": tid, "table_name": (t.label or f"T{t.number}") if t else None,
"table_id": tid, "order_count": 0, "revenue": 0.0, "fees": 0.0, "durations": []}
"table_name": (t.label or f"T{t.number}") if t else f"#{tid}",
"order_count": 0,
"revenue": 0.0,
"durations": [],
}
summary[tid]["order_count"] += 1 summary[tid]["order_count"] += 1
summary[tid]["revenue"] += sum( summary[tid]["revenue"] += per_order[order.id].revenue
_item_val(i) for i in order.items if i.status in ("active", "paid") summary[tid]["fees"] += per_order[order.id].fees
)
if order.closed_at and order.opened_at: if order.closed_at and order.opened_at:
summary[tid]["durations"].append( summary[tid]["durations"].append((order.closed_at - order.opened_at).total_seconds() / 60)
(order.closed_at - order.opened_at).total_seconds() / 60
)
result = [] result = []
for entry in summary.values(): for entry in summary.values():
durations = entry.pop("durations") durations = entry.pop("durations")
entry["avg_duration_minutes"] = round(sum(durations) / len(durations), 1) if durations else None entry["avg_duration_minutes"] = round(sum(durations) / len(durations), 1) if durations else None
entry["revenue"] = round(entry["revenue"], 2) entry["revenue"] = round(entry["revenue"], 2)
entry["fees"] = round(entry["fees"], 2)
result.append(entry) result.append(entry)
result.sort(key=lambda x: x["revenue"], reverse=True) result.sort(key=lambda x: x["revenue"], reverse=True)
return {"tables": result} return result
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -1193,10 +1140,8 @@ def traffic_analysis(
q = q.filter(Order.business_day_id == business_day_id) q = q.filter(Order.business_day_id == business_day_id)
orders = q.all() orders = q.all()
by_hour, by_weekday = traffic_buckets( per_order = sales.order_totals(db, orders) # 6.12a: products, net of refunds
(order.opened_at, sum(_item_val(i) for i in order.items if i.status in ("active", "paid"))) by_hour, by_weekday = traffic_buckets((order.opened_at, per_order[order.id].revenue) for order in orders)
for order in orders
)
return { return {
"by_hour": list(by_hour.values()), "by_hour": list(by_hour.values()),
@@ -1231,22 +1176,8 @@ def business_days_list(
cancelled_orders = [o for o in orders if o.status == "cancelled"] cancelled_orders = [o for o in orders if o.status == "cancelled"]
day_shifts = db.query(WaiterShift).filter(WaiterShift.business_day_id == d.id).all() day_shifts = db.query(WaiterShift).filter(WaiterShift.business_day_id == d.id).all()
waiter_ids = {s.waiter_id for s in day_shifts} waiter_ids = {s.waiter_id for s in day_shifts}
revenue = 0.0 # 6.12a: everything sold that day (open orders too), net of refunds, fees apart
total_cost = 0.0 money = sales.totals(sales.lines(db, [i for o in orders for i in o.items])).out()
trackable_profit = 0.0
has_gap = False
for o in closed_orders:
for i in o.items:
if i.status not in ("active", "paid"):
continue
rev = _item_val(i)
revenue += rev
if i.unit_cost is not None:
cost = i.unit_cost * i.quantity
total_cost += cost
trackable_profit += rev - cost
else:
has_gap = True
opener = waiters_db.get(d.opened_by_id) opener = waiters_db.get(d.opened_by_id)
closer = waiters_db.get(d.closed_by_id) if d.closed_by_id else None closer = waiters_db.get(d.closed_by_id) if d.closed_by_id else None
result.append({ result.append({
@@ -1256,17 +1187,15 @@ def business_days_list(
"closed_at": _dt(d.closed_at), "closed_at": _dt(d.closed_at),
"opened_by": (opener.full_name or opener.username) if opener else None, "opened_by": (opener.full_name or opener.username) if opener else None,
"closed_by": (closer.full_name or closer.username) if closer else None, "closed_by": (closer.full_name or closer.username) if closer else None,
"opened_auto": bool(d.opened_auto), "closed_auto": bool(d.closed_auto), # 6F.8: by the system
"notes": d.notes, "notes": d.notes,
"order_count": len(orders), "order_count": len(orders),
"closed_order_count": len(closed_orders), "closed_order_count": len(closed_orders),
"cancellation_count": len(cancelled_orders), "cancellation_count": len(cancelled_orders),
"waiter_count": len(waiter_ids), "waiter_count": len(waiter_ids),
"shift_count": len(day_shifts), "shift_count": len(day_shifts),
"revenue": round(revenue, 2), **money,
"refunds": day_refunds(db, d.id), "refunds": day_refunds(db, d.id),
"total_cost": round(total_cost, 2),
"trackable_profit": round(trackable_profit, 2),
"has_gap": has_gap,
}) })
return {"business_days": result} return {"business_days": result}
@@ -1288,37 +1217,21 @@ def current_business_day(
WaiterShift.business_day_id == day.id, WaiterShift.business_day_id == day.id,
WaiterShift.ended_at == None, WaiterShift.ended_at == None,
).all() ).all()
revenue = 0.0 day_lines = sales.lines(db, [i for o in orders for i in o.items])
total_cost = 0.0 money = sales.totals(day_lines).out() # 6.12a: everything sold so far, net of refunds, fees apart
trackable_profit = 0.0
has_gap = False
for o in closed_orders:
for i in o.items:
if i.status not in ("active", "paid"):
continue
rev = _item_val(i)
revenue += rev
if i.unit_cost is not None:
cost = i.unit_cost * i.quantity
total_cost += cost
trackable_profit += rev - cost
else:
has_gap = True
item_counts: dict = {} item_counts: dict = {}
for o in orders: item_names: dict = {}
if o.status == "cancelled": for line in day_lines:
if line.fee or not line.kept:
continue continue
for item in o.items: pid = line.item.product_id
if item.status in ("active", "paid"): item_counts[pid] = item_counts.get(pid, 0) + line.quantity
pid = item.product_id item_names[pid] = line.item.product_name
item_counts[pid] = item_counts.get(pid, 0) + item.quantity
top_product_id = max(item_counts, key=item_counts.get) if item_counts else None top_product_id = max(item_counts, key=item_counts.get) if item_counts else None
top_product = None top_product = None
if top_product_id: if top_product_id:
from models.product import Product top_product = {"id": top_product_id, "name": item_names.get(top_product_id) or f"#{top_product_id}", "qty": round(item_counts[top_product_id], 3)}
p = db.query(Product).filter(Product.id == top_product_id).first()
top_product = {"id": top_product_id, "name": p.name if p else f"#{top_product_id}", "qty": item_counts[top_product_id]}
# Count cancelled items (individual items cancelled, across all orders in this day) # Count cancelled items (individual items cancelled, across all orders in this day)
all_order_ids = [o.id for o in orders] all_order_ids = [o.id for o in orders]
@@ -1339,11 +1252,9 @@ def current_business_day(
"business_day": { "business_day": {
"id": day.id, "id": day.id,
"opened_at": _dt(day.opened_at), "opened_at": _dt(day.opened_at),
"revenue": round(revenue, 2), **money,
"refunds": day_refunds(db, day.id), "refunds": day_refunds(db, day.id),
"total_cost": round(total_cost, 2), "tab_received": tab_books.for_day(db, day.id)["received"], # 6.13c: money paid on tabs today
"trackable_profit": round(trackable_profit, 2),
"has_gap": has_gap,
"orders_closed": len(closed_orders), "orders_closed": len(closed_orders),
"orders_open": len(open_orders), "orders_open": len(open_orders),
"active_waiters": len(active_shifts), "active_waiters": len(active_shifts),
@@ -1367,13 +1278,14 @@ def revenue_trends(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_reports), user: User = Depends(require_reports),
): ):
q = db.query(Order).filter(Order.status.in_(["closed", "paid"])) q = db.query(Order).filter(Order.status != "cancelled") # 6.12a: what was sold, open orders too
_since = history_since(from_dt, 'reports') _since = history_since(from_dt, 'reports')
if _since: if _since:
q = q.filter(Order.opened_at >= _since) q = q.filter(Order.opened_at >= _since)
if to_dt: if to_dt:
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt)) q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
orders = q.all() orders = q.all()
per_order = sales.order_totals(db, orders)
# Bucket by business date (D-11): the stored date of the order's business day, # Bucket by business date (D-11): the stored date of the order's business day,
# or computed from opened_at for orders outside a business day. # or computed from opened_at for orders outside a business day.
@@ -1390,21 +1302,18 @@ def revenue_trends(
key = dt.strftime("%Y-%m-%d") key = dt.strftime("%Y-%m-%d")
if key not in buckets: if key not in buckets:
buckets[key] = {"date": key, "revenue": 0.0, "profit": 0.0, "has_gap": False, "orders": 0} buckets[key] = {"date": key, "revenue": 0.0, "fees": 0.0, "profit": 0.0, "has_gap": False, "orders": 0}
for i in order.items: t = per_order[order.id]
if i.status not in ("active", "paid"): buckets[key]["revenue"] += t.revenue
continue buckets[key]["fees"] += t.fees
rev = _item_val(i) buckets[key]["profit"] += t.profit
buckets[key]["revenue"] += rev buckets[key]["has_gap"] = buckets[key]["has_gap"] or t.has_gap
if i.unit_cost is not None:
buckets[key]["profit"] += rev - i.unit_cost * i.quantity
else:
buckets[key]["has_gap"] = True
buckets[key]["orders"] += 1 buckets[key]["orders"] += 1
arr = sorted(buckets.values(), key=lambda x: x["date"]) arr = sorted(buckets.values(), key=lambda x: x["date"])
for d in arr: for d in arr:
d["revenue"] = round(d["revenue"], 2) d["revenue"] = round(d["revenue"], 2)
d["fees"] = round(d["fees"], 2)
d["profit"] = round(d["profit"], 2) d["profit"] = round(d["profit"], 2)
if granularity == "daily": if granularity == "daily":
@@ -1419,17 +1328,6 @@ def revenue_trends(
# Category performance # Category performance
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def _names_as_sold(items) -> tuple[dict, dict]:
"""{product_id: name}, {category_id: name} from the order items' snapshots (D-18, CS-4).
If a product or category was renamed within the period, the newest name sold wins."""
pnames, cnames = {}, {}
for it in sorted(items, key=lambda i: (i.added_at is None, i.added_at, i.id)):
pnames[it.product_id] = it.product_name
if it.category_id is not None:
cnames[it.category_id] = it.category_name
return pnames, cnames
@router.get("/categories/performance") @router.get("/categories/performance")
def category_performance( def category_performance(
from_dt: Optional[str] = Query(default=None, alias="from"), from_dt: Optional[str] = Query(default=None, alias="from"),
@@ -1440,7 +1338,7 @@ def category_performance(
): ):
from models.product import Product, Category 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') _since = history_since(from_dt, 'reports')
if _since: if _since:
q = q.filter(OrderItem.added_at >= _since) q = q.filter(OrderItem.added_at >= _since)
@@ -1451,43 +1349,18 @@ def category_performance(
items = q.all() items = q.all()
categories_db = {c.id: c for c in db.query(Category).all()} categories_db = {c.id: c for c in db.query(Category).all()}
_, cat_names = _names_as_sold(items) # 6.12a: net of refunds, fees left out; the category it was in when sold (D-18)
summary: dict = sales.categories(db, items)
summary: dict = {}
for item in items:
cid = item.category_id # the category it was in when sold (D-18)
if cid not in summary:
cat = categories_db.get(cid)
summary[cid] = {
"category_id": cid,
"category_name": cat_names.get(cid) or "—",
"color": cat.color if cat and hasattr(cat, "color") else None,
"units_sold": 0,
"revenue": 0.0,
"total_cost": 0.0,
"trackable_profit": 0.0,
"uncosted_revenue": 0.0,
"has_gap": False,
"product_ids": set(),
}
qty = item.quantity
rev = _item_val(item)
summary[cid]["units_sold"] += qty
summary[cid]["revenue"] += rev
summary[cid]["product_ids"].add(item.product_id)
if item.unit_cost is not None:
cost = item.unit_cost * qty
summary[cid]["total_cost"] += cost
summary[cid]["trackable_profit"] += rev - cost
else:
summary[cid]["uncosted_revenue"] += rev
summary[cid]["has_gap"] = True
total_rev = sum(v["revenue"] for v in summary.values()) total_rev = sum(v["revenue"] for v in summary.values())
total_profit = sum(v["trackable_profit"] for v in summary.values()) total_profit = sum(v["trackable_profit"] for v in summary.values())
result = [] result = []
for entry in summary.values(): for entry in summary.values():
entry["product_count"] = len(entry.pop("product_ids")) cat = categories_db.get(entry["category_id"])
entry["color"] = cat.color if cat is not None else None
entry["product_count"] = len(entry.pop("products"))
entry["units_sold"] = round(entry["units_sold"], 3)
entry["refunded"] = round(entry["refunded"], 2)
entry["revenue"] = round(entry["revenue"], 2) entry["revenue"] = round(entry["revenue"], 2)
entry["total_cost"] = round(entry["total_cost"], 2) entry["total_cost"] = round(entry["total_cost"], 2)
entry["trackable_profit"] = round(entry["trackable_profit"], 2) entry["trackable_profit"] = round(entry["trackable_profit"], 2)
@@ -1514,7 +1387,7 @@ def cancellations_log(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_reports), user: User = Depends(require_reports),
): ):
q = db.query(OrderItem).filter(OrderItem.status == "cancelled") q = db.query(OrderItem).filter(OrderItem.status == "cancelled").options(selectinload(OrderItem.order))
# Date filter on cancelled_at if available, otherwise fall back to added_at # Date filter on cancelled_at if available, otherwise fall back to added_at
dt_from = history_since(from_dt, 'reports') # clamped even without a "from" (D-6) dt_from = history_since(from_dt, 'reports') # clamped even without a "from" (D-6)
@@ -1544,16 +1417,9 @@ def cancellations_log(
items = q.order_by(OrderItem.added_at.desc()).all() items = q.order_by(OrderItem.added_at.desc()).all()
waiters_db = {u.id: u for u in db.query(User).all()} waiters_db = {u.id: u for u in db.query(User).all()}
tables_db = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} tables_db = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()}
orders_cache = {}
def _get_order(oid):
if oid not in orders_cache:
orders_cache[oid] = db.query(Order).filter(Order.id == oid).first()
return orders_cache[oid]
result = [] result = []
for item in items: for item in items:
order = _get_order(item.order_id) order = item.order # loaded with the items (selectinload above)
table_name = tables_db.get(order.table_id, f"#{order.table_id}") if order else "—" table_name = tables_db.get(order.table_id, f"#{order.table_id}") if order else "—"
waiter = waiters_db.get(item.added_by) waiter = waiters_db.get(item.added_by)
waiter_name = (waiter.full_name or waiter.username) if waiter else f"#{item.added_by}" waiter_name = (waiter.full_name or waiter.username) if waiter else f"#{item.added_by}"
@@ -1639,7 +1505,7 @@ def printer_history(
order_total = sum( order_total = sum(
_item_val(i) _item_val(i)
for i in order.items 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: if log.success and log.order_id not in seen_order_totals:
seen_order_totals[log.order_id] = order_total seen_order_totals[log.order_id] = order_total
@@ -1721,30 +1587,6 @@ def meta_products(
# CSV export endpoints # CSV export endpoints
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def _csv_response_fields(rows: list, fields: list, filename: str) -> StreamingResponse:
output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=fields)
writer.writeheader()
writer.writerows(rows)
return StreamingResponse(iter([output.getvalue()]), media_type="text/csv",
headers={"Content-Disposition": f'attachment; filename="{filename}"'})
def _csv_response(rows: list, filename: str) -> StreamingResponse:
if not rows:
rows = [{}]
output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=list(rows[0].keys()))
writer.writeheader()
writer.writerows(rows)
output.seek(0)
return StreamingResponse(
iter([output.getvalue()]),
media_type="text/csv",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
@router.get("/shifts/export") @router.get("/shifts/export")
def shifts_export( def shifts_export(
waiter_id: Optional[int] = None, waiter_id: Optional[int] = None,
@@ -1754,26 +1596,18 @@ def shifts_export(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_reports), user: User = Depends(require_reports),
): ):
"""Shifts as CSV (6.12a: venue time, the zone in the header; csv_export)."""
data = shifts_report(waiter_id=waiter_id, business_day_id=business_day_id, from_dt=from_dt, to_dt=to_dt, active_only=False, db=db, user=user) data = shifts_report(waiter_id=waiter_id, business_day_id=business_day_id, from_dt=from_dt, to_dt=to_dt, active_only=False, db=db, user=user)
rows = [] rows = [{
for s in data["shifts"]: "id": s["id"], "waiter": s["waiter_name"], "started_at": s["started_at"], "ended_at": s["ended_at"],
rows.append({ "duration_hours": s.get("duration_hours"), "hourly_rate": s.get("hourly_rate_snapshot"), "shift_pay": s.get("shift_pay"),
"id": s["id"], "starting_cash": s["starting_cash"], "total_collected": s["total_collected"], "net_to_deliver": s["net_to_deliver"],
"waiter": s["waiter_name"], "counted_cash_end": s.get("counted_cash_end"), "cash_discrepancy": s.get("cash_discrepancy"),
"started_at": s["started_at"],
"ended_at": s["ended_at"] or "",
"duration_hours": s.get("duration_hours", ""),
"hourly_rate": s.get("hourly_rate_snapshot", ""),
"shift_pay": s.get("shift_pay", ""),
"counted_cash_end": s.get("counted_cash_end", ""),
"cash_discrepancy": s.get("cash_discrepancy", ""),
"starting_cash": s["starting_cash"],
"total_collected": s["total_collected"],
"net_to_deliver": s["net_to_deliver"],
"status": "active" if s["is_active"] else "ended", "status": "active" if s["is_active"] else "ended",
}) } for s in data["shifts"]]
date_str = (from_dt or "")[:10] fields = ["id", "waiter", "started_at", "ended_at", "duration_hours", "hourly_rate", "shift_pay", "starting_cash",
return _csv_response(rows, f"shifts-{date_str}.csv") "total_collected", "net_to_deliver", "counted_cash_end", "cash_discrepancy", "status"]
return csv_export.response(db, rows, fields, f"shifts-{(from_dt or '')[:10]}.csv", times=("started_at", "ended_at"))
@router.get("/orders/export") @router.get("/orders/export")
@@ -1787,23 +1621,17 @@ def orders_export(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_reports), user: User = Depends(require_reports),
): ):
"""Orders as CSV, same filters as GET /orders/history (KI-008: it read the history's """Orders as CSV, same filters as GET /orders/history: products (net of refunds), the
dicts as ORM rows and always failed; business_day_id was ignored). Times are UTC ISO, delivery fee apart, what was refunded (6.12a), times in venue time."""
like the other exports."""
orders = order_history(from_date=from_date, to_date=to_date, waiter_id=waiter_id, order_status=order_status, orders = order_history(from_date=from_date, to_date=to_date, waiter_id=waiter_id, order_status=order_status,
table_id=table_id, business_day_id=business_day_id, page=1, page_size=10000, db=db, user=user) table_id=table_id, business_day_id=business_day_id, page=1, page_size=10000, db=db, user=user)
rows = [{ rows = [{
"id": o["id"], "id": o["id"], "table": o["table_name"] or "", "waiter": o["opened_by_name"] or "",
"table": o["table_name"] or "", "opened_at": o["opened_at"], "closed_at": o["closed_at"], "status": o["status"],
"waiter": o["opened_by_name"] or "", "products": o["totals"]["revenue"], "fees": o["totals"]["fees"], "refunded": o["totals"]["refunded"], "total": o["totals"]["takings"],
"opened_at": o["opened_at"] or "",
"closed_at": o["closed_at"] or "",
"status": o["status"],
"total": round(sum((i["unit_price"] + i["price_adjustment"]) * i["quantity"]
for i in o["items"] if i["status"] in ("active", "paid")), 2),
} for o in orders] } for o in orders]
fields = ["id", "table", "waiter", "opened_at", "closed_at", "status", "total"] # header even when empty fields = ["id", "table", "waiter", "opened_at", "closed_at", "status", "products", "fees", "refunded", "total"]
return _csv_response_fields(rows, fields, f"orders-{(from_date or '')[:10]}.csv") return csv_export.response(db, rows, fields, f"orders-{(from_date or '')[:10]}.csv", times=("opened_at", "closed_at"))
@router.get("/products/export") @router.get("/products/export")
@@ -1816,16 +1644,8 @@ def products_export(
user: User = Depends(require_reports), user: User = Depends(require_reports),
): ):
data = product_performance(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, category_id=category_id, db=db, user=user) data = product_performance(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, category_id=category_id, db=db, user=user)
rows = [{ fields = ["product_id", "product_name", "category_id", "qty_sold", "revenue", "refunded", "total_cost", "trackable_profit", "order_count"]
"product_id": p["product_id"], return csv_export.response(db, data["products"], fields, f"products-{(from_dt or '')[:10]}.csv")
"product_name": p["product_name"],
"category_id": p.get("category_id", ""),
"qty_sold": p["qty_sold"],
"revenue": p["revenue"],
"order_count": p["order_count"],
} for p in data["products"]]
date_str = (from_dt or "")[:10]
return _csv_response(rows, f"products-{date_str}.csv")
@router.get("/printers/export") @router.get("/printers/export")
@@ -1838,17 +1658,10 @@ def printers_export(
user: User = Depends(require_reports), user: User = Depends(require_reports),
): ):
data = printer_history(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, printer_id=printer_id, db=db, user=user) data = printer_history(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, printer_id=printer_id, db=db, user=user)
rows = [{ rows = [{"id": r["id"], "printed_at": r["printed_at"], "printer": r["printer_name"], "order_id": r["order_id"],
"id": r["id"], "table": r["table"], "success": r["success"], "error_message": r.get("error_message") or ""} for r in data["logs"]]
"printed_at": r["printed_at"], fields = ["id", "printed_at", "printer", "order_id", "table", "success", "error_message"]
"printer": r["printer_name"], return csv_export.response(db, rows, fields, f"printer-history-{(from_dt or '')[:10]}.csv", times=("printed_at",))
"order_id": r["order_id"],
"table": r["table"],
"success": r["success"],
"error_message": r.get("error_message") or "",
} for r in data["logs"]]
date_str = (from_dt or "")[:10]
return _csv_response(rows, f"printer-history-{date_str}.csv")
@router.get("/cancellations/export") @router.get("/cancellations/export")
@@ -1861,20 +1674,11 @@ def cancellations_export(
user: User = Depends(require_reports), user: User = Depends(require_reports),
): ):
data = cancellations_log(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, waiter_id=waiter_id, db=db, user=user) data = cancellations_log(from_dt=from_dt, to_dt=to_dt, business_day_id=business_day_id, waiter_id=waiter_id, db=db, user=user)
rows = [{ rows = [{"id": c["id"], "order_id": c["order_id"], "table": c["table"], "waiter": c["waiter_name"], "product": c["product_name"],
"id": c["id"], "quantity": c["quantity"], "value": c["value"], "cancelled_by": c.get("cancelled_by") or "",
"order_id": c["order_id"], "reason": c.get("cancel_reason") or "", "cancelled_at": c["cancelled_at"]} for c in data["cancellations"]]
"table": c["table"], fields = ["id", "order_id", "table", "waiter", "product", "quantity", "value", "cancelled_by", "reason", "cancelled_at"]
"waiter": c["waiter_name"], return csv_export.response(db, rows, fields, f"cancellations-{(from_dt or '')[:10]}.csv", times=("cancelled_at",))
"product": c["product_name"],
"quantity": c["quantity"],
"value": c["value"],
"cancelled_by": c.get("cancelled_by") or "",
"reason": c.get("cancel_reason") or "",
"cancelled_at": c["cancelled_at"],
} for c in data["cancellations"]]
date_str = (from_dt or "")[:10]
return _csv_response(rows, f"cancellations-{date_str}.csv")
# ── Prep Zones report ────────────────────────────────────────────────────────── # ── Prep Zones report ──────────────────────────────────────────────────────────
@@ -1902,7 +1706,7 @@ def prep_zones_report(
product_zone_map[product.id].append(zone.id) product_zone_map[product.id].append(zone.id)
# Query order items in the requested range # Query order items in the requested range
q = db.query(OrderItem).join(Order) q = db.query(OrderItem).join(Order).options(contains_eager(OrderItem.order))
_since = history_since(from_dt, 'reports') _since = history_since(from_dt, 'reports')
if _since: if _since:
q = q.filter(Order.opened_at >= _since) q = q.filter(Order.opened_at >= _since)
@@ -1910,7 +1714,7 @@ def prep_zones_report(
q = q.filter(Order.opened_at <= parse_api_datetime(to_dt)) q = q.filter(Order.opened_at <= parse_api_datetime(to_dt))
if business_day_id: if business_day_id:
q = q.filter(Order.business_day_id == 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() items = q.all()
# Aggregate per zone # Aggregate per zone
@@ -2007,11 +1811,11 @@ def print_prep_zone(
): ):
printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first() printer = db.query(Printer).filter(Printer.id == body.printer_id, Printer.is_active == True).first()
if not printer: if not printer:
raise HTTPException(status_code=404, detail="Printer not found or inactive") raise XeniaError("printer.not_found")
zone = db.query(PrepZone).filter(PrepZone.id == body.zone_id).first() zone = db.query(PrepZone).filter(PrepZone.id == body.zone_id).first()
if not zone: if not zone:
raise HTTPException(status_code=404, detail="Prep zone not found") raise XeniaError("prep_zone.not_found")
# Resolve period label # Resolve period label
if body.business_day_id: if body.business_day_id:
@@ -2036,7 +1840,7 @@ def print_prep_zone(
q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt)) q = q.filter(Order.opened_at <= parse_api_datetime(body.to_dt))
if body.business_day_id: if body.business_day_id:
q = q.filter(Order.business_day_id == 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() items = q.all()
product_counts: dict[str, dict] = {} product_counts: dict[str, dict] = {}
@@ -2069,6 +1873,133 @@ def print_prep_zone(
# Phase 2L — Discount audit report # 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") @router.get("/discounts")
def discounts_report( def discounts_report(
from_dt: Optional[str] = Query(default=None, alias="from"), from_dt: Optional[str] = Query(default=None, alias="from"),
+25 -14
View File
@@ -1,5 +1,5 @@
from core.timeutil import utcnow, venue_day_window from core.timeutil import utcnow, venue_day_window
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status, Query from fastapi import APIRouter, BackgroundTasks, Depends, status, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import List, Optional from typing import List, Optional
from datetime import datetime, timezone from datetime import datetime, timezone
@@ -12,6 +12,7 @@ from schemas.reservation import (
) )
from routers.deps import get_current_user, require_manager from routers.deps import get_current_user, require_manager
from models.user import User from models.user import User
from core.errors import XeniaError
router = APIRouter() router = APIRouter()
@@ -37,7 +38,7 @@ def create_reservation(
): ):
if body.table_id: if body.table_id:
if not db.query(Table).filter(Table.id == body.table_id, Table.is_active == True).first(): if not db.query(Table).filter(Table.id == body.table_id, Table.is_active == True).first():
raise HTTPException(status_code=400, detail="Table not found or inactive") raise XeniaError("table.not_found", status=400)
r = Reservation( r = Reservation(
guest_name=body.guest_name, guest_name=body.guest_name,
@@ -46,15 +47,21 @@ def create_reservation(
email=body.email, email=body.email,
note=body.note, note=body.note,
reserved_for=body.reserved_for, reserved_for=body.reserved_for,
table_id=body.table_id,
source=body.source, source=body.source,
online_customer_id=body.online_customer_id, online_customer_id=body.online_customer_id,
created_by_user_id=user.id, created_by_user_id=user.id,
status="pending", status="pending",
) )
if body.table_id:
from services.online_reservations import keep_table
keep_table(db, r, body.table_id) # not kept for another booking close by (6.9)
db.add(r) db.add(r)
db.commit() db.commit()
db.refresh(r) db.refresh(r)
from services.ws_bus import broadcast_sync
broadcast_sync("reservation_updated", {"reservation_id": r.id, "status": r.status, "table_id": r.table_id})
if r.table_id:
broadcast_sync("table_list_changed", {})
return _enrich(r) return _enrich(r)
@@ -71,7 +78,7 @@ def list_reservations(
try: try:
day = datetime.fromisoformat(date).date() day = datetime.fromisoformat(date).date()
except ValueError: except ValueError:
raise HTTPException(status_code=400, detail="Invalid date format") raise XeniaError("validation.datetime", status=400)
# The venue's calendar day, as a UTC window (D-11; 23 h / 25 h on DST days) # The venue's calendar day, as a UTC window (D-11; 23 h / 25 h on DST days)
start, end = venue_day_window(day) start, end = venue_day_window(day)
q = q.filter(Reservation.reserved_for >= start, Reservation.reserved_for < end) q = q.filter(Reservation.reserved_for >= start, Reservation.reserved_for < end)
@@ -106,7 +113,7 @@ def get_reservation(
): ):
r = db.query(Reservation).filter(Reservation.id == reservation_id).first() r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
if not r: if not r:
raise HTTPException(status_code=404, detail="Reservation not found") raise XeniaError("reservation.not_found", reservation_id=reservation_id)
return _enrich(r) return _enrich(r)
@@ -119,16 +126,17 @@ def update_reservation(
): ):
r = db.query(Reservation).filter(Reservation.id == reservation_id).first() r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
if not r: if not r:
raise HTTPException(status_code=404, detail="Reservation not found") raise XeniaError("reservation.not_found", reservation_id=reservation_id)
updates = body.model_dump(exclude_none=True) updates = body.model_dump(exclude_none=True)
# the table: set, changed or taken back (null) — kept for one booking at a time (6.9)
if "table_id" in updates and updates["table_id"] is not None: if "table_id" in body.model_fields_set:
if not db.query(Table).filter(Table.id == updates["table_id"], Table.is_active == True).first(): from services.online_reservations import keep_table
raise HTTPException(status_code=400, detail="Table not found or inactive") keep_table(db, r, body.table_id)
updates.pop("table_id", None)
if "status" in updates and updates["status"] not in VALID_STATUSES: if "status" in updates and updates["status"] not in VALID_STATUSES:
raise HTTPException(status_code=400, detail=f"Invalid status: {updates['status']}") raise XeniaError("validation.choice", field='status', value=updates['status'])
for field, value in updates.items(): for field, value in updates.items():
setattr(r, field, value) setattr(r, field, value)
@@ -136,6 +144,9 @@ def update_reservation(
r.updated_at = utcnow() r.updated_at = utcnow()
db.commit() db.commit()
db.refresh(r) db.refresh(r)
from services.ws_bus import broadcast_sync
broadcast_sync("reservation_updated", {"reservation_id": r.id, "status": r.status, "table_id": r.table_id})
broadcast_sync("table_list_changed", {})
return _enrich(r) return _enrich(r)
@@ -148,11 +159,11 @@ def update_reservation_status(
user: User = Depends(get_current_user), user: User = Depends(get_current_user),
): ):
if body.status not in VALID_STATUSES: if body.status not in VALID_STATUSES:
raise HTTPException(status_code=400, detail=f"Invalid status: {body.status}") raise XeniaError("validation.choice", field='status', value=body.status)
r = db.query(Reservation).filter(Reservation.id == reservation_id).first() r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
if not r: if not r:
raise HTTPException(status_code=404, detail="Reservation not found") raise XeniaError("reservation.not_found", reservation_id=reservation_id)
if r.online_order_cloud_id and r.status in ("requested", "pending") and body.status in ("arrived", "cancelled", "no_show"): if r.online_order_cloud_id and r.status in ("requested", "pending") and body.status in ("arrived", "cancelled", "no_show"):
# an online booking (phase 3S, S.6): the same steps as the counter's, and the customer's page follows # an online booking (phase 3S, S.6): the same steps as the counter's, and the customer's page follows
@@ -185,6 +196,6 @@ def delete_reservation(
): ):
r = db.query(Reservation).filter(Reservation.id == reservation_id).first() r = db.query(Reservation).filter(Reservation.id == reservation_id).first()
if not r: if not r:
raise HTTPException(status_code=404, detail="Reservation not found") raise XeniaError("reservation.not_found", reservation_id=reservation_id)
db.delete(r) db.delete(r)
db.commit() db.commit()
+90
View File
@@ -0,0 +1,90 @@
"""Scenes (owner 2026-11-21): list them (everyone in the dashboard), make, change, delete and turn
them on or off (`core.scenes.manage`). services/scenes.py says what follows a scene."""
from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Depends, Response
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from core.access.deps import require
from core.errors import XeniaError
from core.timeutil import utcnow
from database import get_db
from models.scene import Scene
from services import scenes as svc
router = APIRouter()
VIEW = "core.dashboard.access"
KEY = "core.scenes.manage"
COLOUR = r"^#[0-9a-fA-F]{6}$"
class SceneBody(BaseModel):
name: str = Field(min_length=1, max_length=60)
color: Optional[str] = Field(default=None, pattern=COLOUR)
description: Optional[str] = Field(default=None, max_length=200)
class ActiveBody(BaseModel):
active: bool
until: Optional[datetime] = None # on until then (UTC); None: until turned off
def _scene(db, sid: int) -> Scene:
s = db.get(Scene, sid)
if s is None:
raise XeniaError("scene.not_found", scene_id=sid)
return s
@router.get("")
def list_scenes(db: Session = Depends(get_db), user=Depends(require(VIEW))):
return [svc.out(s) for s in db.query(Scene).order_by(Scene.sort_order, Scene.id)]
@router.post("", status_code=201)
def create_scene(body: SceneBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = Scene(name=body.name.strip(), color=body.color, description=(body.description or "").strip() or None,
sort_order=db.query(Scene).count())
db.add(s)
db.commit()
db.refresh(s)
svc.changed(db)
return svc.out(s)
@router.put("/{scene_id}")
def update_scene(scene_id: int, body: SceneBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _scene(db, scene_id)
s.name, s.color, s.description = body.name.strip(), body.color, (body.description or "").strip() or None
db.commit()
svc.changed(db)
return svc.out(s)
@router.put("/{scene_id}/active")
def set_active(scene_id: int, body: ActiveBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _scene(db, scene_id)
if body.active and body.until is not None and svc._aware(body.until) <= utcnow():
raise XeniaError("scene.until_past")
s.is_active = body.active
s.activated_at = utcnow() if body.active else None
s.until = body.until if body.active else None
db.commit()
svc.changed(db)
return svc.out(s)
@router.delete("/{scene_id}", status_code=204)
def delete_scene(scene_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""The signage lines that played only in it are turned off (they would otherwise play always)."""
s = _scene(db, scene_id)
from models.signage import SignageScheduleItem
for item in db.query(SignageScheduleItem).filter(SignageScheduleItem.scene_id == s.id):
item.scene_id = None
item.enabled = False
db.delete(s)
db.commit()
svc.changed(db)
return Response(status_code=204)
+54 -14
View File
@@ -1,7 +1,6 @@
from core.access.queries import holders_filter
from core.timeutil import to_venue, venue_day_window, venue_date from core.timeutil import to_venue, venue_day_window, venue_date
from datetime import date, datetime, timedelta, timezone from datetime import date, datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException, status, Query from fastapi import APIRouter, Depends, status, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import List, Optional from typing import List, Optional
@@ -10,9 +9,40 @@ from models.schedule import ScheduledShift
from models.shift import WaiterShift from models.shift import WaiterShift
from models.user import User from models.user import User
from schemas.schedule import ScheduledShiftCreate, ScheduledShiftUpdate, ScheduledShiftOut from schemas.schedule import ScheduledShiftCreate, ScheduledShiftUpdate, ScheduledShiftOut
from routers.deps import require_manager from routers.deps import require_manager, require_staff_manager
from core.errors import XeniaError
import re
router = APIRouter() router = APIRouter()
_HHMM = re.compile(r"^([01]\d|2[0-3]):[0-5]\d$")
def _time(value: str) -> str:
if not isinstance(value, str) or not _HHMM.match(value.strip()):
raise XeniaError("schedule.bad_time")
return value.strip()
def _minutes(t: str) -> int:
return int(t[:2]) * 60 + int(t[3:5])
def _overlaps(a_start: str, a_end: str, b_start: str, b_end: str) -> bool:
"""Same-day spans; an end at or before the start runs past midnight."""
a0, a1, b0, b1 = _minutes(a_start), _minutes(a_end), _minutes(b_start), _minutes(b_end)
a1 += 1440 if a1 <= a0 else 0
b1 += 1440 if b1 <= b0 else 0
return a0 < b1 and b0 < a1
def _check_overlap(db, user_id: int, day, start: str, end: str, skip_id: int | None = None) -> None:
"""One person can't have two shifts at the same time on one day (6.11)."""
q = db.query(ScheduledShift).filter(ScheduledShift.user_id == user_id, ScheduledShift.scheduled_date == day)
for other in q.all():
if other.id != skip_id and _overlaps(start, end, other.start_time, other.end_time):
u = other.user
raise XeniaError("schedule.overlap", name=(u.full_name or u.username) if u else f"#{user_id}",
start=other.start_time, end=other.end_time)
def _duration_hours(start: str, end: str) -> float: def _duration_hours(start: str, end: str) -> float:
@@ -70,16 +100,18 @@ def list_schedule(
def create_scheduled_shift( def create_scheduled_shift(
body: ScheduledShiftCreate, body: ScheduledShiftCreate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require_staff_manager),
): ):
target = db.query(User).filter(User.id == body.user_id, User.is_active == True).first() target = db.query(User).filter(User.id == body.user_id, User.is_active == True).first()
if not target: if not target:
raise HTTPException(status_code=404, detail="User not found") raise XeniaError("staff.not_found")
start, end = _time(body.start_time), _time(body.end_time)
_check_overlap(db, body.user_id, body.scheduled_date, start, end)
s = ScheduledShift( s = ScheduledShift(
user_id=body.user_id, user_id=body.user_id,
scheduled_date=body.scheduled_date, scheduled_date=body.scheduled_date,
start_time=body.start_time, start_time=start,
end_time=body.end_time, end_time=end,
notes=body.notes, notes=body.notes,
created_by_id=user.id, created_by_id=user.id,
) )
@@ -94,12 +126,19 @@ def update_scheduled_shift(
shift_id: int, shift_id: int,
body: ScheduledShiftUpdate, body: ScheduledShiftUpdate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require_staff_manager),
): ):
s = db.query(ScheduledShift).filter(ScheduledShift.id == shift_id).first() s = db.query(ScheduledShift).filter(ScheduledShift.id == shift_id).first()
if not s: if not s:
raise HTTPException(status_code=404, detail="Scheduled shift not found") raise XeniaError("schedule.shift_not_found")
for field, value in body.model_dump(exclude_none=True).items(): data = body.model_dump(exclude_none=True)
for k in ("start_time", "end_time"):
if k in data:
data[k] = _time(data[k])
_check_overlap(db, s.user_id, s.scheduled_date, data.get("start_time", s.start_time), data.get("end_time", s.end_time), skip_id=s.id)
if "notes" in body.model_fields_set and body.notes is not None:
data["notes"] = body.notes.strip() or None
for field, value in data.items():
setattr(s, field, value) setattr(s, field, value)
db.commit() db.commit()
db.refresh(s) db.refresh(s)
@@ -110,11 +149,11 @@ def update_scheduled_shift(
def delete_scheduled_shift( def delete_scheduled_shift(
shift_id: int, shift_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require_staff_manager),
): ):
s = db.query(ScheduledShift).filter(ScheduledShift.id == shift_id).first() s = db.query(ScheduledShift).filter(ScheduledShift.id == shift_id).first()
if not s: if not s:
raise HTTPException(status_code=404, detail="Scheduled shift not found") raise XeniaError("schedule.shift_not_found")
db.delete(s) db.delete(s)
db.commit() db.commit()
@@ -144,7 +183,8 @@ def week_schedule(
WaiterShift.started_at < week_end_dt, WaiterShift.started_at < week_end_dt,
).all() ).all()
waiters = {u.id: u for u in db.query(User).filter(holders_filter("waiter_app.access"), User.is_active == True).all()} # everyone who works here (6.11: the kitchen too, not only waiters); not support accounts
waiters = {u.id: u for u in db.query(User).filter(User.is_active == True, User.role != "superadmin").all()}
def _dt(dt): def _dt(dt):
if not dt: if not dt:
@@ -183,7 +223,7 @@ def week_schedule(
"scheduled": scheduled_out, "scheduled": scheduled_out,
"total_estimated_pay": round(total_estimated_pay, 2), "total_estimated_pay": round(total_estimated_pay, 2),
"waiters": [ "waiters": [
{"id": u.id, "name": u.full_name or u.username, "hourly_rate": u.hourly_rate} {"id": u.id, "name": u.full_name or u.username, "nickname": u.nickname, "role": u.role, "hourly_rate": u.hourly_rate}
for u in sorted(waiters.values(), key=lambda x: x.full_name or x.username) for u in sorted(waiters.values(), key=lambda x: x.full_name or x.username)
], ],
} }
+12 -3
View File
@@ -1,7 +1,7 @@
from core import i18n, timeutil from core import i18n, timeutil
from core.errors import XeniaError from core.errors import XeniaError
from core.timeutil import utcnow from core.timeutil import utcnow
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from datetime import datetime, timezone from datetime import datetime, timezone
@@ -52,11 +52,17 @@ def update_setting(
user: User = Depends(require_settings_manager), user: User = Depends(require_settings_manager),
): ):
if key not in valid_settings(): if key not in valid_settings():
raise HTTPException(status_code=400, detail=f"Unknown setting key: {key}") raise XeniaError("settings.unknown_key", key=key)
from core.modules.registry import setting_defs from core.modules.registry import setting_defs
sd = setting_defs()[key][0] sd = setting_defs()[key][0]
if (sd.type == "enum" and body.value not in sd.choices) or (sd.type == "bool" and body.value not in ("true", "false")) or (sd.type == "int" and not body.value.lstrip("-").isdigit()): if (sd.type == "enum" and body.value not in sd.choices) or (sd.type == "bool" and body.value not in ("true", "false")) or (sd.type == "int" and not body.value.lstrip("-").isdigit()):
raise XeniaError("validation.setting_value", key=key, value=body.value) raise XeniaError("validation.setting_value", key=key, value=body.value)
if sd.type == "json": # 6.14a: a broken JSON setting (courses, quick notes, table colours…) would break the apps reading it
import json
try:
json.loads(body.value)
except ValueError:
raise XeniaError("validation.setting_value", key=key, value=body.value[:40])
if key == "venue.timezone": if key == "venue.timezone":
try: try:
timeutil.validate_tz(body.value) timeutil.validate_tz(body.value)
@@ -66,7 +72,7 @@ def update_setting(
raise XeniaError("validation.unknown_language", language=body.value) raise XeniaError("validation.unknown_language", language=body.value)
if key == "business_day.rollover_hour": if key == "business_day.rollover_hour":
if not (body.value.isdigit() and 0 <= int(body.value) <= 23): if not (body.value.isdigit() and 0 <= int(body.value) <= 23):
raise HTTPException(status_code=422, detail="rollover_hour must be 0-23") raise XeniaError("validation.range", status=422, field='rollover_hour', min=0, max=23)
setting = db.query(PosSettings).filter(PosSettings.key == key).first() setting = db.query(PosSettings).filter(PosSettings.key == key).first()
if setting: if setting:
@@ -83,4 +89,7 @@ def update_setting(
timeutil.invalidate() # live: next call re-reads the setting timeutil.invalidate() # live: next call re-reads the setting
if key == "venue.language": if key == "venue.language":
i18n.invalidate() i18n.invalidate()
if key in ("auth.default_login_mode", "auth.terminal_require_username"):
from services import ws_bus
ws_bus.notify_device(every_device=True) # paired screens re-read how people sign in (6F.7)
return {"key": setting.key, "value": setting.value} return {"key": setting.key, "value": setting.value}
+6 -8
View File
@@ -1,7 +1,7 @@
from core.access.deps import public from core.access.deps import public
from core.access.queries import holders_filter from core.access.queries import holders_filter
from core.timeutil import utcnow from core.timeutil import utcnow
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from pydantic import BaseModel, EmailStr from pydantic import BaseModel, EmailStr
from typing import Optional from typing import Optional
@@ -10,6 +10,7 @@ import bcrypt
from database import get_db from database import get_db
from models.user import User from models.user import User
from services.chat_service import add_user_to_system_group from services.chat_service import add_user_to_system_group
from core.errors import XeniaError
router = APIRouter() router = APIRouter()
@@ -50,19 +51,16 @@ def setup_init(body: SetupInitRequest, db: Session = Depends(get_db)):
User.is_active == True, User.is_active == True,
).first() ).first()
if has_manager: if has_manager:
raise HTTPException( raise XeniaError("setup.done")
status_code=status.HTTP_409_CONFLICT,
detail="Setup already completed — a manager account already exists.",
)
if not body.username.strip(): if not body.username.strip():
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Username is required.") raise XeniaError("auth.username_required")
if len(body.password) < 6: if len(body.password) < 6:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Password must be at least 6 characters.") raise XeniaError("auth.password_too_short", status=422, min=6)
existing = db.query(User).filter(User.username == body.username.strip()).first() existing = db.query(User).filter(User.username == body.username.strip()).first()
if existing: if existing:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Username already taken.") raise XeniaError("staff.username_taken")
from core import i18n, timeutil from core import i18n, timeutil
from core.errors import XeniaError from core.errors import XeniaError
+76 -41
View File
@@ -1,6 +1,7 @@
from core.access.deps import require
from core.access.check import holds from core.access.check import holds
from core.timeutil import utcnow from core.timeutil import utcnow
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import Optional from typing import Optional
from datetime import datetime, timezone from datetime import datetime, timezone
@@ -13,6 +14,7 @@ from models.settings import PosSettings
from models.user import User from models.user import User
from schemas.shift import StartShiftRequest, EndShiftRequest from schemas.shift import StartShiftRequest, EndShiftRequest
from routers.deps import get_current_user, require_manager from routers.deps import get_current_user, require_manager
from core.errors import XeniaError
router = APIRouter() router = APIRouter()
@@ -30,33 +32,42 @@ def _get_setting(db: Session, key: str, default: str = "true") -> str:
def compute_shift_total(shift_id: int, db: Session) -> float: def compute_shift_total(shift_id: int, db: Session) -> float:
"""What the shift took, net of its refunds (3.3e).""" """The money the shift took (cash + card: items paid and tab payments), net of its refunds."""
split = compute_shift_payment_split(shift_id, db) split = compute_shift_payment_split(shift_id, db)
return round(split["cash_sales"] + split["card_sales"] - split["cash_refunds"] - split["card_refunds"], 2) return round(split["cash_sales"] + split["card_sales"] + split["tab_cash"] + split["tab_card"]
- split["cash_refunds"] - split["card_refunds"], 2)
def compute_shift_payment_split(shift_id: int, db: Session) -> dict: def compute_shift_payment_split(shift_id: int, db: Session) -> dict:
"""cash_sales / card_sales (items paid in this shift, with their price adjustments, i.e. """The shift's money by kind (6.13c: every movement apart).
discounts) and cash_refunds / card_refunds (money this shift gave back, 3.3e)."""
cash_sales / card_sales: items paid in this shift (with their price changes) in cash / by card;
other_sales: items paid any other way (transfer, on the house…): recorded, in no drawer
(until 6.13c they were counted as cash). tab_cash / tab_card / tab_other: payments on
customers' tabs this shift received. cash_refunds / card_refunds: money it gave back (3.3e).
"""
from services import tab_books
from services.refunds import item_value, shift_refunds from services.refunds import item_value, shift_refunds
items = db.query(OrderItem).filter( items = db.query(OrderItem).filter(
OrderItem.paid_in_shift_id == shift_id, OrderItem.paid_in_shift_id == shift_id,
OrderItem.status == "paid", OrderItem.status == "paid",
).all() ).all()
cash = 0.0 out = {"cash": 0.0, "card": 0.0, "other": 0.0}
card = 0.0
for i in items: for i in items:
amount = item_value(i)
method = (i.payment_method or "cash").lower() method = (i.payment_method or "cash").lower()
if method == "card": out[method if method in ("cash", "card") else "other"] += item_value(i)
card += amount
else:
cash += amount
refunds = shift_refunds(db, shift_id) refunds = shift_refunds(db, shift_id)
return {"cash_sales": round(cash, 2), "card_sales": round(card, 2), tab = tab_books.for_shift(db, shift_id)["received"]
return {"cash_sales": round(out["cash"], 2), "card_sales": round(out["card"], 2), "other_sales": round(out["other"], 2),
"tab_cash": tab["cash"], "tab_card": tab["card"], "tab_other": tab["other"],
"cash_refunds": refunds["cash"], "card_refunds": refunds["card"]} "cash_refunds": refunds["cash"], "card_refunds": refunds["card"]}
def expected_cash(split: dict, starting_cash: float | None) -> float:
"""What should be in the drawer: starting cash + cash for items + cash on tabs − cash refunded."""
return round((starting_cash or 0.0) + split["cash_sales"] + split["tab_cash"] - split["cash_refunds"], 2)
def compute_shift_pay(shift: WaiterShift) -> dict: def compute_shift_pay(shift: WaiterShift) -> dict:
"""Return duration_hours and shift_pay. shift_pay is None if no rate snapshot.""" """Return duration_hours and shift_pay. shift_pay is None if no rate snapshot."""
now = utcnow() now = utcnow()
@@ -92,6 +103,26 @@ def compute_shift_pay(shift: WaiterShift) -> dict:
return {"duration_hours": round(duration_hours, 2), "shift_pay": shift_pay} return {"duration_hours": round(duration_hours, 2), "shift_pay": shift_pay}
def shift_activity(shift: WaiterShift, db: Session) -> dict:
"""What happened in the shift (6.13c): orders opened and items made by this person in it,
items paid in it (by anyone's lines) and items it put on customers' tabs, with their values."""
from models.order import Order
from services import tab_books
from services.sales import gross
end = shift.ended_at or utcnow()
made = db.query(OrderItem).filter(OrderItem.added_by == shift.waiter_id, OrderItem.added_at >= shift.started_at,
OrderItem.added_at <= end, OrderItem.status != "cancelled").all()
paid = db.query(OrderItem).filter(OrderItem.paid_in_shift_id == shift.id, OrderItem.status == "paid").all()
orders = db.query(Order).filter(Order.opened_by == shift.waiter_id, Order.opened_at >= shift.started_at,
Order.opened_at <= end, Order.status != "cancelled").count()
tab = tab_books.for_shift(db, shift.id)["on_tab"]
r = lambda v: round(v, 2) # noqa: E731
return {"orders": orders,
"made_items": sum(i.quantity for i in made), "made_value": r(sum(gross(i) for i in made)),
"paid_items": sum(i.quantity for i in paid), "paid_value": r(sum(gross(i) for i in paid)),
"tab_items": tab["items"], "tab_value": tab["value"]}
def _enrich_shift(shift: WaiterShift, db: Session) -> dict: def _enrich_shift(shift: WaiterShift, db: Session) -> dict:
w = shift.waiter w = shift.waiter
wname = (w.full_name or w.username) if w else f"#{shift.waiter_id}" wname = (w.full_name or w.username) if w else f"#{shift.waiter_id}"
@@ -123,7 +154,12 @@ def _enrich_shift(shift: WaiterShift, db: Session) -> dict:
"card_sales": split["card_sales"], "card_sales": split["card_sales"],
"cash_refunds": split["cash_refunds"], "cash_refunds": split["cash_refunds"],
"card_refunds": split["card_refunds"], "card_refunds": split["card_refunds"],
"net_to_deliver": round(split["cash_sales"] - split["cash_refunds"] + (shift.starting_cash or 0.0), 2), "other_sales": split["other_sales"],
"tab_cash": split["tab_cash"],
"tab_card": split["tab_card"],
"tab_other": split["tab_other"],
"net_to_deliver": expected_cash(split, shift.starting_cash),
"activity": shift_activity(shift, db),
"is_active": shift.ended_at is None, "is_active": shift.ended_at is None,
"notes": shift.notes, "notes": shift.notes,
"hourly_rate_snapshot": shift.hourly_rate_snapshot, "hourly_rate_snapshot": shift.hourly_rate_snapshot,
@@ -134,9 +170,8 @@ def _enrich_shift(shift: WaiterShift, db: Session) -> dict:
"cancellation_value": cancellation_value, "cancellation_value": cancellation_value,
# Phase 2E — discrepancy computed live against cash-only expected (starting_cash + cash_sales) # Phase 2E — discrepancy computed live against cash-only expected (starting_cash + cash_sales)
"counted_cash_end": shift.counted_cash_end, "counted_cash_end": shift.counted_cash_end,
"cash_discrepancy": round( "cash_discrepancy": round(shift.counted_cash_end - expected_cash(split, shift.starting_cash), 2)
shift.counted_cash_end - (split["cash_sales"] - split["cash_refunds"] + (shift.starting_cash or 0.0)), 2 if shift.counted_cash_end is not None else None,
) if shift.counted_cash_end is not None else None,
"breaks": [ "breaks": [
{"id": b.id, "shift_id": b.shift_id, "started_at": _dt(b.started_at), "ended_at": _dt(b.ended_at)} {"id": b.id, "shift_id": b.shift_id, "started_at": _dt(b.started_at), "ended_at": _dt(b.ended_at)}
for b in shift.breaks for b in shift.breaks
@@ -163,25 +198,25 @@ def start_shift(
if target_id and target_id != user.id: if target_id and target_id != user.id:
if not holds(user, "core.dashboard.access"): if not holds(user, "core.dashboard.access"):
raise HTTPException(status_code=403, detail="Only managers can start shifts for other staff") raise XeniaError("shift.others_need_manager")
target = db.query(User).filter(User.id == target_id, User.is_active == True).first() target = db.query(User).filter(User.id == target_id, User.is_active == True).first()
if not target: if not target:
raise HTTPException(status_code=404, detail="Staff member not found") raise XeniaError("staff.not_found")
else: else:
target_id = user.id target_id = user.id
if not holds(user, "core.dashboard.access") and _get_setting(db, "shifts.waiter_self_start") != "true": if not holds(user, "core.dashboard.access") and _get_setting(db, "shifts.waiter_self_start") != "true":
raise HTTPException(status_code=403, detail="Shift start requires manager confirmation") raise XeniaError("shift.start_needs_manager")
active_day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() active_day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if not active_day: if not active_day:
raise HTTPException(status_code=400, detail="No open business day — manager must open the restaurant first") raise XeniaError("business_day.closed", status=400)
existing = db.query(WaiterShift).filter( existing = db.query(WaiterShift).filter(
WaiterShift.waiter_id == target_id, WaiterShift.waiter_id == target_id,
WaiterShift.ended_at == None, WaiterShift.ended_at == None,
).first() ).first()
if existing: if existing:
raise HTTPException(status_code=400, detail="Waiter already has an active shift") raise XeniaError("shift.already_active")
target_user = db.query(User).filter(User.id == target_id).first() target_user = db.query(User).filter(User.id == target_id).first()
shift = WaiterShift( shift = WaiterShift(
@@ -203,14 +238,14 @@ def end_shift(
user: User = Depends(get_current_user), user: User = Depends(get_current_user),
): ):
if not holds(user, "core.dashboard.access") and _get_setting(db, "shifts.waiter_self_end") != "true": if not holds(user, "core.dashboard.access") and _get_setting(db, "shifts.waiter_self_end") != "true":
raise HTTPException(status_code=403, detail="Shift end requires manager confirmation") raise XeniaError("shift.end_needs_manager")
shift = db.query(WaiterShift).filter( shift = db.query(WaiterShift).filter(
WaiterShift.waiter_id == user.id, WaiterShift.waiter_id == user.id,
WaiterShift.ended_at == None, WaiterShift.ended_at == None,
).first() ).first()
if not shift: if not shift:
raise HTTPException(status_code=404, detail="No active shift found") raise XeniaError("shift.none_active")
now = utcnow() now = utcnow()
total = compute_shift_total(shift.id, db) total = compute_shift_total(shift.id, db)
@@ -240,22 +275,22 @@ def manager_start_shift(
user: User = Depends(require_manager), user: User = Depends(require_manager),
): ):
if not body.waiter_id: if not body.waiter_id:
raise HTTPException(status_code=400, detail="waiter_id is required") raise XeniaError("validation.missing", field='waiter_id')
target = db.query(User).filter(User.id == body.waiter_id, User.is_active == True).first() target = db.query(User).filter(User.id == body.waiter_id, User.is_active == True).first()
if not target: if not target:
raise HTTPException(status_code=404, detail="Waiter not found") raise XeniaError("staff.not_found")
active_day = db.query(BusinessDay).filter(BusinessDay.status == "open").first() active_day = db.query(BusinessDay).filter(BusinessDay.status == "open").first()
if not active_day: if not active_day:
raise HTTPException(status_code=400, detail="No open business day") raise XeniaError("business_day.none_open", status=400)
existing = db.query(WaiterShift).filter( existing = db.query(WaiterShift).filter(
WaiterShift.waiter_id == body.waiter_id, WaiterShift.waiter_id == body.waiter_id,
WaiterShift.ended_at == None, WaiterShift.ended_at == None,
).first() ).first()
if existing: if existing:
raise HTTPException(status_code=400, detail="Waiter already has an active shift") raise XeniaError("shift.already_active")
shift = WaiterShift( shift = WaiterShift(
waiter_id=body.waiter_id, waiter_id=body.waiter_id,
@@ -281,7 +316,7 @@ def manager_end_shift(
WaiterShift.ended_at == None, WaiterShift.ended_at == None,
).first() ).first()
if not shift: if not shift:
raise HTTPException(status_code=404, detail="Active shift not found") raise XeniaError("shift.none_active")
now = utcnow() now = utcnow()
total = compute_shift_total(shift.id, db) total = compute_shift_total(shift.id, db)
@@ -312,17 +347,17 @@ def start_break(
): ):
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first() shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
if not shift: if not shift:
raise HTTPException(status_code=404, detail="Shift not found") raise XeniaError("shift.not_found")
if shift.waiter_id != user.id and not holds(user, "core.dashboard.access"): if shift.waiter_id != user.id and not holds(user, "core.dashboard.access"):
raise HTTPException(status_code=403, detail="Access denied") raise XeniaError("shift.not_yours")
if shift.ended_at: if shift.ended_at:
raise HTTPException(status_code=400, detail="Shift already ended") raise XeniaError("shift.ended")
open_break = db.query(ShiftBreak).filter( open_break = db.query(ShiftBreak).filter(
ShiftBreak.shift_id == shift_id, ShiftBreak.ended_at == None ShiftBreak.shift_id == shift_id, ShiftBreak.ended_at == None
).first() ).first()
if open_break: if open_break:
raise HTTPException(status_code=400, detail="Break already in progress") raise XeniaError("shift.on_break")
b = ShiftBreak(shift_id=shift_id) b = ShiftBreak(shift_id=shift_id)
db.add(b) db.add(b)
@@ -339,15 +374,15 @@ def end_break(
): ):
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first() shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
if not shift: if not shift:
raise HTTPException(status_code=404, detail="Shift not found") raise XeniaError("shift.not_found")
if shift.waiter_id != user.id and not holds(user, "core.dashboard.access"): if shift.waiter_id != user.id and not holds(user, "core.dashboard.access"):
raise HTTPException(status_code=403, detail="Access denied") raise XeniaError("shift.not_yours")
open_break = db.query(ShiftBreak).filter( open_break = db.query(ShiftBreak).filter(
ShiftBreak.shift_id == shift_id, ShiftBreak.ended_at == None ShiftBreak.shift_id == shift_id, ShiftBreak.ended_at == None
).first() ).first()
if not open_break: if not open_break:
raise HTTPException(status_code=404, detail="No active break found") raise XeniaError("shift.no_break")
open_break.ended_at = utcnow() open_break.ended_at = utcnow()
db.commit() db.commit()
@@ -382,7 +417,7 @@ def get_shift(
): ):
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first() shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
if not shift: if not shift:
raise HTTPException(status_code=404, detail="Shift not found") raise XeniaError("shift.not_found")
return _enrich_shift(shift, db) return _enrich_shift(shift, db)
@@ -390,7 +425,7 @@ def get_shift(
def delete_shift( def delete_shift(
shift_id: int, shift_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require("core.settings.manage")),
): ):
"""Permanently delete a shift, its breaks, and all orders opened during that shift.""" """Permanently delete a shift, its breaks, and all orders opened during that shift."""
from models.order import Order, OrderItem, OrderAuditLog, OrderWaiter from models.order import Order, OrderItem, OrderAuditLog, OrderWaiter
@@ -398,9 +433,9 @@ def delete_shift(
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first() shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
if not shift: if not shift:
raise HTTPException(status_code=404, detail="Shift not found") raise XeniaError("shift.not_found")
if shift.ended_at is None: if shift.ended_at is None:
raise HTTPException(status_code=400, detail="Cannot delete an active shift — end it first") raise XeniaError("shift.delete_active")
# Find all orders opened during this shift's time window by this waiter # Find all orders opened during this shift's time window by this waiter
orders = db.query(Order).filter( orders = db.query(Order).filter(
@@ -440,7 +475,7 @@ def get_shift_summary(
shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first() shift = db.query(WaiterShift).filter(WaiterShift.id == shift_id).first()
if not shift: if not shift:
raise HTTPException(status_code=404, detail="Shift not found") raise XeniaError("shift.not_found")
waiter_id = shift.waiter_id waiter_id = shift.waiter_id
File diff suppressed because it is too large Load Diff
+18 -14
View File
@@ -1,13 +1,12 @@
from core.access.deps import public from core.access.deps import public, require
from core.access.queries import holders_filter from core.access.queries import holders_filter
from core.access.deps import require
import asyncio import asyncio
import ipaddress import ipaddress
import json import json
import os import os
import socket import socket
import time import time
from fastapi import APIRouter, Depends, HTTPException, Query from fastapi import APIRouter, Depends, Query
from fastapi.responses import StreamingResponse from fastapi.responses import StreamingResponse
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@@ -27,6 +26,7 @@ from services.lan_ip import OVERRIDE_KEY, resolve_lan_ip, validate_lan_ip
from services.tls_identity import tls_info from services.tls_identity import tls_info
from services.license_state import license_state from services.license_state import license_state
from config import settings from config import settings
from core.errors import XeniaError
router = APIRouter() router = APIRouter()
@@ -165,7 +165,7 @@ def set_lan_ip_override(body: LanIpOverride, db: Session = Depends(get_db), user
try: try:
value = validate_lan_ip(body.ip) value = validate_lan_ip(body.ip)
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=422, detail=str(e)) raise XeniaError("validation.lan_ip")
if row: if row:
row.value = value row.value = value
row.updated_by_id = user.id or None row.updated_by_id = user.id or None
@@ -205,8 +205,12 @@ def list_printers(db: Session = Depends(get_db), user: User = Depends(require_ma
return db.query(Printer).all() return db.query(Printer).all()
# 6.10: adding, changing, removing and finding printers is venue set-up
_SETTINGS = require("core.settings.manage")
@router.post("/printers", response_model=PrinterOut) @router.post("/printers", response_model=PrinterOut)
def create_printer(body: PrinterCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def create_printer(body: PrinterCreate, db: Session = Depends(get_db), user: User = Depends(_SETTINGS)):
printer = Printer(**body.model_dump()) printer = Printer(**body.model_dump())
db.add(printer) db.add(printer)
db.commit() db.commit()
@@ -218,7 +222,7 @@ def create_printer(body: PrinterCreate, db: Session = Depends(get_db), user: Use
def test_printer(printer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)): def test_printer(printer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
printer = db.query(Printer).filter(Printer.id == printer_id).first() printer = db.query(Printer).filter(Printer.id == printer_id).first()
if not printer: if not printer:
raise HTTPException(status_code=404, detail="Printer not found") raise XeniaError("printer.not_found")
success, error = printer_service.send_test_print(printer.ip_address, printer.port, printer.name, printer.codepage_n) success, error = printer_service.send_test_print(printer.ip_address, printer.port, printer.name, printer.codepage_n)
return {"success": success, "error": error} return {"success": success, "error": error}
@@ -227,7 +231,7 @@ def test_printer(printer_id: int, db: Session = Depends(get_db), user: User = De
def test_order_print(printer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)): def test_order_print(printer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
printer = db.query(Printer).filter(Printer.id == printer_id).first() printer = db.query(Printer).filter(Printer.id == printer_id).first()
if not printer: if not printer:
raise HTTPException(status_code=404, detail="Printer not found") raise XeniaError("printer.not_found")
success, error = printer_service.send_test_order_print(printer.ip_address, printer.port, db, printer.line_width, printer.codepage_n) success, error = printer_service.send_test_order_print(printer.ip_address, printer.port, db, printer.line_width, printer.codepage_n)
return {"success": success, "error": error} return {"success": success, "error": error}
@@ -236,16 +240,16 @@ def test_order_print(printer_id: int, db: Session = Depends(get_db), user: User
def test_beep(printer_id: int, n1: int = 2, n2: int = 2, n3: int = 1, db: Session = Depends(get_db), user: User = Depends(require_manager)): def test_beep(printer_id: int, n1: int = 2, n2: int = 2, n3: int = 1, db: Session = Depends(get_db), user: User = Depends(require_manager)):
printer = db.query(Printer).filter(Printer.id == printer_id).first() printer = db.query(Printer).filter(Printer.id == printer_id).first()
if not printer: if not printer:
raise HTTPException(status_code=404, detail="Printer not found") raise XeniaError("printer.not_found")
success, error = printer_service.send_test_beep(printer.ip_address, printer.port, n1, n2, n3, printer.codepage_n) success, error = printer_service.send_test_beep(printer.ip_address, printer.port, n1, n2, n3, printer.codepage_n)
return {"success": success, "error": error} return {"success": success, "error": error}
@router.put("/printers/{printer_id}", response_model=PrinterOut) @router.put("/printers/{printer_id}", response_model=PrinterOut)
def update_printer(printer_id: int, body: PrinterUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)): def update_printer(printer_id: int, body: PrinterUpdate, db: Session = Depends(get_db), user: User = Depends(_SETTINGS)):
printer = db.query(Printer).filter(Printer.id == printer_id).first() printer = db.query(Printer).filter(Printer.id == printer_id).first()
if not printer: if not printer:
raise HTTPException(status_code=404, detail="Printer not found") raise XeniaError("printer.not_found")
for field, value in body.model_dump(exclude_none=True).items(): for field, value in body.model_dump(exclude_none=True).items():
setattr(printer, field, value) setattr(printer, field, value)
db.commit() db.commit()
@@ -254,10 +258,10 @@ def update_printer(printer_id: int, body: PrinterUpdate, db: Session = Depends(g
@router.delete("/printers/{printer_id}") @router.delete("/printers/{printer_id}")
def delete_printer(printer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)): def delete_printer(printer_id: int, db: Session = Depends(get_db), user: User = Depends(_SETTINGS)):
printer = db.query(Printer).filter(Printer.id == printer_id).first() printer = db.query(Printer).filter(Printer.id == printer_id).first()
if not printer: if not printer:
raise HTTPException(status_code=404, detail="Printer not found") raise XeniaError("printer.not_found")
db.delete(printer) db.delete(printer)
db.commit() db.commit()
return {"ok": True} return {"ok": True}
@@ -336,7 +340,7 @@ async def _scan_subnet_sse(subnet: str, port: int, token: str):
async def scan_printers( async def scan_printers(
subnet: str = Query(default=""), subnet: str = Query(default=""),
port: int = Query(default=9100), port: int = Query(default=9100),
user: User = Depends(require_manager), user: User = Depends(_SETTINGS),
): ):
"""SSE endpoint: scan a subnet for devices responding on the given port.""" """SSE endpoint: scan a subnet for devices responding on the given port."""
# Fall back to auto-detected subnet if none provided # Fall back to auto-detected subnet if none provided
@@ -355,7 +359,7 @@ async def scan_printers(
@router.get("/printers/scan-hints") @router.get("/printers/scan-hints")
def scan_hints(user: User = Depends(require_manager)): def scan_hints(user: User = Depends(_SETTINGS)):
"""Return auto-detected local subnets to suggest in the scan UI.""" """Return auto-detected local subnets to suggest in the scan UI."""
return {"subnets": _detect_local_subnets()} return {"subnets": _detect_local_subnets()}
+12 -17
View File
@@ -1,6 +1,6 @@
from core.access.check import holds from core.access.check import holds
from core.timeutil import utcnow from core.timeutil import utcnow
from fastapi import APIRouter, Depends, HTTPException, status, Body from fastapi import APIRouter, Depends, status, Body
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import List from typing import List
from datetime import datetime, timezone, timedelta from datetime import datetime, timezone, timedelta
@@ -34,7 +34,7 @@ def list_groups(db: Session = Depends(get_db), user: User = Depends(get_current_
@router.post("/groups", response_model=TableGroupOut, status_code=status.HTTP_201_CREATED) @router.post("/groups", response_model=TableGroupOut, status_code=status.HTTP_201_CREATED)
def create_group(body: TableGroupCreate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)): def create_group(body: TableGroupCreate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
if db.query(TableGroup).filter(TableGroup.name == body.name).first(): if db.query(TableGroup).filter(TableGroup.name == body.name).first():
raise HTTPException(status_code=400, detail="Group name already exists") raise XeniaError("table_group.name_taken")
sort_order = db.query(TableGroup).count() sort_order = db.query(TableGroup).count()
group = TableGroup(name=body.name, prefix=body.prefix, color=body.color, sort_order=sort_order) group = TableGroup(name=body.name, prefix=body.prefix, color=body.color, sort_order=sort_order)
db.add(group) db.add(group)
@@ -54,7 +54,7 @@ def reorder_groups(body: List[int] = Body(...), db: Session = Depends(get_db), u
def update_group(group_id: int, body: TableGroupUpdate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)): def update_group(group_id: int, body: TableGroupUpdate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
group = db.query(TableGroup).filter(TableGroup.id == group_id).first() group = db.query(TableGroup).filter(TableGroup.id == group_id).first()
if not group: if not group:
raise HTTPException(status_code=404, detail="Group not found") raise XeniaError("table_group.not_found")
for field, value in body.model_dump(exclude_none=True).items(): for field, value in body.model_dump(exclude_none=True).items():
setattr(group, field, value) setattr(group, field, value)
db.commit() db.commit()
@@ -66,7 +66,7 @@ def update_group(group_id: int, body: TableGroupUpdate, db: Session = Depends(ge
def delete_group(group_id: int, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)): def delete_group(group_id: int, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
group = db.query(TableGroup).filter(TableGroup.id == group_id).first() group = db.query(TableGroup).filter(TableGroup.id == group_id).first()
if not group: if not group:
raise HTTPException(status_code=404, detail="Group not found") raise XeniaError("table_group.not_found")
db.query(Table).filter(Table.group_id == group_id).update({"group_id": None}) db.query(Table).filter(Table.group_id == group_id).update({"group_id": None})
db.delete(group) db.delete(group)
db.commit() db.commit()
@@ -149,7 +149,7 @@ def create_table(body: TableCreate, db: Session = Depends(get_db), user: User =
@router.post("/batch", response_model=List[TableOut], status_code=status.HTTP_201_CREATED) @router.post("/batch", response_model=List[TableOut], status_code=status.HTTP_201_CREATED)
def batch_create_tables(body: TableBatchCreate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)): def batch_create_tables(body: TableBatchCreate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
if body.count < 1 or body.count > 200: if body.count < 1 or body.count > 200:
raise HTTPException(status_code=400, detail="Count must be between 1 and 200") raise XeniaError("validation.range", field='count', min=1, max=200)
# Group-local label numbering: find highest suffix already used in this group # Group-local label numbering: find highest suffix already used in this group
existing_in_group = ( existing_in_group = (
@@ -171,10 +171,7 @@ def batch_create_tables(body: TableBatchCreate, db: Session = Depends(get_db), u
last_n = start_label_n + body.count - 1 last_n = start_label_n + body.count - 1
worst_case = f"{body.name_prefix}{last_n}" worst_case = f"{body.name_prefix}{last_n}"
if len(worst_case) > MAX_TABLE_NAME_LENGTH: if len(worst_case) > MAX_TABLE_NAME_LENGTH:
raise HTTPException( raise XeniaError("table.name_too_long", name=worst_case, max=MAX_TABLE_NAME_LENGTH)
status_code=400,
detail=f"Table name '{worst_case}' would exceed {MAX_TABLE_NAME_LENGTH} characters. Shorten the prefix or reduce the count.",
)
created = [] created = []
for i in range(body.count): for i in range(body.count):
@@ -199,7 +196,7 @@ def batch_create_tables(body: TableBatchCreate, db: Session = Depends(get_db), u
def update_table(table_id: int, body: TableUpdate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)): def update_table(table_id: int, body: TableUpdate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
table = db.query(Table).filter(Table.id == table_id).first() table = db.query(Table).filter(Table.id == table_id).first()
if not table: if not table:
raise HTTPException(status_code=404, detail="Table not found") raise XeniaError("table.not_found")
for field, value in body.model_dump(exclude_none=True).items(): for field, value in body.model_dump(exclude_none=True).items():
setattr(table, field, value) setattr(table, field, value)
db.commit() db.commit()
@@ -211,16 +208,13 @@ def update_table(table_id: int, body: TableUpdate, db: Session = Depends(get_db)
def delete_table(table_id: int, hard: bool = False, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)): def delete_table(table_id: int, hard: bool = False, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
table = db.query(Table).filter(Table.id == table_id).first() table = db.query(Table).filter(Table.id == table_id).first()
if not table: if not table:
raise HTTPException(status_code=404, detail="Table not found") raise XeniaError("table.not_found")
active_order = db.query(Order).filter( active_order = db.query(Order).filter(
Order.table_id == table_id, Order.table_id == table_id,
Order.status.in_(["open", "partially_paid", "paid"]) Order.status.in_(["open", "partially_paid", "paid"])
).first() ).first()
if active_order: if active_order:
raise HTTPException( raise XeniaError("table.has_order")
status_code=400,
detail="Cannot delete or deactivate a table with an active order"
)
if hard: if hard:
# Delete all past (non-active) orders for this table so FK constraint doesn't block deletion. # Delete all past (non-active) orders for this table so FK constraint doesn't block deletion.
# Active orders are already blocked above. Items/waiters/print_logs cascade via ORM. # Active orders are already blocked above. Items/waiters/print_logs cascade via ORM.
@@ -238,7 +232,7 @@ def delete_table(table_id: int, hard: bool = False, db: Session = Depends(get_db
def table_status(table_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)): def table_status(table_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
table = db.query(Table).filter(Table.id == table_id).first() table = db.query(Table).filter(Table.id == table_id).first()
if not table: if not table:
raise HTTPException(status_code=404, detail="Table not found") raise XeniaError("table.not_found")
active_order = ( active_order = (
db.query(Order) db.query(Order)
.filter(Order.table_id == table_id, Order.status.in_(["open", "partially_paid", "paid"])) .filter(Order.table_id == table_id, Order.status.in_(["open", "partially_paid", "paid"]))
@@ -255,7 +249,7 @@ def table_status(table_id: int, db: Session = Depends(get_db), user: User = Depe
def update_floorplan(table_id: int, body: TableFloorplanUpdate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)): def update_floorplan(table_id: int, body: TableFloorplanUpdate, db: Session = Depends(get_db), user: User = Depends(require_tables_manager)):
table = db.query(Table).filter(Table.id == table_id).first() table = db.query(Table).filter(Table.id == table_id).first()
if not table: if not table:
raise HTTPException(status_code=404, detail="Table not found") raise XeniaError("table.not_found")
table.floor_x = body.floor_x table.floor_x = body.floor_x
table.floor_y = body.floor_y table.floor_y = body.floor_y
db.commit() db.commit()
@@ -276,6 +270,7 @@ def _table_in_zones(db: Session, user: User, table: Table) -> bool:
from core.access.deps import require as _require # noqa: E402 from core.access.deps import require as _require # noqa: E402
from core.modules.state import module_required as _module_required # noqa: E402 from core.modules.state import module_required as _module_required # noqa: E402
from core.errors import XeniaError
@router.get("/{table_id}/history", dependencies=[Depends(_module_required("history"))]) @router.get("/{table_id}/history", dependencies=[Depends(_module_required("history"))])

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