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
+1
View File
@@ -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/
+1
View File
@@ -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",
@@ -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 (
<div className="flex flex-col h-full min-h-0">
<TablesConfigTab />
<div className="flex flex-wrap gap-1 border-b border-line px-4 md:px-6 pt-3 shrink-0" role="tablist" aria-label={t('floor.pageTabs')}>
{TABS.map(k => (
<button key={k} type="button" role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`tables-tab-${k}`}
className={`px-3 py-2 -mb-px border-b-2 text-label font-medium transition-colors duration-fast
${tab === k ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink'}`}>
{t(`floor.tabs.${k}`)}
</button>
))}
</div>
<div className="flex-1 min-h-0 overflow-y-auto">
{tab === 'list' ? <TablesConfigTab /> : <FloorPlansTab />}
</div>
</div>
)
}
+17 -3
View File
@@ -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() {
/>
)}
<div className="flex items-center justify-end flex-wrap gap-3">
<div className="flex rounded-control border border-line overflow-hidden mr-auto" role="group">
{['list', 'map'].map(v => (
<button key={v} type="button" aria-pressed={view === v} onClick={() => setView(v)} data-testid={`tables-view-${v}`}
className={`px-3 py-1.5 text-label font-medium ${view === v ? 'bg-accent-soft text-accent-ink' : 'bg-surface text-ink-2 hover:bg-surface-2'}`}>
{t(`floorMap.${v}`)}
</button>
))}
</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
<MultiSelectDropdown
label="Κατάσταση"
@@ -728,11 +740,13 @@ export default function TablesPage() {
</div>
</div>
{filtered.length === 0 && (
{view === 'map' && <LiveFloor zone={zoneFilter.length === 1 && zoneFilter[0] !== '__none__' ? Number(zoneFilter[0]) : null} onOpen={id => navigate(`/orders/${id}`)} />}
{view === 'list' && filtered.length === 0 && (
<p className="text-center text-gray-400 py-16">Δεν βρέθηκαν τραπέζια.</p>
)}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(330px, 1fr))', gap: 16 }}>
{view === 'list' && <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(330px, 1fr))', gap: 16 }}>
{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() {
/>
)
})}
</div>
</div>}
{pendingPrintOrders.length > 0 && (
<div className="bg-white rounded-2xl border border-orange-200 shadow-sm overflow-hidden">
@@ -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 (
<div className="grid gap-4 lg:grid-cols-[1fr_18rem] items-start" data-testid="floor-editor" data-plan={saved.id}>
<div className="grid gap-3 content-start min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-body-lg font-semibold text-ink mr-auto">{form.name || saved.name}</h2>
{dirty && <span className="px-2 py-0.5 rounded-full bg-warning-soft text-warning-ink text-caption font-medium" data-testid="floor-dirty">{t('floor.unsaved')}</span>}
<Button variant="secondary" size="sm" icon={<Undo2 size={16} />} disabled={!dirty || busy}
onClick={() => { setLayout(initial); setForm({ ...saved }); setSel(null) }}>{t('floor.undoAll')}</Button>
<Button size="sm" icon={<Save size={16} />} loading={busy} disabled={!dirty || !form.name.trim()} onClick={save} data-testid="floor-save">{t('floor.save')}</Button>
</div>
<div className="flex flex-wrap items-center gap-3 text-label text-ink-2">
<Switch checked={!!form.grid_on} onChange={v => setF('grid_on', v)} label={t('floor.grid')} data-testid="floor-grid" />
{form.grid_on && (
<Select size="sm" value={String(form.grid_size)} onChange={e => setF('grid_size', Number(e.target.value))} aria-label={t('floor.gridSize')}
options={[...new Set([...GRID_SIZES, form.grid_size])].sort((a, b) => a - b).map(v => ({ value: String(v), label: t('floor.gridCell', { size: v }) }))} />
)}
<Switch checked={shapeMode} onChange={v => { setShapeMode(v); setSel(null) }} label={t('floor.editShape')} data-testid="floor-shape-mode" />
</div>
{shapeMode && <p className="text-caption text-ink-2">{t('floor.shapeHint')}</p>}
<div className="rounded-card border border-line bg-canvas overflow-auto max-h-[70vh]">
<svg ref={svg} viewBox={`${-PAD} ${-PAD} ${plan.width + 2 * PAD} ${plan.height + 2 * PAD}`} tabIndex={0} onKeyDown={keys} role="application" aria-label={t('floor.canvas')}
className="block w-full h-auto touch-none select-none outline-none focus-visible:ring-2 focus-visible:ring-[var(--x-accent)]"
onPointerMove={move} onPointerUp={end} onPointerCancel={end} onPointerDown={() => setSel(null)} data-testid="floor-canvas">
<Floor plan={plan} showGrid={!!plan.grid_on} />
{layout.items.map(i => (
<Item key={i.key} item={i} label={t('floor.kinds.bar')} selected={sel?.type === 'item' && sel.id === i.key}
style={{ cursor: shapeMode ? 'default' : 'move' }} pointerEvents={shapeMode ? 'none' : undefined}
onPointerDown={e => start(e, { type: 'item', id: i.key })} data-testid="floor-item" data-kind={i.kind} />
))}
{layout.tables.map(tb => (
<TableShape key={tb.id} table={tb} live={false} selected={sel?.type === 'table' && sel.id === tb.id}
style={{ cursor: shapeMode ? 'default' : 'move' }} pointerEvents={shapeMode ? 'none' : undefined}
onPointerDown={e => start(e, { type: 'table', id: tb.id })} data-testid="floor-table" />
))}
{shapeMode && corners.map(([x, y], i) => (
<circle key={i} cx={x} cy={y} r={Math.max(10, plan.width / 90)} data-testid="floor-corner"
fill={sel?.type === 'corner' && sel.index === i ? 'var(--x-accent)' : 'var(--x-surface)'} stroke="var(--x-accent)" strokeWidth="3"
style={{ cursor: 'grab' }} onPointerDown={e => start(e, { type: 'corner', index: i })} />
))}
</svg>
</div>
<p className="text-caption text-ink-3">{t('floor.keysHint')}</p>
</div>
<aside className="grid gap-4 content-start lg:max-h-[calc(100vh-10rem)] lg:overflow-y-auto">
{shapeMode ? (
<Panel title={t('floor.shapeTitle')}>
<p className="text-caption text-ink-2">{t('floor.cornerCount', { count: corners.length })}</p>
<div className="flex flex-wrap gap-2">
<Button size="sm" variant="secondary" disabled={sel?.type !== 'corner'} data-testid="floor-corner-add"
onClick={() => setForm(f => ({ ...f, outline: addCorner(outlineOf(f), sel.index) }))}>{t('floor.addCorner')}</Button>
<Button size="sm" variant="secondary" disabled={sel?.type !== 'corner' || corners.length <= 3}
onClick={() => { setForm(f => ({ ...f, outline: removeCorner(outlineOf(f), sel.index) })); setSel(null) }}>{t('floor.removeCorner')}</Button>
<Button size="sm" variant="ghost" disabled={!form.outline} onClick={() => { setF('outline', null); setSel(null) }}>{t('floor.rectangle')}</Button>
</div>
</Panel>
) : selected ? (
<Selected thing={selected} sel={sel} plan={plan} t={t}
onChange={patch => setLayout(l => update(l, sel, patch))}
onRemove={() => { setLayout(l => remove(l, sel)); setSel(null) }} />
) : (
<Panel title={t('floor.add')}>
<Field label={t('floor.newTableShape')}>
<Select size="sm" value={newShape} onChange={e => setNewShape(e.target.value)} options={SHAPES.map(s => ({ value: s, label: t(`floor.shapes.${s}`) }))} />
</Field>
{own.length + other.length === 0 ? <p className="text-caption text-ink-3">{t('floor.allPlaced')}</p> : (
<div className="grid gap-2">
<TableButtons tables={own} title={plan.group_id != null ? t('floor.zoneTables', { zone: zoneName(plan.group_id) }) : t('floor.offPlan')}
onAdd={tb => { setLayout(l => placeTable(l, plan, tb, newShape)); setSel({ type: 'table', id: tb.id }) }} />
{other.length > 0 && <TableButtons tables={other} title={t('floor.otherTables')} quiet
onAdd={tb => { setLayout(l => placeTable(l, plan, tb, newShape)); setSel({ type: 'table', id: tb.id }) }} />}
</div>
)}
<div className="grid gap-1.5">
<span className="text-label font-semibold text-ink">{t('floor.things')}</span>
<div className="flex flex-wrap gap-2">
{ITEM_KINDS.map(k => (
<Button key={k} size="sm" variant="secondary" data-testid={`floor-add-${k}`}
onClick={() => { const r = addItem(layout, plan, k, k === 'label' ? t('floor.labelText') : null); setLayout(r.layout); setSel({ type: 'item', id: r.key }) }}>
{t(`floor.kinds.${k}`)}
</Button>
))}
</div>
</div>
</Panel>
)}
<Panel title={t('floor.settings')}>
<Field label={t('floor.name')}><Input size="sm" value={form.name} maxLength={60} onChange={e => setF('name', e.target.value)} data-testid="floor-name" /></Field>
<Field label={t('floor.zone')} hint={t('floor.zoneHint')}>
<Select size="sm" value={form.group_id ?? ''} onChange={e => setF('group_id', e.target.value === '' ? null : Number(e.target.value))}
options={[{ value: '', label: t('floor.noZone') }, ...groups.map(g => ({ value: g.id, label: g.name }))]} />
</Field>
<div className="grid grid-cols-2 gap-2">
<Field label={t('floor.width')}>
<Input size="sm" type="number" min={200} max={6000} step={50} value={form.width}
onChange={e => { const w = Number(e.target.value); setForm(f => ({ ...f, width: w, outline: fitOutline(f.outline, w, f.height) })) }} />
</Field>
<Field label={t('floor.height')}>
<Input size="sm" type="number" min={200} max={6000} step={50} value={form.height}
onChange={e => { const h = Number(e.target.value); setForm(f => ({ ...f, height: h, outline: fitOutline(f.outline, f.width, h) })) }} />
</Field>
</div>
<MediaField value={form.background} onChange={img => setF('background', img)} label={t('floor.background')} testid="floor-background" />
{form.background && (
<label className="grid gap-1 text-label text-ink-2">{t('floor.backgroundOpacity', { value: Math.round((form.background_opacity ?? 0.6) * 100) })}
<input type="range" min="0.1" max="1" step="0.05" value={form.background_opacity ?? 0.6} onChange={e => setF('background_opacity', Number(e.target.value))} />
</label>
)}
<Button size="sm" variant="ghost" icon={<Trash2 size={16} />} onClick={() => setDeleting(true)} className="justify-self-start text-danger-ink">{t('floor.delete')}</Button>
</Panel>
</aside>
{deleting && (
<Dialog open size="sm" title={t('floor.deleteTitle')} onClose={() => setDeleting(false)}
footer={<>
<Button variant="secondary" onClick={() => setDeleting(false)}>{t('floor.cancel')}</Button>
<Button variant="danger" loading={busy} data-testid="floor-confirm-delete" onClick={async () => {
setBusy(true)
try { await api.deletePlan(saved.id); toast.success(t('floor.deleted')); onDeleted() } catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
}}>{t('floor.delete')}</Button>
</>}>
<p>{t('floor.deleteBody', { name: saved.name })}</p>
</Dialog>
)}
</div>
)
}
function Panel({ title, children }) {
return (
<section className="grid gap-3 p-4 rounded-card border border-line bg-surface shadow-raised">
<h3 className="text-label font-semibold text-ink uppercase tracking-wide">{title}</h3>
{children}
</section>
)
}
function TableButtons({ tables, title, onAdd, quiet = false }) {
if (!tables.length) return null
return (
<div className="grid gap-1.5">
<span className={cx('text-caption', quiet ? 'text-ink-3' : 'text-ink-2')}>{title}</span>
<div className="flex flex-wrap gap-1.5" data-testid={quiet ? 'floor-other-tables' : 'floor-own-tables'}>
{tables.map(tb => (
<button key={tb.id} type="button" onClick={() => onAdd(tb)} data-table={tb.id} data-name={tb.name}
className="min-w-[2.75rem] px-2.5 py-1.5 rounded-control border border-line bg-surface-2 text-label font-semibold text-ink hover:border-accent hover:bg-accent-soft">
{tb.name}
</button>
))}
</div>
</div>
)
}
function Selected({ thing, sel, plan, t, onChange, onRemove }) {
const isTable = sel.type === 'table'
const setSize = (w, h) => onChange(resize(thing, plan, w, h))
return (
<Panel title={isTable ? t('floor.table', { name: thing.name }) : t(`floor.kinds.${thing.kind}`)}>
{isTable && (
<>
<Field label={t('floor.shape')}>
<div className="flex gap-1.5" role="radiogroup">
{SHAPES.map(s => (
<button key={s} type="button" role="radio" aria-checked={thing.shape === s} data-testid={`floor-shape-${s}`}
onClick={() => onChange({ shape: s, ...defaultSize(s, thing.seats, plan.grid_on ? plan.grid_size : 0) })}
className={cx('flex-1 px-2 py-1.5 rounded-control border text-label font-medium',
thing.shape === s ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{t(`floor.shapes.${s}`)}
</button>
))}
</div>
</Field>
<Field label={t('floor.seats')} hint={t('floor.seatsHint')}>
<Input size="sm" type="number" min={0} max={99} value={thing.seats ?? ''} data-testid="floor-seats"
onChange={e => onChange({ seats: e.target.value === '' ? null : Math.max(0, Math.min(99, Math.round(Number(e.target.value)))) })} />
</Field>
</>
)}
{!isTable && thing.kind !== 'wall' && (
<Field label={t('floor.text')}>
<Input size="sm" value={thing.text ?? ''} maxLength={60} onChange={e => onChange({ text: e.target.value })} data-testid="floor-item-text" />
</Field>
)}
<div className="grid grid-cols-2 gap-2">
<Field label={t('floor.itemWidth')}><Input size="sm" type="number" min={4} value={thing.width} onChange={e => setSize(Number(e.target.value), undefined)} /></Field>
<Field label={t('floor.itemHeight')}><Input size="sm" type="number" min={4} value={thing.height} onChange={e => setSize(undefined, Number(e.target.value))} /></Field>
</div>
<div className="flex items-center gap-1.5">
<span className="text-label text-ink-2 mr-auto">{t('floor.rotation', { deg: Math.round(thing.rotation || 0) })}</span>
<IconButton size="sm" variant="secondary" label={t('floor.rotateLeft')} onClick={() => onChange({ rotation: rotate(thing.rotation || 0, -15) })}><RotateCcw size={16} /></IconButton>
<IconButton size="sm" variant="secondary" label={t('floor.rotateRight')} onClick={() => onChange({ rotation: rotate(thing.rotation || 0, 15) })} data-testid="floor-rotate"><RotateCw size={16} /></IconButton>
<Button size="sm" variant="secondary" onClick={() => onChange({ rotation: rotate(thing.rotation || 0, 90) })}>90°</Button>
</div>
<Button size="sm" variant="ghost" icon={<Trash2 size={16} />} onClick={onRemove} className="justify-self-start text-danger-ink" data-testid="floor-remove">
{isTable ? t('floor.takeOff') : t('floor.removeThing')}
</Button>
</Panel>
)
}
@@ -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 <div className="flex justify-center p-8"><Spinner /></div>
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 (
<div className="p-4 md:p-6 grid gap-4" data-testid="floor-plans">
<nav className="grid gap-2" aria-label={t('floor.title')}>
<p className="text-label text-ink-2 max-w-4xl">{t('floor.intro')}</p>
<div className="flex flex-wrap items-end gap-x-4 gap-y-2">
{byZone.map(z => (
<div key={z.id ?? 'none'} className="grid gap-1">
<span className="text-caption font-semibold text-ink-3 uppercase tracking-wide">{z.name}</span>
<div className="flex flex-wrap gap-1.5">
{z.plans.map(p => (
<button key={p.id} type="button" onClick={() => setChosen(p.id)} aria-current={plan?.id === p.id ? 'true' : undefined} data-testid="floor-plan-item" data-name={p.name}
className={cx('px-3 py-1.5 rounded-control border text-label font-medium transition-colors duration-fast text-left',
plan?.id === p.id ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface hover:bg-surface-2 text-ink')}>
{p.name}
<span className="ml-2 text-caption text-ink-3 font-normal">{t('floor.tableCount', { count: data.tables.filter(x => x.plan_id === p.id).length })}</span>
</button>
))}
</div>
</div>
))}
<Button size="sm" variant="secondary" icon={<Plus size={16} />} onClick={() => setCreating(true)} data-testid="floor-new">{t('floor.new')}</Button>
</div>
</nav>
<main className="min-w-0">
{plan ? (
<FloorEditor key={`${plan.id}:${version}`} plan={plan} data={data} groups={groups}
onSaved={async () => { await refetch(); setVersion(v => v + 1) }}
onDeleted={async () => { setChosen(null); await refetch(); setVersion(v => v + 1) }} />
) : <EmptyState title={t('floor.none')} description={t('floor.noneHint')} action={<Button icon={<Plus size={16} />} onClick={() => setCreating(true)}>{t('floor.new')}</Button>} />}
</main>
{creating && <NewPlan groups={groups} onClose={() => 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)) }
}} />}
</div>
)
}
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 (
<Dialog open size="sm" title={t('floor.new')} onClose={onClose}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('floor.cancel')}</Button>
<Button disabled={!name.trim()} data-testid="floor-create"
onClick={() => onCreate({ name: name.trim(), group_id: zone, width: SIZES[size][0], height: SIZES[size][1], grid_on: true, grid_size: 40 })}>{t('floor.create')}</Button>
</>}>
<div className="grid gap-3">
<Field label={t('floor.name')}><Input value={name} autoFocus maxLength={60} onChange={e => setName(e.target.value)} placeholder={t('floor.namePlaceholder')} data-testid="floor-new-name" /></Field>
<Field label={t('floor.zone')} hint={t('floor.zoneHint')}>
<Select value={zone ?? ''} onChange={e => setZone(e.target.value === '' ? null : Number(e.target.value))} data-testid="floor-new-zone"
options={[...groups.map(g => ({ value: g.id, label: g.name })), { value: '', label: t('floor.noZone') }]} />
</Field>
<Field label={t('floor.size')} hint={t('floor.sizeHint')}>
<Select value={size} onChange={e => 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] }) }))} />
</Field>
</div>
</Dialog>
)
}
@@ -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 (
<div className="h-[calc(100vh-12rem)] min-h-[24rem]" data-testid="manager-floor">
<FloorView data={data} zone={zone} onPick={table => { if (table.order) onOpen(table.order.id) }} />
</div>
)
}
@@ -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)
@@ -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)
+61
View File
@@ -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 })
})
+2 -2
View File
@@ -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"
]
}