feat: the table map (platform-v2 step 6.8, D-31)

- floor_plans / floor_items (0035), tables' plan_id + width/height/rotation/shape;
  /api/floor-plans (set-up, catalog.tables.manage, floor_plans.changed) and
  /api/floor-plans/live (each table's state, guests, waiters, time; zone rule)
- @xenia/floorplan: the drawing (Floor, Item, TableShape, FloorView) and its geometry
  (grid snap in whole cells, outlines, chairs), tested
- manager: Management -> Tables -> Floor plans (editor: drag, grid, irregular floor,
  walls/bar/labels/areas, background picture), Tables page List / Map
- counter POS: Tables List / Map; waiter: Map mode, the list stays the default
- tests: test_floor_plans.py, floor + geometry unit tests, manager/waiter/terminal e2e

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 17:00:45 +02:00
co-authored by Claude Opus 5.5
parent fd3254aa31
commit f4aae6abbc
47 changed files with 2102 additions and 8 deletions
+5
View File
@@ -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."),
@@ -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')
+1
View File
@@ -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)
+58
View File
@@ -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")
+6
View File
@@ -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)
@@ -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'),
+245
View File
@@ -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}
+80
View File
@@ -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]
+92
View File
@@ -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