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 (
- +
+ {TABS.map(k => ( + + ))} +
+
+ {tab === 'list' ? : } +
) } diff --git a/manager_dashboard/src/pages/TablesPage.jsx b/manager_dashboard/src/pages/TablesPage.jsx index b443b53..875b3d1 100644 --- a/manager_dashboard/src/pages/TablesPage.jsx +++ b/manager_dashboard/src/pages/TablesPage.jsx @@ -3,6 +3,8 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useNavigate } from 'react-router-dom' import toast from 'react-hot-toast' import client from '../api/client' +import { useTranslation } from '@xenia/i18n' +import LiveFloor from './floor/LiveFloor' function relativeTime(isoStr) { if (!isoStr) return '' @@ -550,6 +552,8 @@ function MultiSelectDropdown({ label, options, selected, onChange, allLabel = ' // ─── Page ───────────────────────────────────────────────────────────────────── export default function TablesPage() { + const { t } = useTranslation('common') + const [view, setView] = useState('list') // list | map (6.8: the floor plans, live) const [statusFilter, setStatusFilter] = useState([]) const [zoneFilter, setZoneFilter] = useState([]) const [retryingId, setRetryingId] = useState(null) @@ -710,6 +714,14 @@ export default function TablesPage() { /> )}
+
+ {['list', 'map'].map(v => ( + + ))} +
- {filtered.length === 0 && ( + {view === 'map' && navigate(`/orders/${id}`)} />} + + {view === 'list' && filtered.length === 0 && (

Δεν βρέθηκαν τραπέζια.

)} -
+ {view === 'list' &&
{filtered.map(({ table, order, tableStatus, hasPendingPrint, tableFlags }) => { const waiterNames = order ? order.waiters.map(w => waiterMap[w.waiter_id] || { name: `#${w.waiter_id}`, shortName: `#${w.waiter_id}`, avatarUrl: null }) @@ -757,7 +771,7 @@ export default function TablesPage() { /> ) })} -
+
} {pendingPrintOrders.length > 0 && (
diff --git a/manager_dashboard/src/pages/floor/FloorEditor.jsx b/manager_dashboard/src/pages/floor/FloorEditor.jsx new file mode 100644 index 0000000..6f0f23f --- /dev/null +++ b/manager_dashboard/src/pages/floor/FloorEditor.jsx @@ -0,0 +1,294 @@ +// One floor plan's editor (plan step 6.8, D-31). Drag tables and things on the floor; the panel +// on the right edits what's selected (shape, seats, size, rotation, text), adds the tables that +// aren't on the plan and walls / the bar / labels / areas, and holds the plan's settings: name, +// zone, size, the grid (snap on / off and its size), the floor's shape (drag its corners; add or +// remove corners) and a background picture from the media library. Arrow keys move the selected +// thing (a grid cell, or 5; Shift: 1), Delete takes it off, Escape lets go. Nothing is saved +// until "Save"; then every app's map changes at once. +import { useMemo, useRef, useState } from 'react' +import toast from 'react-hot-toast' +import { RotateCcw, RotateCw, Save, Trash2, Undo2 } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { + Floor, GRID_SIZES, ITEM_KINDS, Item, SHAPES, TableShape, addCorner, defaultSize, moveCorner, moveTo, outlineOf, removeCorner, toPlan, +} from '@xenia/floorplan' +import { useTranslation } from '@xenia/i18n' +import { Button, Dialog, Field, IconButton, Input, Select, Switch, cx } from '@xenia/ui' +import MediaField from '../media/MediaField' +import * as api from './floorApi' +import { addItem, addable, find, fitOutline, layoutBody, layoutOf, nudge, placeTable, planBody, remove, resize, rotate, sameLayout, update } from './editorLogic' + +const PAD = 30 // room around the floor for the corner handles + +export default function FloorEditor({ plan: saved, data, groups, onSaved, onDeleted }) { + const { t } = useTranslation('manager') + const initial = useMemo(() => layoutOf(data, saved.id), [data, saved.id]) + const [layout, setLayout] = useState(initial) + const [form, setForm] = useState(() => ({ ...saved })) + const [sel, setSel] = useState(null) // {type: 'table'|'item', id} | {type: 'corner', index} + const [shapeMode, setShapeMode] = useState(false) + const [newShape, setNewShape] = useState('square') + const [busy, setBusy] = useState(false) + const [deleting, setDeleting] = useState(false) + const svg = useRef(null) + const drag = useRef(null) + + const plan = form // the preview follows the unsaved settings + const dirtySettings = JSON.stringify(planBody(form)) !== JSON.stringify(planBody(saved)) + const dirty = dirtySettings || !sameLayout(layout, initial) + const selected = sel && sel.type !== 'corner' ? find(layout, sel) : null + const corners = outlineOf(plan) + const setF = (k, v) => setForm(f => ({ ...f, [k]: v })) + const { own, other } = addable(data, plan, layout) + + const point = e => toPlan(svg.current, e.clientX, e.clientY) + const start = (e, target) => { + e.stopPropagation() + svg.current?.focus() + const [px, py] = point(e) + if (target.type === 'corner') { + setSel(target) + drag.current = { target } + } else { + const thing = find(layout, target) + setSel(target) + drag.current = { target, dx: px - thing.x, dy: py - thing.y } + } + svg.current.setPointerCapture?.(e.pointerId) + } + const move = e => { + const d = drag.current + if (!d) return + const [px, py] = point(e) + if (d.target.type === 'corner') { + setForm(f => ({ ...f, outline: moveCorner(outlineOf(f), d.target.index, px, py, f) })) + return + } + setLayout(l => { + const thing = find(l, d.target) + if (!thing) return l + const m = moveTo(thing, px - d.dx, py - d.dy, plan) + return update(l, d.target, { x: m.x, y: m.y }) + }) + } + const end = () => { drag.current = null } + const keys = e => { + if (!sel || sel.type === 'corner') return + const dirs = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] } + if (dirs[e.key]) { e.preventDefault(); setLayout(l => nudge(l, sel, plan, ...dirs[e.key], e.shiftKey)) } + else if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); setLayout(l => remove(l, sel)); setSel(null) } + else if (e.key === 'Escape') setSel(null) + } + + const save = async () => { + setBusy(true) + try { + if (dirtySettings) await api.savePlan(saved.id, planBody(form)) + await api.saveLayout(saved.id, layoutBody(layout)) + toast.success(t('floor.saved')) + onSaved() + } catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) } + } + const zoneName = id => groups.find(g => g.id === id)?.name ?? t('floor.noZone') + + return ( +
+
+
+

{form.name || saved.name}

+ {dirty && {t('floor.unsaved')}} + + +
+
+ setF('grid_on', v)} label={t('floor.grid')} data-testid="floor-grid" /> + {form.grid_on && ( + setNewShape(e.target.value)} options={SHAPES.map(s => ({ value: s, label: t(`floor.shapes.${s}`) }))} /> + + {own.length + other.length === 0 ?

{t('floor.allPlaced')}

: ( +
+ { setLayout(l => placeTable(l, plan, tb, newShape)); setSel({ type: 'table', id: tb.id }) }} /> + {other.length > 0 && { setLayout(l => placeTable(l, plan, tb, newShape)); setSel({ type: 'table', id: tb.id }) }} />} +
+ )} +
+ {t('floor.things')} +
+ {ITEM_KINDS.map(k => ( + + ))} +
+
+ + )} + + + setF('name', e.target.value)} data-testid="floor-name" /> + + { const w = Number(e.target.value); setForm(f => ({ ...f, width: w, outline: fitOutline(f.outline, w, f.height) })) }} /> + + + { const h = Number(e.target.value); setForm(f => ({ ...f, height: h, outline: fitOutline(f.outline, f.width, h) })) }} /> + +
+ setF('background', img)} label={t('floor.background')} testid="floor-background" /> + {form.background && ( + + )} + + + + + {deleting && ( + setDeleting(false)} + footer={<> + + + }> +

{t('floor.deleteBody', { name: saved.name })}

+
+ )} +
+ ) +} + +function Panel({ title, children }) { + return ( +
+

{title}

+ {children} +
+ ) +} + +function TableButtons({ tables, title, onAdd, quiet = false }) { + if (!tables.length) return null + return ( +
+ {title} +
+ {tables.map(tb => ( + + ))} +
+
+ ) +} + +function Selected({ thing, sel, plan, t, onChange, onRemove }) { + const isTable = sel.type === 'table' + const setSize = (w, h) => onChange(resize(thing, plan, w, h)) + return ( + + {isTable && ( + <> + +
+ {SHAPES.map(s => ( + + ))} +
+
+ + onChange({ seats: e.target.value === '' ? null : Math.max(0, Math.min(99, Math.round(Number(e.target.value)))) })} /> + + + )} + {!isTable && thing.kind !== 'wall' && ( + + onChange({ text: e.target.value })} data-testid="floor-item-text" /> + + )} +
+ setSize(Number(e.target.value), undefined)} /> + setSize(undefined, Number(e.target.value))} /> +
+
+ {t('floor.rotation', { deg: Math.round(thing.rotation || 0) })} + onChange({ rotation: rotate(thing.rotation || 0, -15) })}> + onChange({ rotation: rotate(thing.rotation || 0, 15) })} data-testid="floor-rotate"> + +
+ +
+ ) +} diff --git a/manager_dashboard/src/pages/floor/FloorPlansTab.jsx b/manager_dashboard/src/pages/floor/FloorPlansTab.jsx new file mode 100644 index 0000000..ef37ec5 --- /dev/null +++ b/manager_dashboard/src/pages/floor/FloorPlansTab.jsx @@ -0,0 +1,99 @@ +// Management → Tables → Floor plans (plan step 6.8, D-31): the venue's floor plans by zone (a zone +// can have several, e.g. "Ground floor" and "Upstairs"; a plan may have no zone), "New floor plan", +// and the chosen plan's editor (FloorEditor). The phones, the counter and the Tables page draw +// the saved plans live (@xenia/floorplan FloorView). +import { useState } from 'react' +import toast from 'react-hot-toast' +import { Plus } from 'lucide-react' +import { errorMessage } from '@xenia/api' +import { useTranslation } from '@xenia/i18n' +import { Button, Dialog, EmptyState, Field, Input, Select, Spinner, cx } from '@xenia/ui' +import { useLiveQuery } from '../../live/useLiveQuery' +import FloorEditor from './FloorEditor' +import * as api from './floorApi' + +const SIZES = { small: [800, 600], medium: [1200, 800], large: [1800, 1200] } + +export default function FloorPlansTab() { + const { t } = useTranslation('manager') + const { data, refetch } = useLiveQuery({ queryKey: ['floor-plans'], queryFn: api.listPlans, events: api.FLOOR_EVENTS }) + const { data: groups = [] } = useLiveQuery({ queryKey: ['table-groups'], queryFn: api.listZones, events: ['table_list_changed'] }) + const [chosen, setChosen] = useState(null) + const [creating, setCreating] = useState(false) + const [version, setVersion] = useState(0) // a new editor after a save (it starts from what was saved) + + if (!data) return
+ const plans = data.plans + const plan = plans.find(p => p.id === chosen) ?? plans[0] ?? null + const byZone = [...groups.map(g => ({ id: g.id, name: g.name, plans: plans.filter(p => p.group_id === g.id) })), + { id: null, name: t('floor.noZone'), plans: plans.filter(p => p.group_id == null || !groups.some(g => g.id === p.group_id)) }].filter(z => z.plans.length) + + return ( +
+ +
+ {plan ? ( + { await refetch(); setVersion(v => v + 1) }} + onDeleted={async () => { setChosen(null); await refetch(); setVersion(v => v + 1) }} /> + ) : } onClick={() => setCreating(true)}>{t('floor.new')}} />} +
+ {creating && setCreating(false)} onCreate={async body => { + try { + const p = await api.createPlan(body) + setCreating(false) + await refetch() + setChosen(p.id) + setVersion(v => v + 1) + } catch (err) { toast.error(errorMessage(err, t)) } + }} />} +
+ ) +} + +function NewPlan({ groups, onClose, onCreate }) { + const { t } = useTranslation('manager') + const [name, setName] = useState('') + const [zone, setZone] = useState(groups[0]?.id ?? null) + const [size, setSize] = useState('medium') + return ( + + + + }> +
+ setName(e.target.value)} placeholder={t('floor.namePlaceholder')} data-testid="floor-new-name" /> + + setSize(e.target.value)} + options={Object.keys(SIZES).map(k => ({ value: k, label: t(`floor.sizes.${k}`, { w: SIZES[k][0], h: SIZES[k][1] }) }))} /> + +
+
+ ) +} diff --git a/manager_dashboard/src/pages/floor/LiveFloor.jsx b/manager_dashboard/src/pages/floor/LiveFloor.jsx new file mode 100644 index 0000000..9a11936 --- /dev/null +++ b/manager_dashboard/src/pages/floor/LiveFloor.jsx @@ -0,0 +1,18 @@ +// The manager's Tables page as a map (plan step 6.8, D-31): the floor plans with each table's state +// now (@xenia/floorplan FloorView over GET /api/floor-plans/live), live. A table with an order +// opens it; `zone` narrows the plans to one zone. +import { FloorView } from '@xenia/floorplan' +import { useLiveQuery } from '../../live/useLiveQuery' +import * as api from './floorApi' + +const EVENTS = ['order_updated', 'order_paid', 'order_closed', 'table_list_changed', 'kds_order_updated', 'kds_item_updated', + 'reservation_updated', 'floor_plans.changed'] + +export default function LiveFloor({ zone = null, onOpen }) { + const { data } = useLiveQuery({ queryKey: ['floor-live'], queryFn: api.live, events: EVENTS, refetchInterval: 60_000 }) + return ( +
+ { if (table.order) onOpen(table.order.id) }} /> +
+ ) +} diff --git a/manager_dashboard/src/pages/floor/editorLogic.js b/manager_dashboard/src/pages/floor/editorLogic.js new file mode 100644 index 0000000..c35486c --- /dev/null +++ b/manager_dashboard/src/pages/floor/editorLogic.js @@ -0,0 +1,115 @@ +// The floor plan editor's state as plain data (plan step 6.8, D-31), tested in tests/floor.test.mjs. +// A layout = { tables: [...placed tables], items: [...] } for one plan; the editor changes it +// locally and saves it whole (PUT /api/floor-plans/{id}/layout). +import { ITEM_SIZES, clamp, defaultSize, moveTo, snapSize } from '@xenia/floorplan/geometry' + +/** The layout of a plan from GET /api/floor-plans. Items get local keys (`key`). */ +export function layoutOf(data, planId) { + const plan = data.plans.find(p => p.id === planId) + return { + tables: data.tables.filter(t => t.plan_id === planId && t.x != null).map(t => ({ ...t })), + items: (plan?.items ?? []).map((i, n) => ({ ...i, key: `i${i.id ?? n}` })), + } +} + +/** The tables to add: not on this plan; the plan's zone first, then the rest. */ +export function addable(data, plan, layout) { + const here = new Set(layout.tables.map(t => t.id)) + const rest = data.tables.filter(t => !here.has(t.id)) + const own = rest.filter(t => plan.group_id == null || t.group_id === plan.group_id) + const other = rest.filter(t => !own.includes(t)) + return { own, other } +} + +const gridOf = plan => (plan.grid_on ? plan.grid_size : 0) + +/** Put a table on the plan: at the middle (or a free spot near it), sized from its shape and seats. */ +export function placeTable(layout, plan, table, shape = 'square') { + const size = defaultSize(shape, table.seats, gridOf(plan)) + const spot = freeSpot(layout, plan, size) + return { ...layout, tables: [...layout.tables, moveTo({ ...table, shape, rotation: 0, ...size, plan_id: plan.id }, spot[0], spot[1], plan)] } +} + +/** A spot near the middle not on top of another table (a spiral of steps). */ +export function freeSpot(layout, plan, size) { + const cx = plan.width / 2 + const cy = plan.height / 2 + const step = Math.max(size.width, size.height) + 20 + const taken = ([x, y]) => layout.tables.some(t => Math.abs(t.x - x) < (t.width + size.width) / 2 && Math.abs(t.y - y) < (t.height + size.height) / 2) + for (let r = 0; r < 8; r++) { + for (let i = -r; i <= r; i++) { + for (const [dx, dy] of [[i, -r], [i, r], [-r, i], [r, i]]) { + const p = [clamp(cx + dx * step, size.width / 2, plan.width - size.width / 2), clamp(cy + dy * step, size.height / 2, plan.height - size.height / 2)] + if (!taken(p)) return p + } + } + } + return [cx, cy] +} + +let counter = 0 +/** A wall, bar, label or area at the middle. */ +export function addItem(layout, plan, kind, text = null) { + const [w, h] = ITEM_SIZES[kind] + const grid = gridOf(plan) + const item = moveTo({ key: `n${++counter}`, kind, width: snapSize(w, grid), height: kind === 'wall' ? h : snapSize(h, grid), rotation: 0, text }, plan.width / 2, plan.height / 2, plan) + return { layout: { ...layout, items: [...layout.items, item] }, key: item.key } +} + +/** Change the selected thing (a table by id, an item by key). */ +export function update(layout, sel, patch) { + if (!sel) return layout + if (sel.type === 'table') return { ...layout, tables: layout.tables.map(t => (t.id === sel.id ? { ...t, ...patch } : t)) } + return { ...layout, items: layout.items.map(i => (i.key === sel.id ? { ...i, ...patch } : i)) } +} + +export function remove(layout, sel) { + if (!sel) return layout + if (sel.type === 'table') return { ...layout, tables: layout.tables.filter(t => t.id !== sel.id) } + return { ...layout, items: layout.items.filter(i => i.key !== sel.id) } +} + +export function find(layout, sel) { + if (!sel) return null + return sel.type === 'table' ? layout.tables.find(t => t.id === sel.id) ?? null : layout.items.find(i => i.key === sel.id) ?? null +} + +/** Move the selected thing by a step (arrow keys): a grid cell, or 5 units (Shift: 1). */ +export function nudge(layout, sel, plan, dx, dy, fine = false) { + const thing = find(layout, sel) + if (!thing) return layout + const step = plan.grid_on ? plan.grid_size : fine ? 1 : 5 + const moved = moveTo(thing, thing.x + dx * step, thing.y + dy * step, plan) + return update(layout, sel, { x: moved.x, y: moved.y }) +} + +/** A table's or an item's size (grid on: whole cells). */ +export function resize(thing, plan, width, height) { + const grid = gridOf(plan) + const w = Number.isFinite(width) ? (grid ? snapSize(width, grid) : Math.max(10, width)) : thing.width + const h = Number.isFinite(height) ? (grid && thing.kind !== 'wall' ? snapSize(height, grid) : Math.max(4, height)) : thing.height + return { width: w, height: h } +} + +/** A rotation turned by `by` degrees, kept within 0–359. */ +export const rotate = (deg, by) => (((deg + by) % 360) + 360) % 360 + +/** The body the server takes. */ +export function layoutBody(layout) { + return { + tables: layout.tables.map(t => ({ id: t.id, x: t.x, y: t.y, width: t.width, height: t.height, rotation: t.rotation || 0, shape: t.shape || 'square', seats: t.seats ?? null })), + items: layout.items.map(i => ({ kind: i.kind, x: i.x, y: i.y, width: i.width, height: i.height, rotation: i.rotation || 0, text: i.text || null })), + } +} + +export const sameLayout = (a, b) => JSON.stringify(layoutBody(a)) === JSON.stringify(layoutBody(b)) + +/** The plan's settings form → body. */ +export const planBody = f => ({ + name: f.name.trim(), group_id: f.group_id ?? null, width: Math.round(f.width), height: Math.round(f.height), + outline: f.outline?.length >= 3 ? f.outline : null, grid_on: !!f.grid_on, grid_size: Math.round(f.grid_size), + media_id: f.background?.id ?? null, background_opacity: f.background_opacity ?? 0.6, +}) + +/** A smaller canvas: the outline's corners come inside it. */ +export const fitOutline = (outline, width, height) => (outline ? outline.map(([x, y]) => [clamp(x, 0, width), clamp(y, 0, height)]) : null) diff --git a/manager_dashboard/src/pages/floor/floorApi.js b/manager_dashboard/src/pages/floor/floorApi.js new file mode 100644 index 0000000..213f25a --- /dev/null +++ b/manager_dashboard/src/pages/floor/floorApi.js @@ -0,0 +1,15 @@ +// Floor plans' server calls (plan step 6.8). Backend: routers/floor_plans.py (/api/floor-plans); +// every change sends the live event `floor_plans.changed`. +import client from '../../api/client' + +const data = r => r.data + +export const FLOOR_EVENTS = ['floor_plans.changed', 'table_list_changed'] + +export const listPlans = () => client.get('/api/floor-plans').then(data) +export const createPlan = body => client.post('/api/floor-plans', body).then(data) +export const savePlan = (id, body) => client.put(`/api/floor-plans/${id}`, body).then(data) +export const saveLayout = (id, body) => client.put(`/api/floor-plans/${id}/layout`, body).then(data) +export const deletePlan = id => client.delete(`/api/floor-plans/${id}`) +export const listZones = () => client.get('/api/tables/groups').then(data) +export const live = () => client.get('/api/floor-plans/live').then(data) diff --git a/manager_dashboard/tests/floor.test.mjs b/manager_dashboard/tests/floor.test.mjs new file mode 100644 index 0000000..c0a2b28 --- /dev/null +++ b/manager_dashboard/tests/floor.test.mjs @@ -0,0 +1,61 @@ +// The floor plan editor's state (plan step 6.8): placing tables and things, moving, the body saved. +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { addItem, addable, freeSpot, layoutBody, layoutOf, nudge, placeTable, planBody, remove, resize, rotate, sameLayout, update } from '../src/pages/floor/editorLogic.js' + +const plan = { id: 1, name: 'Ground', group_id: 10, width: 1000, height: 600, grid_on: true, grid_size: 50, outline: null, background: null, background_opacity: 0.6 } +const data = { + plans: [{ ...plan, items: [{ id: 7, kind: 'bar', x: 500, y: 50, width: 300, height: 50, rotation: 0, text: null }] }], + tables: [ + { id: 1, name: '1', group_id: 10, seats: 4, plan_id: 1, x: 100, y: 100, width: 100, height: 100, rotation: 0, shape: 'square' }, + { id: 2, name: '2', group_id: 10, seats: 2, plan_id: null, x: null, y: null }, + { id: 3, name: 'T1', group_id: 11, seats: 6, plan_id: null, x: null, y: null }, + ], +} + +test('a plan\'s layout and the tables that can be added (its zone first)', () => { + const l = layoutOf(data, 1) + assert.deepEqual(l.tables.map(t => t.id), [1]) + assert.equal(l.items[0].key, 'i7') + const { own, other } = addable(data, plan, l) + assert.deepEqual([own.map(t => t.id), other.map(t => t.id)], [[2], [3]]) +}) + +test('placing a table: sized from its seats, on the grid, not on top of another', () => { + let l = layoutOf(data, 1) + l = placeTable(l, plan, data.tables[1], 'round') + const t2 = l.tables.find(t => t.id === 2) + assert.deepEqual([t2.width, t2.height, t2.shape, t2.x % 25, t2.y % 25], [50, 50, 'round', 0, 0]) // 2 seats: 70, one 50-cell + l = placeTable(l, plan, data.tables[2], 'long') + const t3 = l.tables.find(t => t.id === 3) + assert.ok(Math.abs(t3.x - t2.x) >= 50 || Math.abs(t3.y - t2.y) >= 50, 'placed apart') + const spot = freeSpot({ tables: [] }, plan, { width: 100, height: 100 }) + assert.deepEqual(spot, [500, 300]) +}) + +test('things, moving with the arrows, resizing, turning, removing', () => { + let l = layoutOf(data, 1) + const r = addItem(l, plan, 'wall') + l = r.layout + const wall = l.items.find(i => i.key === r.key) + assert.deepEqual([wall.kind, wall.height], ['wall', 12]) // a wall keeps its thickness + l = nudge(l, { type: 'table', id: 1 }, plan, 1, 0) + assert.equal(l.tables[0].x, 150) // one grid cell + l = nudge(l, { type: 'table', id: 1 }, { ...plan, grid_on: false }, 0, 1, true) + assert.equal(l.tables[0].y, 101) + assert.deepEqual(resize(l.tables[0], plan, 130, undefined), { width: 150, height: 100 }) + assert.equal(rotate(350, 15), 5) + l = update(l, { type: 'item', id: r.key }, { text: 'x' }) + l = remove(l, { type: 'table', id: 1 }) + assert.equal(l.tables.length, 0) +}) + +test('what is saved', () => { + const l = layoutOf(data, 1) + const body = layoutBody(l) + assert.deepEqual(body.tables[0], { id: 1, x: 100, y: 100, width: 100, height: 100, rotation: 0, shape: 'square', seats: 4 }) + assert.deepEqual(body.items[0], { kind: 'bar', x: 500, y: 50, width: 300, height: 50, rotation: 0, text: null }) + assert.equal(sameLayout(l, layoutOf(data, 1)), true) + assert.deepEqual(planBody({ ...plan, name: ' Up ', background: { id: 4 }, outline: [[0, 0], [5, 5]] }), + { name: 'Up', group_id: 10, width: 1000, height: 600, outline: null, grid_on: true, grid_size: 50, media_id: 4, background_opacity: 0.6 }) +}) diff --git a/manager_dashboard/v2.json b/manager_dashboard/v2.json index 0d95728..0cb02ca 100644 --- a/manager_dashboard/v2.json +++ b/manager_dashboard/v2.json @@ -1,9 +1,9 @@ { "_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.", "paths": [ - "src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing" + "src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx" ], "strict": [ - "src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing" + "src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor" ] } diff --git a/package-lock.json b/package-lock.json index ba58758..a991c66 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,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", @@ -3216,6 +3217,10 @@ "resolved": "packages/api", "link": true }, + "node_modules/@xenia/floorplan": { + "resolved": "packages/floorplan", + "link": true + }, "node_modules/@xenia/i18n": { "resolved": "packages/i18n", "link": true @@ -9566,6 +9571,16 @@ "name": "@xenia/api", "version": "0.0.0" }, + "packages/floorplan": { + "name": "@xenia/floorplan", + "version": "0.0.0", + "dependencies": { + "@xenia/i18n": "^0.0.0" + }, + "peerDependencies": { + "react": "^19.0.0" + } + }, "packages/i18n": { "name": "@xenia/i18n", "version": "0.0.0", @@ -9602,6 +9617,7 @@ "dependencies": { "@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", @@ -9665,6 +9681,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/ui": "^0.0.0", "axios": "^1.21.1", diff --git a/packages/floorplan/package.json b/packages/floorplan/package.json new file mode 100644 index 0000000..65035db --- /dev/null +++ b/packages/floorplan/package.json @@ -0,0 +1,21 @@ +{ + "name": "@xenia/floorplan", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "The table map (plan step 6.8, D-31): floor plans drawn the same in the waiter app, the counter POS and the manager (live map and editor), and their pure geometry (grid snap, outlines, chairs).", + "main": "src/index.js", + "exports": { + ".": "./src/index.js", + "./geometry": "./src/geometry.js" + }, + "dependencies": { + "@xenia/i18n": "^0.0.0" + }, + "scripts": { + "test": "node --test \"tests/*.test.mjs\"" + }, + "peerDependencies": { + "react": "^19.0.0" + } +} diff --git a/packages/floorplan/src/FloorView.jsx b/packages/floorplan/src/FloorView.jsx new file mode 100644 index 0000000..e3ae4f3 --- /dev/null +++ b/packages/floorplan/src/FloorView.jsx @@ -0,0 +1,106 @@ +// The live table map (plan step 6.8, D-31), the same in the waiter app, the counter POS and the +// manager's Tables page. `data` is GET /api/floor-plans/live ({plans, tables}); the app reloads it +// on its live events. A tab per floor plan (of the zone, when one is chosen), zoom buttons, and +// the tables not on any plan as buttons under it. A tap on a table calls onPick(table). +// Styles are inline with @xenia/ui tokens, so it fits the apps with and without Tailwind. +import { useEffect, useMemo, useState } from 'react' +import { useTranslation } from '@xenia/i18n' +import { plansFor, splitTables, toneOf, TONES } from './geometry.js' +import { Floor, Item, TableShape } from './Shapes.jsx' + +const ZOOMS = [0.5, 0.75, 1, 1.25, 1.5, 2, 3] + +function useMinuteClock() { + const [now, setNow] = useState(() => Date.now()) + useEffect(() => { + const id = setInterval(() => setNow(Date.now()), 30_000) + return () => clearInterval(id) + }, []) + return now +} + +const btn = active => ({ + padding: '6px 12px', borderRadius: 999, border: `1px solid ${active ? 'var(--x-accent)' : 'var(--x-line)'}`, + background: active ? 'var(--x-accent-soft)' : 'var(--x-surface)', color: active ? 'var(--x-accent-ink)' : 'var(--x-ink-2)', + fontWeight: 600, fontSize: 13, cursor: 'pointer', whiteSpace: 'nowrap', +}) +const round = { width: 36, height: 36, borderRadius: 999, border: '1px solid var(--x-line)', background: 'var(--x-surface)', color: 'var(--x-ink)', fontSize: 18, fontWeight: 700, cursor: 'pointer' } + +export function FloorView({ data, zone = null, onPick, mediaBase = '', height = '100%' }) { + const { t } = useTranslation('common') + const now = useMinuteClock() + const plans = useMemo(() => plansFor(data?.plans ?? [], zone), [data, zone]) + const [chosen, setChosen] = useState(null) + const [zoom, setZoom] = useState(null) // null = fit the width + const plan = plans.find(p => p.id === chosen) ?? plans[0] ?? null + const { placed, unplaced } = useMemo(() => splitTables(data?.tables ?? [], plan?.id ?? -1, zone), [data, plan, zone]) + + if (!data) return null + if (!plan) { + return ( +
+

{t('floorMap.none')}

+

{t('floorMap.noneHint')}

+
+ ) + } + const step = d => setZoom(z => { + const cur = z ?? 1 + const i = ZOOMS.findIndex(v => v >= cur - 0.001) + return ZOOMS[Math.min(ZOOMS.length - 1, Math.max(0, (i < 0 ? ZOOMS.length - 1 : i) + d))] + }) + return ( +
+
+ {plans.length > 1 && plans.map(p => ( + + ))} + + + + +
+
+ + + {plan.items.map(i => )} + {placed.map(table => ( + onPick?.(table)} onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onPick?.(table) } }} /> + ))} + +
+ + {unplaced.length > 0 && ( +
+ {t('floorMap.notOnMap')} + {unplaced.map(table => { + const tone = TONES[toneOf(table)] + return ( + + ) + })} +
+ )} +
+ ) +} + +function Legend({ t }) { + return ( +
+ {['free', 'mine', 'open', 'paid', 'reserved'].map(k => ( + + + {t(`floorMap.state.${k}`)} + + ))} + {t('floorMap.legendGuests')} +
+ ) +} diff --git a/packages/floorplan/src/Shapes.jsx b/packages/floorplan/src/Shapes.jsx new file mode 100644 index 0000000..c74a464 --- /dev/null +++ b/packages/floorplan/src/Shapes.jsx @@ -0,0 +1,111 @@ +// The pieces of a floor plan as SVG (plan step 6.8): the floor (outline, grid, background +// picture), the walls / bar / labels / areas, and a table with its chairs and what it shows. +// Colours are @xenia/ui tokens (CSS variables), so the same drawing works in every app. +import { chairs, durationText, outlineOf, peopleText, pointsAttr, TONES, toneOf } from './geometry.js' + +/** The floor: background picture, the floor's shape, and the grid (when asked). */ +export function Floor({ plan, showGrid = false, mediaBase = '' }) { + const pts = pointsAttr(outlineOf(plan)) + const g = plan.grid_size + const clip = `floor-clip-${plan.id ?? 'new'}` + return ( + + + + {showGrid && g > 0 && ( + + + + )} + + + {plan.background?.full && ( + + )} + {showGrid && g > 0 && } + + ) +} + +const ITEM_LOOK = { + wall: { fill: 'var(--x-ink-2)', stroke: 'none' }, + bar: { fill: 'var(--x-surface-3)', stroke: 'var(--x-ink-3)' }, + label: { fill: 'none', stroke: 'none' }, + area: { fill: 'var(--x-surface-2)', stroke: 'var(--x-line-strong)', dash: '8 6' }, +} + +/** A wall, the bar, a label or an area. */ +export function Item({ item, selected = false, label, ...rest }) { + const look = ITEM_LOOK[item.kind] ?? ITEM_LOOK.area + const w = item.width + const h = item.height + const text = item.text || (item.kind === 'bar' ? label : '') + return ( + + + {item.kind === 'label' && selected && } + {text && ( + {text} + )} + + ) +} + +/** A small person (for seats / guests): drawn, so it looks the same everywhere. */ +function Person({ x, y, size, color }) { + const r = size / 2 + return ( + + + + + ) +} + +/** + * A table: its shape, chairs for its seats, and (live) its name, guests / seats, time open, + * waiters and a "ready" count. `now` (ms) moves the clock. + */ +export function TableShape({ table, live = true, selected = false, now = Date.now(), ...rest }) { + const tone = TONES[live ? toneOf(table) : 'free'] + const w = table.width || 80 + const h = table.height || 80 + const rot = table.rotation || 0 + const o = live ? table.order : null + const fs = Math.max(11, Math.min(22, Math.min(w, h) * 0.24)) + const lines = [table.name] + const second = o ? `${o.guests ?? '–'}/${table.seats ?? '–'}` : table.seats ? `${table.seats}` : '' + const third = o ? [durationText(o.opened_at ? Math.max(0, Math.floor((now - new Date(o.opened_at).getTime()) / 60000)) : null), peopleText(o.people)].filter(Boolean).join(' · ') : '' + return ( + + + {chairs(table.shape, w, h, table.seats).map(([cx, cy], i) => ( + + ))} + {table.shape === 'round' + ? + : } + + + {lines[0]} + {second && ( + + + {second} + + )} + {third && {third}} + + {o?.ready > 0 && ( + + + {o.ready} + + )} + + ) +} diff --git a/packages/floorplan/src/geometry.js b/packages/floorplan/src/geometry.js new file mode 100644 index 0000000..8f3a7de --- /dev/null +++ b/packages/floorplan/src/geometry.js @@ -0,0 +1,139 @@ +// The table map's geometry (plan step 6.8, D-31), pure and tested (tests/geometry.test.mjs). +// Plan units: 1 unit = 1 px at 100 %. A table's or an item's (x, y) is its centre; rotation in +// degrees, clockwise. The grid is a "snap to fixed positions" grid: positions (centres) and sizes +// become multiples of the grid size (half a cell for odd sizes, so a 1-cell table sits in a cell). + +export const SHAPES = ['square', 'round', 'long'] +export const ITEM_KINDS = ['wall', 'bar', 'label', 'area'] +export const GRID_SIZES = [20, 25, 40, 50, 80, 100] + +/** A value on the grid (off: as it is, to 1 decimal). */ +export function snap(v, grid) { + if (!grid) return Math.round(v * 10) / 10 + return Math.round(v / grid) * grid +} + +/** A size on the grid: whole cells, at least one. */ +export const snapSize = (v, grid) => (grid ? Math.max(grid, Math.round(v / grid) * grid) : Math.max(10, Math.round(v * 10) / 10)) + +/** A centre on the grid: an odd number of cells puts the centre in the middle of a cell. */ +export function snapCentre(c, size, grid) { + if (!grid) return Math.round(c * 10) / 10 + const cells = Math.round(size / grid) + const off = cells % 2 ? grid / 2 : 0 + return Math.round((c - off) / grid) * grid + off +} + +export const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi) + +/** Where a thing goes after a drag, kept on the plan and (grid on) on the grid. */ +export function moveTo(thing, x, y, plan) { + const grid = plan.grid_on ? plan.grid_size : 0 + return { ...thing, x: clamp(snapCentre(x, thing.width, grid), 0, plan.width), y: clamp(snapCentre(y, thing.height, grid), 0, plan.height) } +} + +/** A new table's size from its shape and seats (2 seats: small; long tables grow with seats). */ +export function defaultSize(shape, seats, grid = 0) { + const n = Math.max(1, seats || 4) + let w = 80 + let h = 80 + if (shape === 'round') { w = h = n <= 2 ? 70 : n <= 4 ? 90 : 120 } + else if (shape === 'square') { w = h = n <= 2 ? 70 : 90 } + else { h = 80; w = Math.max(140, Math.ceil(n / 2) * 60) } + return { width: snapSize(w, grid), height: snapSize(h, grid) } +} + +export const ITEM_SIZES = { wall: [300, 12], bar: [320, 60], label: [140, 36], area: [300, 200] } + +/** The floor's corners: its outline, or the whole rectangle. */ +export const outlineOf = plan => (plan.outline?.length >= 3 ? plan.outline : [[0, 0], [plan.width, 0], [plan.width, plan.height], [0, plan.height]]) + +export const pointsAttr = points => points.map(([x, y]) => `${x},${y}`).join(' ') + +/** A corner more: the middle of the edge after corner `i`. */ +export function addCorner(points, i) { + const a = points[i] + const b = points[(i + 1) % points.length] + const out = [...points] + out.splice(i + 1, 0, [Math.round((a[0] + b[0]) / 2), Math.round((a[1] + b[1]) / 2)]) + return out +} + +/** A corner less (a floor keeps at least 3). */ +export const removeCorner = (points, i) => (points.length <= 3 ? points : points.filter((_, j) => j !== i)) + +/** Move corner `i` (kept on the plan, on the grid). */ +export function moveCorner(points, i, x, y, plan) { + const grid = plan.grid_on ? plan.grid_size : 0 + return points.map((p, j) => (j === i ? [clamp(snap(x, grid), 0, plan.width), clamp(snap(y, grid), 0, plan.height)] : p)) +} + +/** Where the chairs go around a table (centres, relative to the table's centre). */ +export function chairs(shape, width, height, seats) { + const n = Math.max(0, Math.min(seats || 0, 24)) + if (!n) return [] + const gap = 10 + if (shape === 'round') { + const rx = width / 2 + gap + const ry = height / 2 + gap + return Array.from({ length: n }, (_, i) => { + const a = (2 * Math.PI * i) / n - Math.PI / 2 + return [Math.round(rx * Math.cos(a) * 10) / 10, Math.round(ry * Math.sin(a) * 10) / 10] + }) + } + // rectangles: along the two long sides (one at each end when there are few) + const along = width >= height + const len = along ? width : height + const top = Math.ceil(n / 2) + const bottom = n - top + const row = (count, side) => Array.from({ length: count }, (_, i) => { + const t = -len / 2 + (len * (i + 0.5)) / count + const off = side * ((along ? height : width) / 2 + gap) + return along ? [Math.round(t * 10) / 10, off] : [off, Math.round(t * 10) / 10] + }) + if (n === 1) return [along ? [0, -(height / 2 + gap)] : [-(width / 2 + gap), 0]] + return [...row(top, -1), ...row(bottom, 1)] +} + +/** How a table looks from its state: free | open | mine | paid | reserved. */ +export function toneOf(table) { + if (table.state === 'open' && table.mine) return 'mine' + return table.state ?? 'free' +} + +export const TONES = { + free: { fill: 'var(--x-surface)', stroke: 'var(--x-line-strong)', ink: 'var(--x-ink)' }, + open: { fill: 'var(--x-info-soft)', stroke: 'var(--x-info)', ink: 'var(--x-info-ink)' }, + mine: { fill: 'var(--x-accent-soft)', stroke: 'var(--x-accent)', ink: 'var(--x-accent-ink)' }, + paid: { fill: 'var(--x-success-soft)', stroke: 'var(--x-success)', ink: 'var(--x-success-ink)' }, + reserved: { fill: 'var(--x-special-soft)', stroke: 'var(--x-special)', ink: 'var(--x-special-ink)' }, // not the accent: some venues' accent is amber +} + +/** Minutes since an order opened. */ +export const minutesSince = (iso, now = Date.now()) => (iso ? Math.max(0, Math.floor((now - new Date(iso).getTime()) / 60000)) : null) + +/** "42′" under an hour, "1:05" after. */ +export function durationText(min) { + if (min == null) return '' + if (min < 60) return `${min}′` + return `${Math.floor(min / 60)}:${String(min % 60).padStart(2, '0')}` +} + +/** "Maria", "Maria +1". */ +export const peopleText = people => (!people?.length ? '' : people.length === 1 ? people[0] : `${people[0]} +${people.length - 1}`) + +/** The tables of one plan, and the ones not on any plan (of a zone, when given). */ +export function splitTables(tables, planId, zone = null) { + const inZone = zone == null ? tables : tables.filter(t => t.group_id === zone) + return { placed: tables.filter(t => t.plan_id === planId && t.x != null), unplaced: inZone.filter(t => t.plan_id == null || t.x == null) } +} + +/** The plans to offer for a zone (null = all): the zone's plans and the plans without a zone. */ +export const plansFor = (plans, zone = null) => (zone == null ? plans : plans.filter(p => p.group_id === zone || p.group_id == null)) + +/** Turn a point on screen (client coordinates) into plan units, for an drawn with a viewBox. */ +export function toPlan(svg, clientX, clientY) { + const r = svg.getBoundingClientRect() + const vb = svg.viewBox.baseVal + return [vb.x + ((clientX - r.left) / r.width) * vb.width, vb.y + ((clientY - r.top) / r.height) * vb.height] +} diff --git a/packages/floorplan/src/index.js b/packages/floorplan/src/index.js new file mode 100644 index 0000000..223319e --- /dev/null +++ b/packages/floorplan/src/index.js @@ -0,0 +1,5 @@ +// @xenia/floorplan (plan step 6.8, D-31): the table map, drawn the same in the waiter app, the +// counter POS and the manager (the live map and the editor), with its pure geometry. +export * from './geometry.js' +export { Floor, Item, TableShape } from './Shapes.jsx' +export { FloorView } from './FloorView.jsx' diff --git a/packages/floorplan/tests/geometry.test.mjs b/packages/floorplan/tests/geometry.test.mjs new file mode 100644 index 0000000..f1c9142 --- /dev/null +++ b/packages/floorplan/tests/geometry.test.mjs @@ -0,0 +1,65 @@ +// The table map's geometry (plan step 6.8): the grid, outlines, chairs, what a table shows. +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { + addCorner, chairs, defaultSize, durationText, minutesSince, moveCorner, moveTo, outlineOf, peopleText, plansFor, removeCorner, + snap, snapCentre, snapSize, splitTables, toneOf, +} from '../src/geometry.js' + +const plan = { width: 1000, height: 600, grid_on: true, grid_size: 50 } + +test('the grid snaps positions and sizes; off, they stay as they are', () => { + assert.equal(snap(73, 50), 50) + assert.equal(snap(73.27, 0), 73.3) + assert.equal(snapSize(20, 50), 50) // at least one cell + assert.equal(snapSize(130, 50), 150) + assert.equal(snapCentre(130, 50, 50), 125) // one cell: the centre of a cell + assert.equal(snapCentre(130, 100, 50), 150) // two cells: on a line + assert.deepEqual(moveTo({ width: 50, height: 50 }, 1210, -20, plan), { width: 50, height: 50, x: 1000, y: 0 }) + assert.deepEqual(moveTo({ width: 50, height: 50 }, 312.4, 99, { ...plan, grid_on: false }), { width: 50, height: 50, x: 312.4, y: 99 }) +}) + +test('new tables get a size from their shape and seats', () => { + assert.deepEqual(defaultSize('round', 2), { width: 70, height: 70 }) + assert.deepEqual(defaultSize('long', 8), { width: 240, height: 80 }) + assert.deepEqual(defaultSize('square', 4, 50), { width: 100, height: 100 }) +}) + +test('irregular floors: corners added, moved, removed (never fewer than 3)', () => { + const rect = outlineOf(plan) + assert.equal(rect.length, 4) + const five = addCorner(rect, 1) // the middle of the right side + assert.deepEqual(five[2], [1000, 300]) + const moved = moveCorner(five, 2, 640, 333, plan) + assert.deepEqual(moved[2], [650, 350]) + assert.equal(removeCorner(removeCorner(moved, 0), 0).length, 3) + assert.equal(removeCorner([[0, 0], [1, 0], [0, 1]], 0).length, 3) + assert.deepEqual(outlineOf({ ...plan, outline: moved }), moved) +}) + +test('chairs go around round tables and along the long sides', () => { + const r = chairs('round', 80, 80, 4) + assert.deepEqual(r[0], [0, -50]) + assert.equal(r.length, 4) + const l = chairs('long', 200, 80, 6) + assert.equal(l.filter(([, y]) => y < 0).length, 3) + assert.equal(l.filter(([, y]) => y > 0).length, 3) + assert.deepEqual(chairs('square', 80, 80, 0), []) +}) + +test('what a table shows', () => { + assert.equal(toneOf({ state: 'open', mine: true }), 'mine') + assert.equal(toneOf({ state: 'paid', mine: true }), 'paid') + assert.equal(durationText(42), '42′') + assert.equal(durationText(65), '1:05') + assert.equal(peopleText(['Maria', 'Nikos']), 'Maria +1') + assert.equal(minutesSince('2026-11-18T10:00:00Z', Date.parse('2026-11-18T10:42:30Z')), 42) +}) + +test('plans of a zone, and the tables not on a plan', () => { + const plans = [{ id: 1, group_id: 1 }, { id: 2, group_id: 2 }, { id: 3, group_id: null }] + assert.deepEqual(plansFor(plans, 2).map(p => p.id), [2, 3]) + const tables = [{ id: 1, plan_id: 1, x: 5, group_id: 1 }, { id: 2, plan_id: null, group_id: 1 }, { id: 3, plan_id: null, group_id: 2 }] + const s = splitTables(tables, 1, 1) + assert.deepEqual([s.placed.map(t => t.id), s.unplaced.map(t => t.id)], [[1], [2]]) +}) diff --git a/packages/i18n/locales/el/common.json b/packages/i18n/locales/el/common.json index 01f426d..461e97a 100644 --- a/packages/i18n/locales/el/common.json +++ b/packages/i18n/locales/el/common.json @@ -98,5 +98,24 @@ "sulphites": "Θειώδη", "lupin": "Λούπινο", "molluscs": "Μαλάκια" + }, + "floorMap": { + "none": "Δεν υπάρχει ακόμα κάτοψη", + "noneHint": "Ένας διευθυντής σχεδιάζει τις κατόψεις στη Διαχείριση → Τραπέζια → Κατόψεις.", + "zoomIn": "Μεγέθυνση", + "zoomOut": "Σμίκρυνση", + "fit": "Προσαρμογή", + "bar": "Μπαρ", + "notOnMap": "Εκτός κάτοψης:", + "legendGuests": "👤 άτομα / θέσεις", + "map": "Κάτοψη", + "list": "Λίστα", + "state": { + "free": "Ελεύθερο", + "mine": "Δικό σας", + "open": "Ανοιχτό", + "paid": "Πληρωμένο", + "reserved": "Κράτηση σύντομα" + } } } diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index ae25243..355e8a2 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -329,5 +329,12 @@ "pricing": { "bad_limit": "Ένα όριο έκπτωσης πρέπει να είναι αριθμός 0 ή μεγαλύτερος, ή κενό για χωρίς όριο.", "bad_condition": "Μια συνθήκη είναι ελλιπής: συμπληρώστε όλες τις τιμές της." + }, + "floor_plan": { + "not_found": "Η κάτοψη δεν βρέθηκε.", + "bad_outline": "Το σχήμα του χώρου χρειάζεται 3 έως 100 γωνίες, όλες μέσα στην κάτοψη.", + "bad_zone": "Αυτή η ζώνη δεν υπάρχει πια.", + "bad_background": "Το φόντο πρέπει να είναι εικόνα από τη βιβλιοθήκη πολυμέσων.", + "bad_layout": "Η διάταξη έχει ένα τραπέζι δύο φορές ή μια θέση που δεν είναι αριθμός." } } diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index fbc9f64..d81ef54 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -2097,5 +2097,90 @@ "max_items_per_orderHint": "Τεμάχια με έκπτωση σε μία παραγγελία." } } + }, + "floor": { + "pageTabs": "Τραπέζια", + "tabs": { + "list": "Τραπέζια και ζώνες", + "floor": "Κατόψεις" + }, + "title": "Κατόψεις", + "intro": "Σχεδιάστε πού βρίσκονται τα τραπέζια. Μια ζώνη μπορεί να έχει πολλές κατόψεις (π.χ. ισόγειο και όροφο). Τα κινητά, το ταμείο και η σελίδα Τραπέζια τις δείχνουν ζωντανά.", + "none": "Δεν υπάρχει ακόμα κάτοψη", + "noneHint": "Φτιάξτε μία και βάλτε πάνω της τα τραπέζια.", + "new": "Νέα κάτοψη", + "create": "Δημιουργία", + "cancel": "Ακύρωση", + "save": "Αποθήκευση", + "saved": "Η κάτοψη αποθηκεύτηκε.", + "delete": "Διαγραφή της κάτοψης", + "deleted": "Η κάτοψη διαγράφηκε.", + "deleteTitle": "Διαγραφή της κάτοψης;", + "deleteBody": "Η «{{name}}» θα χαθεί. Τα τραπέζια της μένουν (εκτός κάτοψης), όπως και οι παραγγελίες τους.", + "unsaved": "Δεν αποθηκεύτηκε", + "undoAll": "Αναίρεση αλλαγών", + "name": "Όνομα", + "namePlaceholder": "π.χ. Ισόγειο", + "zone": "Ζώνη", + "zoneHint": "Τα τραπέζια της προτείνονται πρώτα· οι σερβιτόροι άλλων ζωνών δεν τη βλέπουν.", + "noZone": "Χωρίς ζώνη", + "size": "Μέγεθος", + "sizeHint": "Μπορείτε να το αλλάξετε αργότερα.", + "sizes": { + "small": "Μικρό ({{w}} × {{h}})", + "medium": "Μεσαίο ({{w}} × {{h}})", + "large": "Μεγάλο ({{w}} × {{h}})" + }, + "tableCount_one": "{{count}} τραπέζι", + "tableCount_other": "{{count}} τραπέζια", + "grid": "Πλέγμα", + "gridSize": "Μέγεθος πλέγματος", + "gridCell": "Κελιά των {{size}}", + "editShape": "Αλλαγή σχήματος χώρου", + "shapeHint": "Σύρετε τις γωνίες για να πάρει ο χώρος το πραγματικό του σχήμα (Γ, βεράντα…). Επιλέξτε μια γωνία για να προσθέσετε μία μετά από αυτή ή να την αφαιρέσετε.", + "shapeTitle": "Το σχήμα του χώρου", + "cornerCount_one": "{{count}} γωνία", + "cornerCount_other": "{{count}} γωνίες", + "addCorner": "Προσθήκη γωνίας μετά", + "removeCorner": "Αφαίρεση γωνίας", + "rectangle": "Πίσω σε ορθογώνιο", + "canvas": "Η κάτοψη: σύρετε τραπέζια και αντικείμενα· τα βέλη μετακινούν το επιλεγμένο", + "keysHint": "Τα βέλη μετακινούν το επιλεγμένο (ένα κελί, ή 5· με Shift 1), το Delete το αφαιρεί, το Escape το αφήνει.", + "add": "Προσθήκη", + "newTableShape": "Τα νέα τραπέζια είναι", + "allPlaced": "Όλα τα τραπέζια είναι σε αυτή την κάτοψη.", + "zoneTables": "Τραπέζια της ζώνης {{zone}}", + "offPlan": "Τραπέζια εκτός της κάτοψης", + "otherTables": "Τραπέζια άλλων ζωνών", + "things": "Αντικείμενα", + "kinds": { + "wall": "Τοίχος", + "bar": "Μπαρ", + "label": "Ετικέτα", + "area": "Περιοχή" + }, + "labelText": "Ετικέτα", + "settings": "Η κάτοψη", + "width": "Πλάτος", + "height": "Ύψος", + "background": "Εικόνα φόντου", + "backgroundOpacity": "Ένταση: {{value}}%", + "table": "Τραπέζι {{name}}", + "shape": "Σχήμα", + "shapes": { + "square": "Τετράγωνο", + "round": "Στρογγυλό", + "long": "Μακρύ" + }, + "seats": "Θέσεις", + "seatsHint": "Φαίνονται ως καρέκλες και προτείνονται ως αριθμός ατόμων.", + "text": "Κείμενο", + "itemWidth": "Πλάτος", + "itemHeight": "Βάθος", + "rotation": "Γυρισμένο {{deg}}°", + "rotateLeft": "Στροφή αριστερά 15°", + "rotateRight": "Στροφή δεξιά 15°", + "takeOff": "Βγάλτε το από την κάτοψη", + "removeThing": "Αφαίρεση" } } diff --git a/packages/i18n/locales/en/common.json b/packages/i18n/locales/en/common.json index 919a815..4a5833e 100644 --- a/packages/i18n/locales/en/common.json +++ b/packages/i18n/locales/en/common.json @@ -98,5 +98,24 @@ "sulphites": "Sulphites", "lupin": "Lupin", "molluscs": "Molluscs" + }, + "floorMap": { + "none": "No floor plan yet", + "noneHint": "A manager draws the floor plans in Management → Tables → Floor plans.", + "zoomIn": "Zoom in", + "zoomOut": "Zoom out", + "fit": "Fit", + "bar": "Bar", + "notOnMap": "Not on the map:", + "legendGuests": "👤 guests / seats", + "map": "Map", + "list": "List", + "state": { + "free": "Free", + "mine": "Yours", + "open": "Open", + "paid": "Paid", + "reserved": "Booked soon" + } } } diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index 9665155..4b654ab 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -329,5 +329,12 @@ "pricing": { "bad_limit": "A discount limit must be a number of 0 or more, or empty for no limit.", "bad_condition": "A condition is incomplete: fill in all its values." + }, + "floor_plan": { + "not_found": "Floor plan not found.", + "bad_outline": "The floor's shape needs 3 to 100 corners, all inside the plan.", + "bad_zone": "That zone no longer exists.", + "bad_background": "The background must be a picture from the media library.", + "bad_layout": "The layout has a table twice or a place that is not a number." } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index bdc83c1..e43522d 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -2097,5 +2097,90 @@ "max_items_per_orderHint": "Discounted items on one order." } } + }, + "floor": { + "pageTabs": "Tables", + "tabs": { + "list": "Tables and zones", + "floor": "Floor plans" + }, + "title": "Floor plans", + "intro": "Draw where the tables stand. A zone can have several floor plans (e.g. ground floor and upstairs). The phones, the counter and the Tables page show them live.", + "none": "No floor plan yet", + "noneHint": "Make one, then put the tables on it.", + "new": "New floor plan", + "create": "Create", + "cancel": "Cancel", + "save": "Save", + "saved": "Floor plan saved.", + "delete": "Delete the floor plan", + "deleted": "Floor plan deleted.", + "deleteTitle": "Delete the floor plan?", + "deleteBody": "\"{{name}}\" will be gone. Its tables stay (off any plan) and so do their orders.", + "unsaved": "Not saved", + "undoAll": "Undo the changes", + "name": "Name", + "namePlaceholder": "e.g. Ground floor", + "zone": "Zone", + "zoneHint": "Its tables are the ones offered first; the waiters of other zones don't see it.", + "noZone": "No zone", + "size": "Size", + "sizeHint": "You can change it later.", + "sizes": { + "small": "Small ({{w}} × {{h}})", + "medium": "Medium ({{w}} × {{h}})", + "large": "Large ({{w}} × {{h}})" + }, + "tableCount_one": "{{count}} table", + "tableCount_other": "{{count}} tables", + "grid": "Grid", + "gridSize": "Grid size", + "gridCell": "Cells of {{size}}", + "editShape": "Edit the floor's shape", + "shapeHint": "Drag the corners to give the floor its real shape (an L, a terrace…). Pick a corner to add one after it or remove it.", + "shapeTitle": "The floor's shape", + "cornerCount_one": "{{count}} corner", + "cornerCount_other": "{{count}} corners", + "addCorner": "Add a corner after it", + "removeCorner": "Remove the corner", + "rectangle": "Back to a rectangle", + "canvas": "The floor plan: drag the tables and things; arrow keys move the selected one", + "keysHint": "Arrow keys move what's selected (one grid cell, or 5; with Shift 1), Delete takes it off, Escape lets go.", + "add": "Add", + "newTableShape": "New tables are", + "allPlaced": "Every table is on this plan.", + "zoneTables": "Tables of {{zone}}", + "offPlan": "Tables not on this plan", + "otherTables": "Other zones' tables", + "things": "Things", + "kinds": { + "wall": "Wall", + "bar": "Bar", + "label": "Label", + "area": "Area" + }, + "labelText": "Label", + "settings": "The plan", + "width": "Width", + "height": "Height", + "background": "Background picture", + "backgroundOpacity": "How strong: {{value}}%", + "table": "Table {{name}}", + "shape": "Shape", + "shapes": { + "square": "Square", + "round": "Round", + "long": "Long" + }, + "seats": "Seats", + "seatsHint": "Shown as chairs, and offered as the number of guests.", + "text": "Text", + "itemWidth": "Width", + "itemHeight": "Depth", + "rotation": "Turned {{deg}}°", + "rotateLeft": "Turn left 15°", + "rotateRight": "Turn right 15°", + "takeOff": "Take it off the plan", + "removeThing": "Remove" } } diff --git a/terminal/Dockerfile b/terminal/Dockerfile index 105d32f..b58492f 100644 --- a/terminal/Dockerfile +++ b/terminal/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/terminal/package.json b/terminal/package.json index b17176e..dc93dfe 100644 --- a/terminal/package.json +++ b/terminal/package.json @@ -14,6 +14,7 @@ "dependencies": { "@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/terminal/src/apps/pos/PosScreen.jsx b/terminal/src/apps/pos/PosScreen.jsx index f9b97f3..e78b5a9 100644 --- a/terminal/src/apps/pos/PosScreen.jsx +++ b/terminal/src/apps/pos/PosScreen.jsx @@ -33,6 +33,7 @@ import ReceiptPanel from './ReceiptPanel' import ReceiptsView from './ReceiptsView' import SaleCart from './SaleCart' import TablePanel from './TablePanel' +import TablesMap from './TablesMap' import TablesView from './TablesView' import { useBookings, useMenu, useOnline, useReceipts, useTables } from './usePos' @@ -46,10 +47,12 @@ export default function PosScreen() { } function Counter({ menu, t }) { + const { t: tc } = useTranslation('common') const { language } = useLanguage() const { formatMoney } = useFormat() const [mode, setMode] = useState('sale') // sale | tables | online | receipts const [tableId, setTableId] = useState(null) // the open table (tables mode) + const [tablesView, setTablesView] = useState('list') // list | map (6.8; the list first, always) const [zone, setZone] = useState(null) const [category, setCategory] = useState(() => menu.settings.start_category_id ?? null) const [query, setQuery] = useState('') @@ -207,7 +210,19 @@ function Counter({ menu, t }) { ) : picking ? (
- { setTableId(id); setTableCart([]) }} /> +
+
+ {['list', 'map'].map(v => ( + + ))} +
+
+ {tablesView === 'map' + ? { setTableId(id); setTableCart([]) }} /> + : { setTableId(id); setTableCart([]) }} />} ) : ( <> diff --git a/terminal/src/apps/pos/TablesMap.jsx b/terminal/src/apps/pos/TablesMap.jsx new file mode 100644 index 0000000..ce4483c --- /dev/null +++ b/terminal/src/apps/pos/TablesMap.jsx @@ -0,0 +1,16 @@ +// The tables at the counter as a map (plan step 6.8, D-31): the venue's floor plans with each +// table's state now (@xenia/floorplan FloorView over GET /api/floor-plans/live), live. A tap opens +// the table, as in the list. The list stays the default; the map is a button away. +import { FloorView } from '@xenia/floorplan' +import { Spinner } from '@xenia/ui' +import { useFloorLive } from './usePos' + +export default function TablesMap({ zone, onPick }) { + const { data } = useFloorLive() + if (!data) return
+ return ( +
+ onPick(table.id)} /> +
+ ) +} diff --git a/terminal/src/apps/pos/usePos.js b/terminal/src/apps/pos/usePos.js index 8edaf30..7daeb67 100644 --- a/terminal/src/apps/pos/usePos.js +++ b/terminal/src/apps/pos/usePos.js @@ -92,6 +92,19 @@ export function useTables() { return { data, reload: load } } +/** The table map (6.8): GET /api/floor-plans/live, reloaded on the tables' events and plan changes. */ +export function useFloorLive() { + const [data, setData] = useState(null) + const load = useCallback(async () => { + try { setData((await client.get('/api/floor-plans/live', quiet)).data) } catch { /* the shell shows offline */ } + }, []) + const soon = useCoalesced(load) + useEffect(() => { load() }, [load]) + useLiveEvent('ready', load) + useLiveEvents([...TABLE_EVENTS, 'floor_plans.changed', 'reservation_updated'], soon) + return { data, reload: load } +} + /** GET /api/orders/{id} for one order (null id → null); reloads on that order's events. * → { order, gone, reload } (gone: closed or removed meanwhile). */ export function useOrder(orderId) { diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index 6d5a803..5873737 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -953,6 +953,60 @@ try { for (let i = 0; i < 20 && limits?.max_total_value_workday !== null; i++) { await sleep(250); limits = await api('GET', '/api/pricing/discount-settings/global', { token: boss }) } r.check(`${pg} emptied: no limit`, limits?.max_total_value_workday === null, JSON.stringify(limits)) + // ── 6.8: a floor plan drawn in the manager (the phones and the counter: waiter.mjs, terminal.mjs) ── + const fl = 'floor plans:' + await page.goto(`${APP}/management/tables`) + await page.getByTestId('tables-tab-floor').click() + await page.getByTestId('floor-new').first().click() + await page.getByTestId('floor-new-name').fill('E2E ground floor') + await page.getByTestId('floor-create').click() + await page.getByTestId('floor-editor').waitFor({ timeout: 10_000 }) + const ownButtons = page.getByTestId('floor-own-tables').locator('button') + await ownButtons.first().waitFor({ timeout: 5000 }) + const firstId = Number(await ownButtons.first().getAttribute('data-table')) + await ownButtons.first().click() + await page.keyboard.press('Escape') + await page.getByTestId('floor-canvas').click({ position: { x: 5, y: 5 } }) + const secondId = Number(await ownButtons.first().getAttribute('data-table')) + await ownButtons.first().click() + await page.getByTestId('floor-shape-round').click() + await page.getByTestId('floor-canvas').click({ position: { x: 5, y: 5 } }) + await page.getByTestId('floor-add-bar').click() + // drag the first table 150 px to the right + await page.locator(`[data-testid="floor-canvas"] [data-testid="floor-table"][data-table="${firstId}"]`).scrollIntoViewIfNeeded() + const tb = await page.locator(`[data-testid="floor-canvas"] [data-testid="floor-table"][data-table="${firstId}"]`).boundingBox() + await page.mouse.move(tb.x + tb.width / 2, tb.y + tb.height / 2) + await page.mouse.down() + await page.mouse.move(tb.x + tb.width / 2 + 75, tb.y + tb.height / 2, { steps: 5 }) + await page.mouse.move(tb.x + tb.width / 2 + 150, tb.y + tb.height / 2 + 60, { steps: 5 }) + await page.mouse.up() + // an irregular floor: a corner more, pulled in + await page.getByTestId('floor-shape-mode').click() + await page.getByTestId('floor-corner').nth(1).click() + await page.getByTestId('floor-corner-add').click() + await page.getByTestId('floor-corner').nth(2).scrollIntoViewIfNeeded() + const corner = await page.getByTestId('floor-corner').nth(2).boundingBox() + await page.mouse.move(corner.x + corner.width / 2, corner.y + corner.height / 2) + await page.mouse.down() + await page.mouse.move(corner.x - 120, corner.y + 10, { steps: 6 }) + await page.mouse.up() + await page.getByTestId('floor-shape-mode').click() + await page.screenshot({ path: path.join(OUT, 'manager-floor-editor.png') }) + await page.getByTestId('floor-save').click() + let saved = null + for (let i = 0; i < 30 && !(saved?.tables?.filter(x => x.plan_id != null).length >= 2); i++) { await sleep(250); saved = await api('GET', '/api/floor-plans', { token: boss }) } + const sp = saved.plans.find(x => x.name === 'E2E ground floor') + const placedNow = saved.tables.filter(x => x.plan_id === sp?.id) + const t1 = placedNow.find(x => x.id === firstId) + r.check(`${fl} drawn and saved: two tables (one round), the bar, a five-corner floor`, placedNow.length === 2 && placedNow.find(x => x.id === secondId)?.shape === 'round' + && sp.items.some(i => i.kind === 'bar') && sp.outline?.length === 5, JSON.stringify({ placed: placedNow.map(x => [x.id, x.x, x.y, x.shape]), outline: sp?.outline })) + r.check(`${fl} the dragged table moved, on the grid`, t1 && t1.x > 600 && t1.x % 20 === 0, JSON.stringify(t1)) + await page.goto(`${APP}/tables`) + await page.getByTestId('tables-view-map').click() + r.check(`${fl} the Tables page shows the plan live`, await page.locator('[data-testid="manager-floor"] [data-testid="floor-table"]').first().waitFor({ timeout: 10_000 }).then(() => true).catch(() => false) + && await page.locator('[data-testid="manager-floor"] [data-testid="floor-table"]').count() >= 2) + await page.screenshot({ path: path.join(OUT, 'manager-floor-live.png') }) + await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } }) await page.goto(`${APP}/online-orders`) await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {}) diff --git a/tests/e2e/run-all.mjs b/tests/e2e/run-all.mjs index e72eec1..d49fe66 100644 --- a/tests/e2e/run-all.mjs +++ b/tests/e2e/run-all.mjs @@ -15,6 +15,7 @@ const suites = [ ['unit: packages/api (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/api'], CS], ['unit: packages/access (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/access'], CS], ['unit: packages/signage (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/signage'], CS], + ['unit: packages/floorplan (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/floorplan'], CS], ['unit: manager_dashboard (node --test)', 'npm', ['test', '--silent', '-w', 'manager-dashboard'], CS], ['lint: manager_dashboard (v2 code)', 'npm', ['run', 'lint', '--silent', '-w', 'manager-dashboard'], CS], ['unit: terminal (node --test)', 'npm', ['test', '--silent', '-w', 'terminal'], CS], diff --git a/tests/e2e/terminal.mjs b/tests/e2e/terminal.mjs index 65b4f8c..df7097a 100644 --- a/tests/e2e/terminal.mjs +++ b/tests/e2e/terminal.mjs @@ -522,6 +522,26 @@ try { return card?.dataset.state === 'open' && card.textContent.includes(due) }, [phoneTable.id, (2 * simple.price).toFixed(2)], { timeout: 8000 }).then(() => true).catch(() => false)) await page.screenshot({ path: path.join(OUT, 'terminal-pos-tables.png') }) + + // ── 6.8: the floor plan at the counter, with live states ────────────────── + const third = counterTables.find(t => !t.order && mariaTables.has(t.id) && t.id !== shared.id && t.id !== phoneTable.id) + const fp = await api('POST', '/api/floor-plans', { token: boss, body: { name: 'E2E floor', width: 1000, height: 600, grid_on: true, grid_size: 50 } }) + await api('PUT', `/api/floor-plans/${fp.id}/layout`, { token: boss, body: { + tables: [shared, phoneTable, third].map((t, i) => ({ id: t.id, x: 200 + i * 250, y: 300, width: 100, height: 100, shape: i === 1 ? 'round' : 'square', seats: 4 })), + items: [{ kind: 'bar', x: 500, y: 60, width: 400, height: 60 }] } }) + await page.getByTestId('pos-tables-map').click() + const mapTable = id => page.locator(`[data-testid="pos-floor"] [data-testid="floor-table"][data-table="${id}"]`) + r.check("6.8: the counter shows the floor plan: the phone's table open, the others free", await mapTable(phoneTable.id).waitFor({ timeout: 10_000 }).then(() => true).catch(() => false) + && await mapTable(phoneTable.id).getAttribute('data-state') === 'open' && await mapTable(shared.id).getAttribute('data-state') === 'free') + const thirdOrder = await api('POST', '/api/orders/', { token: maria, body: { table_id: third.id } }) + await api('POST', `/api/orders/${thirdOrder.id}/items`, { token: maria, body: { lines: [{ product_id: simple.id, quantity: 1 }] } }) + r.check("6.8: a table opened on the phone turns open on the counter's map at once", await page.waitForFunction(id => + document.querySelector(`[data-testid="pos-floor"] [data-testid="floor-table"][data-table="${id}"]`)?.dataset.state === 'open', third.id, { timeout: 8000 }).then(() => true).catch(() => false)) + await page.screenshot({ path: path.join(OUT, 'terminal-pos-floor.png') }) + await mapTable(third.id).click() + r.check('6.8: a tap on the map opens the table', await shown(page, 'table-panel', 5000) && Number(await page.getByTestId('table-panel').getAttribute('data-order')) === thirdOrder.id) + await page.getByTestId('mode-tables').click() + await page.getByTestId('pos-tables-list').click().catch(() => {}) phoneWs.close() // ── 3.3d: online orders on the POS ────────────────────────────────────── diff --git a/tests/e2e/waiter.mjs b/tests/e2e/waiter.mjs index b06b108..979f01b 100644 --- a/tests/e2e/waiter.mjs +++ b/tests/e2e/waiter.mjs @@ -358,6 +358,30 @@ try { await api('PUT', '/api/waiters/roles/waiter/permissions', { token: boss, body: { keys: waiterRole.default_keys } }) await a.goto(`${APP}/tables`) + // ── 6.8: the floor plan on the phone; the list stays the default (D-31) ── + const liveNow = (await api('GET', '/api/floor-plans/live', { token: tokenA })).tables + const [fA, fB] = liveNow.filter(t => t.state === 'free') + const fp = await api('POST', '/api/floor-plans', { token: boss, body: { name: 'E2E floor', group_id: fA.group_id, width: 800, height: 500 } }) + await api('PUT', `/api/floor-plans/${fp.id}/layout`, { token: boss, body: { + tables: [fA, fB].map((t, i) => ({ id: t.id, x: 200 + i * 300, y: 250, width: 120, height: 90, shape: 'long', seats: 6 })) } }) + await a.getByTestId('tables-map-toggle').waitFor({ timeout: 10_000 }) + r.check('6.8: the Tables page opens on the list', await a.getByTestId('tables-map-toggle').getAttribute('aria-pressed') === 'false' && await a.getByTestId('waiter-floor').count() === 0) + await a.getByTestId('tables-map-toggle').click() + const onMap = id => a.locator(`[data-testid="waiter-floor"] [data-testid="floor-table"][data-table="${id}"]`) + r.check('6.8: Map shows the floor plan with the tables free', await onMap(fA.id).waitFor({ timeout: 10_000 }).then(() => true).catch(() => false) + && await onMap(fA.id).getAttribute('data-state') === 'free') + const oF = await api('POST', '/api/orders/', { token: tokenA, body: { table_id: fA.id } }) + await api('POST', `/api/orders/${oF.id}/items`, { token: tokenA, body: { lines: [{ product_id: plain.id, quantity: 1 }] } }) + r.check('6.8: the waiter opens a table → it turns "yours" on the map at once', await a.waitForFunction(id => + document.querySelector(`[data-testid="waiter-floor"] [data-testid="floor-table"][data-table="${id}"]`)?.dataset.state === 'mine', fA.id, { timeout: 8000 }).then(() => true).catch(() => false)) + await a.screenshot({ path: path.join(OUT, 'waiter-floor.png') }) + await onMap(fA.id).click() + r.check('6.8: a tap opens the table', await a.waitForURL(new RegExp(`/tables/${fA.id}$`), { timeout: 8000 }).then(() => true).catch(() => false)) + await api('DELETE', `/api/orders/${oF.id}`, { token: boss }).catch(() => {}) + await a.goto(`${APP}/tables`) + await a.getByTestId('tables-map-toggle').waitFor({ timeout: 10_000 }) + r.check("6.8: back on Tables: the list again (the map isn't remembered)", await a.getByTestId('tables-map-toggle').getAttribute('aria-pressed') === 'false') + // ── 4.6: the look on the shared tokens: the venue's colour and light / dark reach the phone ── const accentOf = () => a.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--x-accent-rgb').trim()) r.check('4.6: the venue colour (default amber) is on the phone', await a.evaluate(() => document.documentElement.dataset.venueTheme) === 'amber') diff --git a/waiter_pwa/Dockerfile b/waiter_pwa/Dockerfile index 6fced8c..79b4eb9 100644 --- a/waiter_pwa/Dockerfile +++ b/waiter_pwa/Dockerfile @@ -15,6 +15,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/waiter_pwa/package.json b/waiter_pwa/package.json index e35e7a3..cc76b2b 100644 --- a/waiter_pwa/package.json +++ b/waiter_pwa/package.json @@ -21,6 +21,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/ui": "^0.0.0", "axios": "^1.21.1", diff --git a/waiter_pwa/src/components/FloorMapView.jsx b/waiter_pwa/src/components/FloorMapView.jsx new file mode 100644 index 0000000..389b000 --- /dev/null +++ b/waiter_pwa/src/components/FloorMapView.jsx @@ -0,0 +1,36 @@ +// The tables as a map on the phone (plan step 6.8, D-31): the floor plans of the waiter's zones with +// each table's state now (@xenia/floorplan FloorView over GET /api/floor-plans/live). The Tables +// page always opens on the list; this is its "Map" mode. Refreshes on the tables' live events and +// after a reconnect. A tap opens the table like the list does. +import { useCallback, useEffect, useState } from 'react' +import { FloorView } from '@xenia/floorplan' +import client from '../api/client' + +const EVENTS = ['order_updated', 'order_paid', 'order_closed', 'table_list_changed', 'kds_order_updated', 'kds_item_updated', + 'reservation_updated', 'floor_plans.changed'] + +export default function FloorMapView({ zone, onPick }) { + const [data, setData] = useState(null) + const load = useCallback(async () => { + try { setData((await client.get('/api/floor-plans/live')).data) } catch { /* offline: keep what we have */ } + }, []) + useEffect(() => { + const first = setTimeout(load, 0) + let timer = null + const soon = () => { clearTimeout(timer); timer = setTimeout(load, 150) } + const onEvent = e => { if (EVENTS.includes(e.detail?.type)) soon() } + window.addEventListener('live-event', onEvent) + window.addEventListener('live-reconnected', load) + const tick = setInterval(load, 60_000) + return () => { + clearTimeout(first); clearTimeout(timer); clearInterval(tick) + window.removeEventListener('live-event', onEvent) + window.removeEventListener('live-reconnected', load) + } + }, [load]) + return ( +
+ {data ? : null} +
+ ) +} diff --git a/waiter_pwa/src/pages/TableListPage.jsx b/waiter_pwa/src/pages/TableListPage.jsx index 45aed8d..86da042 100644 --- a/waiter_pwa/src/pages/TableListPage.jsx +++ b/waiter_pwa/src/pages/TableListPage.jsx @@ -3,6 +3,7 @@ import { useAllowed } from '@xenia/access' import { useFormat, useTranslation } from '@xenia/i18n' import { useNavigate, useSearchParams } from 'react-router-dom' import TableCard from '../components/TableCard' +import FloorMapView from '../components/FloorMapView' import useAuthStore from '../store/authStore' import useTableColourStore from '../store/tableColourStore' import useConnectionStore from '../store/connectionStore' @@ -334,6 +335,8 @@ export default function TableListPage() { const PULL_THRESHOLD = 72 const navigate = useNavigate() + const { t: tc } = useTranslation('common') + const [mapView, setMapView] = useState(false) // 6.8: the floor plans; the page always opens on the list (D-31) const [searchParams] = useSearchParams() const pageTab = searchParams.get('tab') === 'orders' ? 'orders' : 'tables' const filterBtnRef = useRef(null) @@ -675,10 +678,20 @@ export default function TableListPage() { onClick={() => setActiveZoneTab(effectiveZoneTab === g.id ? 'all' : g.id)} /> ))} + +
{/* ── Standalone view OR Table grid ────────────────────────────────── */} - {effectiveZoneTab === 'standalone' ? ( + {mapView && effectiveZoneTab !== 'standalone' ? ( + navigate(tb.order ? `/tables/${tb.id}` : `/tables/${tb.id}/add?new=1`)} /> + ) : effectiveZoneTab === 'standalone' ? ( ) : (