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:
@@ -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}
|
||||
Reference in New Issue
Block a user