// Management → Tables → List (plan step 6.14b; was the v1 TablesConfigTab, kept in 6.8a next to
// the floor plans): every table by zone, for typing and changes in bulk. Zones as tabs (drag to
// reorder; a zone's name, prefix and colour; add many tables at once with the zone's prefix,
// numbered on from the last), a table's name (up to 6 characters, empty = numbered by the server),
// zone and seats; names used twice stand out; turn a table off (kept, not used) or delete it (not
// while it has an open order); pick several to move them to a zone, rename them in a series, or
// delete them.
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { GripVertical, Pencil, Plus, Power, Trash2, X } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { BatchDialog, MoveDialog, RenameDialog, TableDialog, ZoneDialog } from './TableDialogs'
import { duplicateNames, reorder, tablesOf } from './tablesLogic'
const LIVE = ['table_list_changed'] // routers/tables.py
export default function TablesListTab() {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const [inactive, setInactive] = useState(false)
const [tab, setTab] = useState('all')
const [picking, setPicking] = useState(false)
const [picked, setPicked] = useState(() => new Set())
const [dialog, setDialog] = useState(null) // { kind, table | zone | ids }
const [drag, setDrag] = useState(null) // { id, gap }
const tablesQ = useLiveQuery({ queryKey: ['tables-all', inactive], events: LIVE, queryFn: () => client.get('/api/tables/', { params: { include_inactive: inactive } }).then(r => r.data) })
const zonesQ = useLiveQuery({ queryKey: ['table-groups'], events: LIVE, queryFn: () => client.get('/api/tables/groups').then(r => r.data) })
const tables = tablesQ.data ?? []
const zones = zonesQ.data ?? []
const changed = () => { for (const k of ['tables-all', 'tables', 'table-groups']) qc.invalidateQueries({ queryKey: [k] }) }
const onError = err => toast.error(errorMessage(err, t))
const close = () => setDialog(null)
const stopPicking = () => { setPicking(false); setPicked(new Set()) }
const shown = tablesOf(tables, tab)
const dupes = duplicateNames(tables)
const allPicked = shown.length > 0 && shown.every(x => picked.has(x.id))
const pick = id => setPicked(p => { const n = new Set(p); if (n.has(id)) n.delete(id); else n.add(id); return n })
const pickAll = () => setPicked(p => { const n = new Set(p); shown.forEach(x => (allPicked ? n.delete(x.id) : n.add(x.id))); return n })
const name = x => x.label || t('tablesList.numbered', { n: x.number })
const update = useMutation({ mutationFn: ({ id, ...body }) => client.put(`/api/tables/${id}`, body), onSuccess: () => { toast.success(t('tablesList.saved')); changed() }, onError })
const remove = useMutation({
mutationFn: ({ id, hard }) => client.delete(`/api/tables/${id}`, { params: { hard } }),
onSuccess: (_r, v) => { toast.success(t(v.hard ? 'tablesList.deleted' : 'tablesList.turnedOff')); close(); changed() }, onError,
})
const reorderZones = useMutation({ mutationFn: ids => client.put('/api/tables/groups/reorder', ids), onSuccess: changed, onError })
/** The same change to many tables, one request each; says how many didn't take. */
const each = async (ids, fn, done) => {
const res = await Promise.allSettled(ids.map(fn))
const failed = res.filter(r => r.status === 'rejected').length
if (failed) toast.error(t('tablesList.someFailed', { count: failed }))
else toast.success(done)
close(); stopPicking(); changed()
}
if (tablesQ.isPending || zonesQ.isPending) return
const tabs = [{ id: 'all', label: t('tablesList.all') }, ...zones.map(z => ({ id: z.id, label: z.prefix ? `${z.prefix} · ${z.name}` : z.name, color: z.color, zone: z })),
...(tables.some(x => !x.group_id) ? [{ id: 'none', label: t('tablesList.noZone') }] : [])]
const count = id => tablesOf(tables, id).length
const zone = zones.find(z => z.id === tab)
const dropOn = (e, i) => { e.preventDefault(); const r = e.currentTarget.getBoundingClientRect(); setDrag(d => d && { ...d, gap: e.clientX < r.left + r.width / 2 ? i : i + 1 }) }
const drop = () => {
if (drag?.gap != null) {
const ids = zones.map(z => z.id)
const next = reorder(ids, drag.id, drag.gap)
if (next.join() !== ids.join()) reorderZones.mutate(next)
}
setDrag(null)
}
return (
{picking || picked.size ? (<>
} onClick={stopPicking}>{picked.size ? t('tablesList.picked', { count: picked.size }) : t('tablesList.pick')}
{picked.size > 0 && (<>
>)}
>) : (
{t('tablesList.counts', { tables: tables.length, zones: zones.length })}
{tables.some(x => !x.is_active) && <> · {t('tablesList.offCount', { count: tables.filter(x => !x.is_active).length })}>}
)}
{!picking && }
} onClick={() => setDialog({ kind: 'zone', zone: {} })} data-testid="zone-new">{t('tablesList.newZone')}
} onClick={() => setDialog({ kind: 'table', table: null })} data-testid="table-new">{t('tablesList.newTable')}
{tabs.map(x => {
const i = x.zone ? zones.indexOf(x.zone) : -1
return (
)
})}
{zone && (
{zone.name}
{zone.prefix &&
{zone.prefix}}
} onClick={() => setDialog({ kind: 'zone', zone })}>{t('tablesList.editZone')}
} className="ml-auto" onClick={() => setDialog({ kind: 'batch', zone })} data-testid="tables-batch">{t('tablesList.addMany')}
)}
{dialog?.kind === 'table' &&
{ close(); changed() }} />}
{dialog?.kind === 'zone' && { close(); changed() }} />}
{dialog?.kind === 'batch' && { close(); changed() }} />}
{dialog?.kind === 'move' && each([...picked], id => client.put(`/api/tables/${id}`, { group_id: groupId }), t('tablesList.moved', { count: picked.size }))} />}
{dialog?.kind === 'rename' && picked.has(x.id))} onClose={close}
onRename={names => { const ids = shown.filter(x => picked.has(x.id)).map(x => x.id); return each(ids, (id, k) => client.put(`/api/tables/${id}`, { label: names[k] }), t('tablesList.renamed', { count: ids.length })) }} />}
{(dialog?.kind === 'off' || dialog?.kind === 'delete') && (
)
}