diff --git a/docs/README.md b/docs/README.md index b29c7cb..7f45149 100644 --- a/docs/README.md +++ b/docs/README.md @@ -51,6 +51,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r | `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out | | `local_backend/routers/menu_tablet.py`, `terminal/src/apps/menu-tablet/` | The menu tablet (5.7a): `GET /api/menu-tablet/menu` (a paired tablet) gives categories in the catalogue's order with their products (a product in several categories shows in each), the products once with the tablet's sales point price, photos, tags, and its device config (view compact / expanded / full, photos, descriptions, group, theme, prices of, sold out, one category, search, languages, idle reset). Menu changes send `menu_tablet.changed` (the same hook as signage). The app: search folds accents and also matches names typed in Latin letters (`latin`, `@xenia/i18n/latin`); the last menu in localStorage. **Call a waiter (5.7b):** device config `table` (ref `tables`) + `call_waiter`; `POST /api/menu-tablet/call` sends a `table_call` staff message (the open order's waiters, else the zone's; `qr_orders.waiters_for`) at most once a minute per tablet (in memory); the waiter's phone shows it with "Open the table" **Ordering at the table (6.6, D-30):** `services/tablet_orders.py` + `models/tablet_order.py` (`tablet_orders`, 0034). Device config `ordering` (off), `bill`, and per-tablet overrides `order_confirm` / `order_no_order` / `order_max_items` / `order_max_of_one` / `order_min_seconds` (-1 / `venue` = the venue's); the venue's rules are the JSON setting `menu_tablet.ordering` (`GET/PUT /api/menu-tablet/ordering`, Settings → Menu tablets). `/menu` adds `table.can_order`, `table.can_see_bill` and `ordering` (rules + `choices`: the POS product shape at in-store prices, so the tablet reuses `pos/ProductDialog`). `POST /quote` / `/order` take POS lines by id (`pos_cart.resolve_line`, never prices or discounts); every order is a `TabletOrder` row (it also times the limit); kitchen mode places it with `orders_api.add_priced_items(source="tablet")`, waiter mode leaves it `waiting` until `POST /requests/{id}/accept|decline` (`ordering.orders.open`; the phone's `TabletRequests` on the table page). Events: `tablet_order_updated` {id, table_id, status} to all (the phones refresh their list), `menu_tablet.order` to the tablet. Staff message type `tablet_order`. `GET/POST /bill`: the table's open order and asking for the bill (a `table_call` message, once a minute) | | `local_backend/routers/pricing.py`, `services/pricing.py`, `manager_dashboard/src/pages/pricing/` | Pricing (6.7): price groups, modifiers (price rules), deals, discount limits. Every set-up endpoint needs `pricing.manage` and broadcasts `pricing.changed` (the page's `useLiveQuery`); the phones keep reading rules / deals with any signed-in user. Conditions are checked on save (`_condition_ok` → `pricing.bad_condition`): an incomplete one used to raise in `services/pricing.py::_eval_condition` at quote time. Venue limits live in settings `discounts.*` (empty = no limit; `pricing.bad_limit`). The page's rules as data: `pricingLogic.js` (`tests/pricing.test.mjs`) | +| `local_backend/routers/floor_plans.py`, `services/floor_live.py`, `packages/floorplan`, manager `src/pages/floor/` | The table map (6.8, D-31): `floor_plans` / `floor_items` (0035) and the tables' `plan_id`, `floor_x/y` (centre), `width`, `height`, `rotation`, `shape`. Set-up `/api/floor-plans` (`catalog.tables.manage`; `PUT /{id}/layout` saves tables + items whole) sends `floor_plans.changed`; `GET /api/floor-plans/live` (any signed-in person, the waiter app's zone rule) gives each table's state, guests (`customer_count`), waiters and time. `@xenia/floorplan`: `FloorView` (inline styles on tokens, so the waiter app can use it), `Floor` / `Item` / `TableShape`, `geometry.js` (grid snap = positions and sizes in whole cells; `@xenia/floorplan/geometry` for node tests). Dockerfiles copy its package.json | | `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more | | `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) | | `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` | diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index 55c8d8c..d5a103e 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -224,6 +224,11 @@ CODES: dict[str, tuple[int, str]] = { "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."), "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."), diff --git a/local_backend/migrations/versions/0035_floor_plans.py b/local_backend/migrations/versions/0035_floor_plans.py new file mode 100644 index 0000000..e104130 --- /dev/null +++ b/local_backend/migrations/versions/0035_floor_plans.py @@ -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') diff --git a/local_backend/models/all.py b/local_backend/models/all.py index fd198da..7012219 100644 --- a/local_backend/models/all.py +++ b/local_backend/models/all.py @@ -42,3 +42,4 @@ import models.media # noqa: F401 Media (media library, step 5.1) import models.display_look # noqa: F401 DisplayLook (customer display looks, step 5.3) import models.signage # noqa: F401 SignagePlaylist, SignageSlide (signage, step 5.4a) import models.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) diff --git a/local_backend/models/floor_plan.py b/local_backend/models/floor_plan.py new file mode 100644 index 0000000..4a19b3b --- /dev/null +++ b/local_backend/models/floor_plan.py @@ -0,0 +1,58 @@ +"""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) + + plan = relationship("FloorPlan", back_populates="items") diff --git a/local_backend/models/table.py b/local_backend/models/table.py index d5878a1..f9972be 100644 --- a/local_backend/models/table.py +++ b/local_backend/models/table.py @@ -25,8 +25,14 @@ class Table(Base): group_id = Column(Integer, ForeignKey("table_groups.id"), nullable=True) is_active = Column(Boolean, default=True, nullable=False) seat_count = Column(Integer, nullable=True) + # its place on a floor plan (6.8, D-31; models/floor_plan.py): floor_x / floor_y = its centre + plan_id = Column(Integer, ForeignKey("floor_plans.id", ondelete="SET NULL"), nullable=True, index=True) floor_x = Column(Float, nullable=True) floor_y = Column(Float, nullable=True) + width = Column(Float, nullable=True) + height = Column(Float, nullable=True) + rotation = Column(Float, nullable=True) + shape = Column(String, nullable=True) # round | square | long # the table's QR code (phase 3S, S.7): a random token in the QR menu link; the cloud gets # only its sha256 (services/table_qr.py). A new token makes the printed code useless. qr_token = Column(String, nullable=True, unique=True) diff --git a/local_backend/modules/catalog/manifest.py b/local_backend/modules/catalog/manifest.py index 379d556..c1ab7cb 100644 --- a/local_backend/modules/catalog/manifest.py +++ b/local_backend/modules/catalog/manifest.py @@ -12,6 +12,7 @@ MODULE = Module( ), routers=( Mount('routers.tables', '/api/tables'), + Mount('routers.floor_plans', '/api/floor-plans'), Mount('routers.products', '/api/products'), Mount('routers.prep_zones', '/api/prep-zones'), Mount('routers.data_transfer', '/api/data-transfer'), diff --git a/local_backend/routers/floor_plans.py b/local_backend/routers/floor_plans.py new file mode 100644 index 0000000..dcd2a41 --- /dev/null +++ b/local_backend/routers/floor_plans.py @@ -0,0 +1,245 @@ +"""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) + + +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} 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)) + 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} diff --git a/local_backend/services/floor_live.py b/local_backend/services/floor_live.py new file mode 100644 index 0000000..c1136ac --- /dev/null +++ b/local_backend/services/floor_live.py @@ -0,0 +1,80 @@ +"""The table map's live data (plan step 6.8, D-31): for each table a person can see, its place on +a floor plan and its state now, the same for the phones, the counter and the manager. + +state free | open | paid | reserved (free, with a booking due within a few hours) +mine the person is one of its order's waiters +order {id, opened_at, guests, people (the waiters' names), total, unpaid, ready} +seats the table's seats (a suggestion, 4.8) +Which tables: the waiter app's rule (routers/tables.list_tables: managers all, staff their zones). +Which plans: those of the zones the person sees (and plans without a zone) that hold a table they +see, or every plan for a manager. +""" +from __future__ import annotations + +from sqlalchemy.orm import selectinload + +ACTIVE = ("open", "partially_paid", "paid") +UNPAID = ("active", "ready") + + +def _iso(v): + from core.timeutil import iso_z + return iso_z(v) + + +def _total(i) -> float: + return (i.unit_price + (i.price_adjustment or 0.0)) * i.quantity + + +def live_tables(db, user) -> list[dict]: + from models.order import Order + from models.user import User + from routers import tables as tables_api + from routers.floor_plans import place_out + from models.table import Table + visible = tables_api.list_tables(include_inactive=False, db=db, user=user) + ids = [t.id for t in visible] + if not ids: + return [] + rows = {t.id: t for t in db.query(Table).filter(Table.id.in_(ids)).all()} + orders = {o.table_id: o for o in db.query(Order).filter(Order.table_id.in_(ids), Order.status.in_(ACTIVE)) + .options(selectinload(Order.items), selectinload(Order.waiters)).all()} + people_ids = {w.waiter_id for o in orders.values() for w in o.waiters} + names = {u.id: u.nickname or u.full_name or u.username + for u in db.query(User).filter(User.id.in_(people_ids)).all()} if people_ids else {} + + def order_out(o): + live = [i for i in o.items if i.status in UNPAID or i.status == "paid"] + return { + "id": o.id, "status": o.status, "opened_at": _iso(o.opened_at), "guests": o.customer_count, + "total": round(sum(_total(i) for i in live), 2), + "unpaid": round(sum(_total(i) for i in live if i.status in UNPAID), 2), + "ready": sum(1 for i in live if (i.kds_status or "pending") == "done"), + "people": [names[w.waiter_id] for w in o.waiters if w.waiter_id in names], + } + + out = [] + for t in visible: + o = orders.get(t.id) + if o is not None: + state = "paid" if o.status == "paid" else "open" + else: + state = "reserved" if t.upcoming_reservation else "free" + res = t.upcoming_reservation + out.append({ + **place_out(rows[t.id]), + "state": state, + "mine": bool(o and any(w.waiter_id == user.id for w in o.waiters)), + "order": order_out(o) if o else None, + "reservation": ({"guest_name": res.guest_name, "party_size": res.party_size, "reserved_for": _iso(res.reserved_for)} + if res and not o else None), + }) + return out + + +def visible_plans(db, user, plans, tables) -> list: + from core.access.check import holds + if holds(user, "core.dashboard.access"): + return plans + used = {t["plan_id"] for t in tables if t["plan_id"] is not None} + return [p for p in plans if p.id in used] diff --git a/local_backend/tests/test_floor_plans.py b/local_backend/tests/test_floor_plans.py new file mode 100644 index 0000000..6afffbc --- /dev/null +++ b/local_backend/tests/test_floor_plans.py @@ -0,0 +1,92 @@ +"""Floor plans and the live table map (plan step 6.8, D-31).""" +import pytest + +from tests.test_live import err, owner_h # noqa: F401 (fixtures) + + +@pytest.fixture +def venue(db): + from models.table import Table, TableGroup + inside, terrace = TableGroup(name="Inside", sort_order=0), TableGroup(name="Terrace", sort_order=1) + db.add_all([inside, terrace]) + db.flush() + t = {n: Table(number=n, group_id=inside.id if n < 10 else terrace.id, seat_count=4) for n in (1, 2, 5, 11)} + db.add_all(t.values()) + db.commit() + return {"inside": inside, "terrace": terrace, **{f"t{n}": x for n, x in t.items()}} + + +def plan(client, h, **extra): + r = client.post("/api/floor-plans", headers=h, json={"name": "Ground floor", "width": 1000, "height": 600, **extra}) + assert r.status_code == 201, r.text + return r.json() + + +def test_a_floor_plan_with_tables_walls_and_an_irregular_shape(client, owner_h, venue, monkeypatch): + import services.ws_bus as bus + sent = [] + monkeypatch.setattr(bus, "broadcast_sync", lambda t, d, **kw: sent.append(t)) + p = plan(client, owner_h, group_id=venue["inside"].id, grid_on=True, grid_size=50, + outline=[[0, 0], [1000, 0], [1000, 300], [600, 600], [0, 600]]) + assert p["outline"][3] == [600, 600] and p["grid_on"] is True and p["items"] == [] + r = client.put(f"/api/floor-plans/{p['id']}/layout", headers=owner_h, json={ + "tables": [{"id": venue["t1"].id, "x": 100, "y": 100, "width": 80, "height": 80, "shape": "round", "seats": 2}, + {"id": venue["t2"].id, "x": 1500, "y": 200, "width": 160, "height": 70, "shape": "long", "rotation": -90}], + "items": [{"kind": "bar", "x": 500, "y": 40, "width": 400, "height": 50}, {"kind": "label", "x": 800, "y": 500, "width": 120, "height": 30, "text": " Kitchen "}], + }) + assert r.status_code == 200, r.text + assert [(i["kind"], i["text"]) for i in r.json()["items"]] == [("bar", None), ("label", "Kitchen")] + data = client.get("/api/floor-plans", headers=owner_h).json() + placed = {t["id"]: t for t in data["tables"]} + assert placed[venue["t1"].id]["plan_id"] == p["id"] and placed[venue["t1"].id]["shape"] == "round" and placed[venue["t1"].id]["seats"] == 2 + assert placed[venue["t2"].id]["x"] == 1000 and placed[venue["t2"].id]["rotation"] == 270 # kept inside, angle normalised + assert placed[venue["t5"].id]["plan_id"] is None + # saved again without table 2: it leaves the plan + client.put(f"/api/floor-plans/{p['id']}/layout", headers=owner_h, json={"tables": [{"id": venue["t1"].id, "x": 1, "y": 1, "width": 80, "height": 80}]}) + assert {t["id"]: t["plan_id"] for t in client.get("/api/floor-plans", headers=owner_h).json()["tables"]}[venue["t2"].id] is None + assert "floor_plans.changed" in sent + # bad shapes are refused + assert err(client.put(f"/api/floor-plans/{p['id']}", headers=owner_h, json={"name": "x", "width": 1000, "height": 600, "outline": [[0, 0], [10, 10]]})) == "floor_plan.bad_outline" + assert err(client.put(f"/api/floor-plans/{p['id']}", headers=owner_h, json={"name": "x", "width": 1000, "height": 600, "outline": [[0, 0], [2000, 0], [0, 10]]})) == "floor_plan.bad_outline" + # deleting the plan keeps the tables + assert client.delete(f"/api/floor-plans/{p['id']}", headers=owner_h).status_code == 204 + assert all(t["plan_id"] is None for t in client.get("/api/floor-plans", headers=owner_h).json()["tables"]) + + +def test_several_plans_per_zone_and_a_background(client, owner_h, venue, db): + from models.media import Media + m = Media(name="Top view", kind="image", sha256="a" * 64, content_type="image/webp", bytes=10) + db.add(m) + db.commit() + a = plan(client, owner_h, group_id=venue["inside"].id, name="Ground floor") + b = plan(client, owner_h, group_id=venue["inside"].id, name="Upstairs", media_id=m.id, background_opacity=0.4) + assert b["background"]["full"].endswith("/full") and b["sort_order"] > a["sort_order"] + assert err(client.post("/api/floor-plans", headers=owner_h, json={"name": "x", "group_id": 999})) == "floor_plan.bad_zone" + + +def test_the_live_map_shows_each_table_state_to_the_right_people(client, owner_h, venue, db, make_user, login): + from core.timeutil import utcnow + from models.order import Order, OrderWaiter + from models.user import WaiterZone + p = plan(client, owner_h) + client.put(f"/api/floor-plans/{p['id']}/layout", headers=owner_h, json={"tables": [ + {"id": venue[k].id, "x": 100 * i, "y": 100, "width": 80, "height": 80} for i, k in enumerate(("t1", "t2", "t11"), 1)]}) + maria = make_user(role="waiter", nickname="Maria") + db.add(WaiterZone(waiter_id=maria.id, group_id=venue["inside"].id)) + o = Order(table_id=venue["t1"].id, opened_by=maria.id, status="open", customer_count=3, opened_at=utcnow()) + db.add(o) + db.flush() + db.add(OrderWaiter(order_id=o.id, waiter_id=maria.id)) + db.commit() + h = login(maria, client="waiter") + data = client.get("/api/floor-plans/live", headers=h).json() + by = {t["id"]: t for t in data["tables"]} + assert venue["t11"].id not in by # the terrace isn't her zone + t1 = by[venue["t1"].id] + assert t1["state"] == "open" and t1["mine"] is True and t1["order"]["guests"] == 3 and t1["order"]["people"] == ["Maria"] + assert t1["order"]["opened_at"].endswith("Z") and t1["seats"] == 4 + assert by[venue["t2"].id]["state"] == "free" and by[venue["t2"].id]["order"] is None + assert [x["id"] for x in data["plans"]] == [p["id"]] + assert len(client.get("/api/floor-plans/live", headers=owner_h).json()["tables"]) == 4 + # only the tables' managers set plans up + assert client.post("/api/floor-plans", headers=h, json={"name": "x"}).status_code == 403 diff --git a/manager_dashboard/Dockerfile b/manager_dashboard/Dockerfile index c4cac13..2007b95 100644 --- a/manager_dashboard/Dockerfile +++ b/manager_dashboard/Dockerfile @@ -12,6 +12,7 @@ COPY packages/i18n/package.json packages/i18n/ COPY packages/api/package.json packages/api/ COPY packages/access/package.json packages/access/ COPY packages/signage/package.json packages/signage/ +COPY packages/floorplan/package.json packages/floorplan/ COPY waiter_pwa/package.json waiter_pwa/ COPY manager_dashboard/package.json manager_dashboard/ COPY terminal/package.json terminal/ diff --git a/manager_dashboard/package.json b/manager_dashboard/package.json index af7466b..128ff85 100644 --- a/manager_dashboard/package.json +++ b/manager_dashboard/package.json @@ -14,6 +14,7 @@ "@tanstack/react-query": "^5.107.1", "@xenia/access": "^0.0.0", "@xenia/api": "^0.0.0", + "@xenia/floorplan": "^0.0.0", "@xenia/i18n": "^0.0.0", "@xenia/signage": "^0.0.0", "@xenia/ui": "^0.0.0", diff --git a/manager_dashboard/src/pages/Management/TablesConfigPage.jsx b/manager_dashboard/src/pages/Management/TablesConfigPage.jsx index 406f789..53da28b 100644 --- a/manager_dashboard/src/pages/Management/TablesConfigPage.jsx +++ b/manager_dashboard/src/pages/Management/TablesConfigPage.jsx @@ -1,9 +1,29 @@ +// Management → Tables: the tables and their zones (the list, for typing and bulk changes), and +// the floor plans (plan step 6.8: where the tables stand, drawn on a map). +import { useState } from 'react' +import { useTranslation } from '@xenia/i18n' +import FloorPlansTab from '../floor/FloorPlansTab' import TablesConfigTab from '../TablesConfigTab' +const TABS = ['list', 'floor'] + export default function TablesConfigPage() { + const { t } = useTranslation('manager') + const [tab, setTab] = useState('list') return (
Δεν βρέθηκαν τραπέζια.
)} -{t('floor.shapeHint')}
} +{t('floor.keysHint')}
+{t('floorMap.none')}
+{t('floorMap.noneHint')}
+