feat(manager): products and categories on v2, a product in several categories, allergens (platform-v2 step 6.3)
- Management/ProductsTab + ProductFormModal (3.1k lines) → src/pages/products/: category tree, list/grid, toolbar + filters (search folds accents and Latin letters), bulk actions, category dialogs; the editor in editor/ (details, sold at, cost, fiscal; the waiter's choices). Arithmetic in productsLogic.js / editor/formLogic.js (tests/products.test.mjs). - Several categories per product with a main one (D-23): edited in the editor, "also in" on the rows, each category's list ordered on its own (drag or up/down → PUT /reorder with category_id); bulk "move to" / "also list in". The waiter's picker now shows a product in every category. - Allergens: products.allergens (Alembic 0032, core/allergens.py: 14 EU, contains | may_contain, catalog.allergen), in the API, POS menu, menu tablet, catalogue bundles and the cloud snapshot (C-2); @xenia/access allergens.js + <Allergens> shown on the phone, the counter, the tablet. - Bell: only the newest load sets the list (an older answer could hide a live notification). - e2e: manager (two categories, order per category, allergens), terminal / menu tablet / waiter (allergens shown); media saves by test id. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -1,9 +0,0 @@
|
||||
import ProductsTab from '../Management/ProductsTab'
|
||||
|
||||
export default function ProductsPage() {
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
<ProductsTab />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,57 @@
|
||||
// What the selected products get in one go (plan step 6.3): their prep zones, or a category —
|
||||
// "move" makes it their only category, "also list" adds it to the ones they have.
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Select } from '@xenia/ui'
|
||||
import { Check } from './editor/parts'
|
||||
import { categoryTree, treeLabel } from './productsLogic'
|
||||
|
||||
export function ZonesDialog({ count, zones, onApply, onClose }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [ids, setIds] = useState([])
|
||||
return (
|
||||
<Dialog open size="sm" onClose={onClose} title={t('products.bulkZones.title')} description={t('products.bulkZones.body', { count })}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
|
||||
<Button disabled={!ids.length} onClick={() => onApply(ids)}>{t('products.apply')}</Button>
|
||||
</>}>
|
||||
{zones.length === 0 ? <EmptyState compact title={t('products.editor.noZones')} /> : (
|
||||
<div className="grid gap-2">
|
||||
{zones.map(z => (
|
||||
<Check key={z.id} checked={ids.includes(z.id)} onChange={on => setIds(s => (on ? [...s, z.id] : s.filter(x => x !== z.id)))}>
|
||||
<span className="text-body text-ink">{z.name}</span>{z.description && <span className="text-caption text-ink-3"> · {z.description}</span>}
|
||||
</Check>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export function CategoryBulkDialog({ count, categories, onApply, onClose }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [cat, setCat] = useState('')
|
||||
const [mode, setMode] = useState('move')
|
||||
return (
|
||||
<Dialog open size="sm" onClose={onClose} title={t('products.bulkCategory.title')} description={t('products.bulkCategory.body', { count })}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
|
||||
<Button disabled={!cat} onClick={() => onApply(Number(cat), mode)} data-testid="bulk-category-apply">{t('products.apply')}</Button>
|
||||
</>}>
|
||||
<div className="grid gap-4">
|
||||
<div className="grid gap-2" role="radiogroup">
|
||||
{['move', 'add'].map(m => (
|
||||
<label key={m} className="flex items-start gap-2 cursor-pointer">
|
||||
<input type="radio" name="bulk-mode" className="mt-1 accent-[var(--x-accent)]" checked={mode === m} onChange={() => setMode(m)} data-testid={`bulk-mode-${m}`} />
|
||||
<span className="grid"><span className="text-body font-medium text-ink">{t(`products.bulkCategory.${m}`)}</span><span className="text-caption text-ink-3">{t(`products.bulkCategory.${m}Hint`)}</span></span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Select value={cat} onChange={e => setCat(e.target.value)} aria-label={t('products.bulkCategory.which')} data-testid="bulk-category-pick">
|
||||
<option value="">{t('products.bulkCategory.which')}</option>
|
||||
{categoryTree(categories).map(({ cat: c, depth }) => <option key={c.id} value={c.id}>{treeLabel(c, depth)}</option>)}
|
||||
</Select>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// A category or sub-category (plan step 6.3): its name, picture and colour; or where it goes
|
||||
// (top level or under another category).
|
||||
import { useState } from 'react'
|
||||
import { Check } from 'lucide-react'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, Field, Input, Select, cx } from '@xenia/ui'
|
||||
import MediaField from '../media/MediaField'
|
||||
import { CATEGORY_COLOURS } from './categoryColours'
|
||||
import { topLevel } from './productsLogic'
|
||||
|
||||
export default function CategoryDialog({ category, parentName, saving, onSave, onClose }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [name, setName] = useState(category.name ?? '')
|
||||
const [color, setColor] = useState(category.color ?? CATEGORY_COLOURS[0])
|
||||
const [image, setImage] = useState(category.image ?? null)
|
||||
const sub = !!category.parent_id
|
||||
const title = t(`products.category.${category.id ? 'edit' : 'new'}${sub ? 'Sub' : ''}`)
|
||||
return (
|
||||
<Dialog open size="sm" onClose={onClose} title={title} description={sub && parentName ? t('products.category.under', { name: parentName }) : undefined}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
|
||||
<Button disabled={!name.trim()} loading={saving} onClick={() => onSave({ name: name.trim(), color, media_id: image?.id ?? null })} data-testid="category-save">{t('products.save')}</Button>
|
||||
</>}>
|
||||
<div className="grid gap-4">
|
||||
<Field label={t('products.category.name')}><Input value={name} onChange={e => setName(e.target.value)} autoFocus data-testid="category-name" /></Field>
|
||||
<MediaField value={image} onChange={setImage} nameAfter={name} nameAfterLabel={t('media.nameAfterCategory')} label={t('media.photo')} testid="category-photo" />
|
||||
<div className="grid gap-2">
|
||||
<span className="text-label font-semibold text-ink">{t('products.category.colour')}</span>
|
||||
<div className="grid grid-cols-6 gap-2" role="radiogroup" aria-label={t('products.category.colour')}>
|
||||
{CATEGORY_COLOURS.map(c => (
|
||||
<button key={c} type="button" role="radio" aria-checked={color === c} aria-label={c} onClick={() => setColor(c)}
|
||||
className={cx('aspect-square rounded-full grid place-items-center text-accent-fg ring-offset-2 ring-offset-surface', color === c && 'ring-2 ring-[var(--x-ink)]')}
|
||||
style={{ background: c }}>
|
||||
{color === c && <Check size={16} />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
/** Move a category: to the top level, or under another top-level category. */
|
||||
export function MoveCategoryDialog({ category, categories, onMove, onClose }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const own = new Set([category.id, ...categories.filter(c => c.parent_id === category.id).map(c => c.id)])
|
||||
const [target, setTarget] = useState('')
|
||||
return (
|
||||
<Dialog open size="sm" onClose={onClose} title={t('products.category.moveTitle')} description={t('products.category.moving', { name: category.name })}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
|
||||
<Button onClick={() => onMove(target === '' ? null : Number(target))}>{t('products.category.move')}</Button>
|
||||
</>}>
|
||||
<Field label={t('products.category.newPlace')}>
|
||||
<Select value={target} onChange={e => setTarget(e.target.value)}>
|
||||
<option value="">{t('products.category.topLevel')}</option>
|
||||
{topLevel(categories).filter(c => !own.has(c.id)).map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||||
</Select>
|
||||
</Field>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// The categories beside the products (plan step 6.3): service items, all products, each
|
||||
// category with its sub-categories (drag to reorder within a level; add a sub-category, move,
|
||||
// edit or delete from a row), then products without a category and the archive. A category's
|
||||
// count is the products listed in it, so a product in two categories counts in both. The chosen
|
||||
// category's row shows its actions.
|
||||
import { useRef, useState } from 'react'
|
||||
import { Archive, ArrowRightLeft, ChevronDown, ChevronRight, Folder, GripVertical, Pencil, Plus, Search, Trash2, Truck, X } from 'lucide-react'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { IconButton, Input, cx } from '@xenia/ui'
|
||||
import { SCOPES, countIn, isArchived, moveId, subsOf, topLevel } from './productsLogic'
|
||||
|
||||
export function Dot({ cat, size = 'w-2 h-2' }) {
|
||||
// a category's colour is the venue's choice (data)
|
||||
return <span className={cx(size, 'rounded-full shrink-0', !cat?.color && 'bg-ink-3')} style={cat?.color ? { background: cat.color } : undefined} aria-hidden="true" />
|
||||
}
|
||||
|
||||
export default function CategoryTree({ categories, products, scope, onScope, onAdd, onEdit, onDelete, onMove, onReorder }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [query, setQuery] = useState('')
|
||||
const [open, setOpen] = useState(() => new Set(topLevel(categories).map(c => c.id)))
|
||||
const drag = useRef(null)
|
||||
const [dropAt, setDropAt] = useState(null)
|
||||
const q = query.trim().toLowerCase()
|
||||
const matches = c => !q || c.name.toLowerCase().includes(q) || subsOf(categories, c.id).some(s => s.name.toLowerCase().includes(q))
|
||||
const live = products.filter(p => !isArchived(p))
|
||||
|
||||
const dnd = (cat, level, parent) => ({
|
||||
draggable: true,
|
||||
onDragStart: e => { drag.current = { id: cat.id, level, parent }; e.dataTransfer.effectAllowed = 'move' },
|
||||
onDragOver: e => { e.preventDefault(); if (drag.current && drag.current.id !== cat.id && drag.current.level === level && drag.current.parent === parent) setDropAt(cat.id) },
|
||||
onDragLeave: () => setDropAt(null),
|
||||
onDrop: e => {
|
||||
e.preventDefault()
|
||||
setDropAt(null)
|
||||
const d = drag.current
|
||||
drag.current = null
|
||||
if (!d || d.level !== level || d.parent !== parent) return
|
||||
const siblings = (level === 'top' ? topLevel(categories) : subsOf(categories, parent)).map(c => c.id)
|
||||
const next = moveId(siblings, d.id, cat.id)
|
||||
if (next) onReorder(level, next)
|
||||
},
|
||||
})
|
||||
|
||||
const row = (cat, depth, parent) => (
|
||||
<div key={cat.id} {...dnd(cat, depth ? 'sub' : 'top', parent)} className={cx(dropAt === cat.id && 'border-t-2 border-accent')}>
|
||||
<Row label={cat.name} count={countIn(products, categories, cat.id)} active={scope === cat.id} onClick={() => onScope(cat.id)} depth={depth}
|
||||
dot={<Dot cat={cat} />} drag testId={`category-${cat.id}`}
|
||||
caret={!depth && subsOf(categories, cat.id).length > 0 ? (open.has(cat.id) || !!q) : null}
|
||||
onCaret={() => setOpen(s => { const n = new Set(s); if (n.has(cat.id)) n.delete(cat.id); else n.add(cat.id); return n })}
|
||||
actions={<>
|
||||
{!depth && <IconButton size="sm" variant="ghost" label={t('products.category.newSub')} onClick={() => onAdd(cat.id)}><Plus size={14} /></IconButton>}
|
||||
<IconButton size="sm" variant="ghost" label={t('products.category.moveTitle')} onClick={() => onMove(cat)}><ArrowRightLeft size={14} /></IconButton>
|
||||
<IconButton size="sm" variant="ghost" label={t('products.category.edit')} onClick={() => onEdit(cat)}><Pencil size={14} /></IconButton>
|
||||
<IconButton size="sm" variant="ghost" label={t('products.category.delete')} onClick={() => onDelete(cat)}><Trash2 size={14} /></IconButton>
|
||||
</>} />
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<aside className="w-full md:w-80 md:min-w-80 border-b md:border-b-0 md:border-r border-line flex flex-col min-h-0 bg-surface" data-testid="category-tree">
|
||||
<div className="flex items-center gap-2 px-4 pt-3 pb-2">
|
||||
<Folder size={16} className="text-ink-3" aria-hidden="true" />
|
||||
<h2 className="flex-1 text-label font-semibold text-ink">{t('products.categories')}</h2>
|
||||
<IconButton size="sm" variant="secondary" label={t('products.category.new')} onClick={() => onAdd(null)} data-testid="category-add"><Plus size={14} /></IconButton>
|
||||
</div>
|
||||
<div className="px-4 pb-2 relative">
|
||||
<Search size={14} className="absolute left-7 top-1/2 -translate-y-1/2 text-ink-3 pointer-events-none" aria-hidden="true" />
|
||||
<Input size="sm" className="pl-8" value={query} onChange={e => setQuery(e.target.value)} placeholder={t('products.searchCategories')} aria-label={t('products.searchCategories')} />
|
||||
{query && <IconButton size="sm" variant="ghost" className="absolute right-5 top-1/2 -translate-y-1/2" label={t('products.clear')} onClick={() => setQuery('')}><X size={12} /></IconButton>}
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-2 pb-2 max-h-72 md:max-h-none">
|
||||
<Row label={t('products.service')} count={live.filter(p => p.is_service_item).length} active={scope === SCOPES.service} onClick={() => onScope(SCOPES.service)}
|
||||
dot={<Truck size={14} className="text-warning-ink shrink-0" aria-hidden="true" />} />
|
||||
<Row label={t('products.all')} count={live.filter(p => !p.is_service_item).length} active={scope === SCOPES.all} onClick={() => onScope(SCOPES.all)}
|
||||
dot={<span className="w-2 h-2 rounded-full bg-accent shrink-0" aria-hidden="true" />} testId="category-all" />
|
||||
{topLevel(categories).filter(matches).map(cat => (
|
||||
<div key={cat.id}>
|
||||
{row(cat, 0, null)}
|
||||
{(open.has(cat.id) || q) && subsOf(categories, cat.id).map(s => row(s, 1, cat.id))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="border-t border-line p-2">
|
||||
<Row label={t('products.uncategorized')} count={live.filter(p => !(p.category_ids ?? []).length && !p.is_service_item).length}
|
||||
active={scope === SCOPES.none} onClick={() => onScope(SCOPES.none)} dot={<Folder size={14} className="text-ink-3 shrink-0" aria-hidden="true" />} />
|
||||
<Row label={t('products.archived')} count={products.filter(isArchived).length}
|
||||
active={scope === SCOPES.archived} onClick={() => onScope(SCOPES.archived)} dot={<Archive size={14} className="text-ink-3 shrink-0" aria-hidden="true" />} />
|
||||
</div>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
function Row({ label, count, active, onClick, dot, depth = 0, caret = null, onCaret, actions, drag = false, testId }) {
|
||||
return (
|
||||
<div className={cx('group relative flex flex-wrap items-center gap-1.5 pr-1 py-1 rounded-control cursor-pointer', active ? 'bg-accent-soft text-accent-ink' : 'hover:bg-surface-2 text-ink')}
|
||||
style={{ paddingLeft: `${0.25 + depth}rem` }} onClick={onClick} data-active={active}>
|
||||
{drag ? <GripVertical size={14} className="text-ink-3 cursor-grab shrink-0" aria-hidden="true" /> : <span className="w-3.5 shrink-0" />}
|
||||
{caret !== null
|
||||
? <button type="button" className="text-ink-3 shrink-0" onClick={e => { e.stopPropagation(); onCaret() }} aria-expanded={caret}>{caret ? <ChevronDown size={14} /> : <ChevronRight size={14} />}</button>
|
||||
: <span className="w-3.5 shrink-0" />}
|
||||
{dot}
|
||||
<button type="button" className={cx('flex-1 min-w-0 truncate text-left text-body', active && 'font-semibold')} data-testid={testId}>{label}</button>
|
||||
{/* a category's own actions show on its row once it's chosen (touch screens have no hover) */}
|
||||
<span className="px-1.5 rounded-full bg-surface-2 text-caption text-ink-2 tabular-nums shrink-0">{count}</span>
|
||||
{actions && active && <span className="w-full flex justify-end gap-0.5" onClick={e => e.stopPropagation()} data-testid="category-actions">{actions}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
// The products of the chosen category (plan step 6.3), as a list or a grid. The list is in
|
||||
// groups, each a category's own list in its own order: drag a product (or use ▲ / ▼) to move it
|
||||
// in that category only. A product listed in several categories shows in each, with its other
|
||||
// categories named; its main one is marked.
|
||||
import { useRef, useState } from 'react'
|
||||
import { Archive, ChevronDown, ChevronRight, ChevronUp, GripVertical, Pencil, Star, Trash2 } from 'lucide-react'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, IconButton, cx } from '@xenia/ui'
|
||||
import { Dot } from './CategoryTree'
|
||||
import { costOf, isArchived, reorderBody, stepBody } from './productsLogic'
|
||||
|
||||
export function Photo({ product, className }) {
|
||||
if (product.image_url) return <img src={product.image?.thumb || product.image_url} alt="" className={cx('object-cover bg-surface-2', className)} />
|
||||
return <span className={cx('grid place-items-center bg-surface-2 text-ink-3 font-semibold', className)} aria-hidden="true">{(product.name || '?').trim()[0]?.toUpperCase()}</span>
|
||||
}
|
||||
|
||||
export default function ProductList({ groups, view, categories, prepZones, selected, onSelect, onEdit, onRemove, onToggle, onReorder }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [folded, setFolded] = useState(new Set())
|
||||
const drag = useRef(null)
|
||||
const [drop, setDrop] = useState(null) // { id, key, after }
|
||||
const headers = groups.length > 1 || (groups[0] && groups[0].key !== '__none__')
|
||||
|
||||
if (view === 'grid') {
|
||||
const seen = new Set()
|
||||
const items = groups.flatMap(g => g.items).filter(p => !seen.has(p.id) && seen.add(p.id))
|
||||
return (
|
||||
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]" data-testid="product-grid">
|
||||
{items.map(p => <Card key={p.id} p={p} categories={categories} selected={selected.has(p.id)} onSelect={onSelect} onEdit={onEdit} onRemove={onRemove} onToggle={onToggle} />)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const handlers = (g, p) => ({
|
||||
draggable: true,
|
||||
onDragStart: e => { drag.current = { id: p.id, key: g.key }; e.dataTransfer.effectAllowed = 'move' },
|
||||
onDragOver: e => {
|
||||
e.preventDefault()
|
||||
if (!drag.current || drag.current.key !== g.key || drag.current.id === p.id) return
|
||||
const r = e.currentTarget.getBoundingClientRect()
|
||||
setDrop({ id: p.id, key: g.key, after: e.clientY > r.top + r.height / 2 })
|
||||
},
|
||||
onDragLeave: () => setDrop(null),
|
||||
onDrop: e => {
|
||||
e.preventDefault()
|
||||
const d = drag.current
|
||||
const after = drop?.after ?? false
|
||||
drag.current = null
|
||||
setDrop(null)
|
||||
if (!d || d.key !== g.key) return
|
||||
const body = reorderBody(g, d.id, p.id, after)
|
||||
if (body) onReorder(body)
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
{groups.map(g => {
|
||||
const shut = folded.has(g.key)
|
||||
return (
|
||||
<section key={g.key} data-testid="product-group" data-category={g.key}>
|
||||
{headers && (
|
||||
<button type="button" onClick={() => setFolded(s => { const n = new Set(s); if (n.has(g.key)) n.delete(g.key); else n.add(g.key); return n })}
|
||||
className="flex items-center gap-2 py-1.5 text-caption font-semibold uppercase tracking-wide text-ink-3" aria-expanded={!shut}>
|
||||
{shut ? <ChevronRight size={14} /> : <ChevronDown size={14} />}
|
||||
{g.cat && <Dot cat={g.cat} />}
|
||||
{g.cat ? (g.cat.parent_id ? `${categories.find(c => c.id === g.cat.parent_id)?.name ?? ''} › ${g.cat.name}` : g.cat.name) : t('products.uncategorized')}
|
||||
<span className="px-1.5 rounded-full bg-surface-2 normal-case tracking-normal tabular-nums">{g.items.length}</span>
|
||||
</button>
|
||||
)}
|
||||
{!shut && (
|
||||
<div className="rounded-card border border-line bg-surface divide-y divide-line">
|
||||
{g.items.map((p, i) => (
|
||||
<Row key={p.id} p={p} g={g} first={i === 0} last={i === g.items.length - 1} categories={categories} prepZones={prepZones}
|
||||
selected={selected.has(p.id)} onSelect={onSelect} onEdit={onEdit} onRemove={onRemove} onToggle={onToggle}
|
||||
onStep={step => { const body = stepBody(g, p.id, step); if (body) onReorder(body) }}
|
||||
drop={drop?.id === p.id && drop?.key === g.key ? (drop.after ? 'after' : 'before') : null} dnd={handlers(g, p)} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Others({ p, here, categories }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const other = (p.category_ids ?? []).filter(id => id !== here)
|
||||
if (!other.length) return null // only in this category: nothing to say
|
||||
return (
|
||||
<>
|
||||
{here != null && here === p.primary_category_id && <span className="inline-flex items-center gap-1 text-accent-ink" title={t('products.mainHere')}><Star size={12} aria-hidden="true" />{t('products.main')}</span>}
|
||||
{other.map(id => {
|
||||
const c = categories.find(x => x.id === id)
|
||||
return c && (
|
||||
<span key={id} className="inline-flex items-center gap-1 px-1.5 rounded-full bg-surface-2" data-testid="also-in">
|
||||
<Dot cat={c} size="w-1.5 h-1.5" />{t('products.alsoIn', { name: c.name })}{id === p.primary_category_id && <Star size={10} className="text-accent-ink" aria-label={t('products.main')} />}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function Row({ p, g, first, last, categories, prepZones, selected, onSelect, onEdit, onRemove, onToggle, onStep, drop, dnd }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatMoney, formatPercent } = useFormat()
|
||||
const c = costOf(p)
|
||||
const archived = isArchived(p)
|
||||
const zones = (p.prep_zone_ids ?? []).map(id => prepZones.find(z => z.id === id)?.name).filter(Boolean)
|
||||
return (
|
||||
<div {...dnd} className={cx('group grid grid-cols-[auto_auto_auto_1fr_auto] md:grid-cols-[auto_auto_auto_1fr_auto_auto] items-center gap-3 px-2 py-2',
|
||||
selected && 'bg-accent-soft', drop === 'before' && 'border-t-2 !border-t-accent', drop === 'after' && 'border-b-2 !border-b-accent')}
|
||||
data-testid="product-row" data-name={p.name} data-id={p.id}>
|
||||
<span className="flex flex-col items-center text-ink-3">
|
||||
<button type="button" className="leading-none opacity-0 group-hover:opacity-100 focus:opacity-100 disabled:invisible hover:text-ink" aria-label={t('products.moveUp')} title={t('products.moveUp')}
|
||||
disabled={first} onClick={() => onStep(-1)} data-testid="product-up"><ChevronUp size={14} /></button>
|
||||
<GripVertical size={14} className="cursor-grab" aria-hidden="true" />
|
||||
<button type="button" className="leading-none opacity-0 group-hover:opacity-100 focus:opacity-100 disabled:invisible hover:text-ink" aria-label={t('products.moveDown')} title={t('products.moveDown')}
|
||||
disabled={last} onClick={() => onStep(1)} data-testid="product-down"><ChevronDown size={14} /></button>
|
||||
</span>
|
||||
<input type="checkbox" className="w-4 h-4 accent-[var(--x-accent)]" checked={selected} onChange={() => onSelect(p.id)} aria-label={t('products.select', { name: p.name })} />
|
||||
<Photo product={p} className="w-11 h-11 rounded-control" />
|
||||
<div className="min-w-0 grid gap-0.5">
|
||||
<span className="flex items-center gap-2 min-w-0">
|
||||
<span className="text-body font-medium text-ink truncate">{p.name}</span>
|
||||
{archived && <span className="px-1.5 rounded bg-surface-2 text-caption font-semibold uppercase text-ink-2">{t('products.archivedBadge')}</span>}
|
||||
{p.is_service_item && !archived && <span className="px-1.5 rounded bg-warning-soft text-caption font-semibold uppercase text-warning-ink">{t('products.service')}</span>}
|
||||
{Object.keys(p.allergens ?? {}).length > 0 && <span className="px-1.5 rounded bg-warning-soft text-caption text-warning-ink" title={t('products.hasAllergens')}>{t('products.allergenCount', { count: Object.keys(p.allergens).length })}</span>}
|
||||
</span>
|
||||
<span className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-caption text-ink-2">
|
||||
<Others p={p} here={g.key === '__none__' ? null : g.key} categories={categories} />
|
||||
{zones.map(z => <span key={z} className="px-1.5 rounded bg-info-soft text-info-ink">{z}</span>)}
|
||||
</span>
|
||||
</div>
|
||||
<span className="grid justify-items-end">
|
||||
<span className="text-body font-semibold tabular-nums text-ink">{formatMoney(p.base_price)}</span>
|
||||
{c && <span className={cx('text-caption', c.over ? 'text-danger-ink' : 'text-success-ink')}>{c.over ? t('products.costOverPrice') : c.margin != null ? t('products.margin', { pct: formatPercent(c.margin, { maxDecimals: 0 }) }) : null}</span>}
|
||||
</span>
|
||||
<span className="col-span-5 md:col-span-1 flex items-center justify-end gap-1.5">
|
||||
{!archived && (
|
||||
<Button size="sm" variant={p.is_available ? 'secondary' : 'ghost'} onClick={() => onToggle(p)} aria-pressed={p.is_available} data-testid="product-available">
|
||||
<span className={cx('w-2 h-2 rounded-full', p.is_available ? 'bg-success' : 'bg-ink-3')} aria-hidden="true" />
|
||||
{p.is_available ? t('products.available') : t('products.unavailable')}
|
||||
</Button>
|
||||
)}
|
||||
<Button size="sm" variant="secondary" icon={<Pencil size={14} />} onClick={() => onEdit(p)} data-testid="product-edit">{t('products.edit')}</Button>
|
||||
<IconButton size="sm" variant="ghost" label={archived ? t('products.delete') : t('products.archive')} onClick={() => onRemove(p)}>{archived ? <Trash2 size={16} /> : <Archive size={16} />}</IconButton>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Card({ p, categories, selected, onSelect, onEdit, onRemove, onToggle }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatMoney } = useFormat()
|
||||
const main = categories.find(c => c.id === p.primary_category_id)
|
||||
const archived = isArchived(p)
|
||||
return (
|
||||
<div className={cx('group rounded-card border bg-surface overflow-hidden flex flex-col', selected ? 'border-accent shadow-focus' : 'border-line hover:shadow-raised')} data-testid="product-card" data-name={p.name}>
|
||||
<div className="relative h-36">
|
||||
<Photo product={p} className="w-full h-full text-display" />
|
||||
<span className="absolute top-2 left-2 flex gap-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100">
|
||||
<input type="checkbox" className="w-5 h-5 accent-[var(--x-accent)]" checked={selected} onChange={() => onSelect(p.id)} aria-label={t('products.select', { name: p.name })} />
|
||||
<IconButton size="sm" variant="secondary" label={t('products.edit')} onClick={() => onEdit(p)}><Pencil size={14} /></IconButton>
|
||||
<IconButton size="sm" variant="secondary" label={archived ? t('products.delete') : t('products.archive')} onClick={() => onRemove(p)}><Archive size={14} /></IconButton>
|
||||
</span>
|
||||
{!archived && (
|
||||
<button type="button" onClick={() => onToggle(p)} title={p.is_available ? t('products.available') : t('products.unavailable')} aria-label={p.is_available ? t('products.available') : t('products.unavailable')}
|
||||
className="absolute top-2 right-2 w-7 h-7 rounded-full bg-surface grid place-items-center shadow-raised">
|
||||
<span className={cx('w-2.5 h-2.5 rounded-full', p.is_available ? 'bg-success' : 'bg-ink-3')} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="p-3 grid gap-1.5">
|
||||
<span className="text-body font-semibold text-ink">{p.name}</span>
|
||||
{main && <span className="inline-flex items-center gap-1 text-caption text-ink-2"><Dot cat={main} />{main.name}{(p.category_ids?.length ?? 0) > 1 && ` +${p.category_ids.length - 1}`}</span>}
|
||||
<span className="text-body font-bold tabular-nums text-ink">{formatMoney(p.base_price)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
// Management → Products (plan step 6.3, was Management/ProductsTab): the categories on the left,
|
||||
// the chosen category's products on the right. A product can be listed in several categories
|
||||
// (D-23); each category's list has its own order, and one of the product's categories is its
|
||||
// main one (tickets and reports group it there). Changes reach every screen live
|
||||
// (`products_changed`).
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import toast from 'react-hot-toast'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, EmptyState, Spinner } from '@xenia/ui'
|
||||
import { Package } from 'lucide-react'
|
||||
import client from '../../api/client'
|
||||
import { useLiveQuery } from '../../live/useLiveQuery'
|
||||
import CategoryDialog, { MoveCategoryDialog } from './CategoryDialog'
|
||||
import CategoryTree from './CategoryTree'
|
||||
import ProductList from './ProductList'
|
||||
import Toolbar, { BulkBar, SubChips } from './Toolbar'
|
||||
import { CategoryBulkDialog, ZonesDialog } from './BulkDialogs'
|
||||
import ProductEditor from './editor/ProductEditor'
|
||||
import { emptyProduct } from './editor/formLogic'
|
||||
import { NO_FILTERS, SCOPES, applyFilters, bulkCategories, groupProducts, isArchived, isCategoryScope, listedIn, scopeProducts, subsOf } from './productsLogic'
|
||||
|
||||
const EVENTS = ['products_changed']
|
||||
const number = v => (v === '' ? null : Number(String(v).replace(',', '.')))
|
||||
|
||||
export default function ProductsPage() {
|
||||
const { t } = useTranslation('manager')
|
||||
const qc = useQueryClient()
|
||||
const [scope, setScope] = useState(SCOPES.all)
|
||||
const [sub, setSub] = useState(null)
|
||||
const [search, setSearch] = useState('')
|
||||
const [filters, setFilters] = useState(NO_FILTERS)
|
||||
const [view, setView] = useState('list')
|
||||
const [selected, setSelected] = useState(new Set())
|
||||
const [editing, setEditing] = useState(null) // a product (new: no id)
|
||||
const [catEdit, setCatEdit] = useState(null) // a category (new: no id, parent_id)
|
||||
const [catMove, setCatMove] = useState(null)
|
||||
const [confirm, setConfirm] = useState(null) // { kind: 'category' | 'archive' | 'delete' | 'bulkArchive', item? }
|
||||
const [bulk, setBulk] = useState(null) // 'zones' | 'category'
|
||||
|
||||
const { data: categories = [], isPending: catsPending } = useLiveQuery({ queryKey: ['categories'], queryFn: () => client.get('/api/products/categories').then(r => r.data), events: EVENTS })
|
||||
const { data: products = [], isPending: productsPending } = useLiveQuery({ queryKey: ['products-all'], queryFn: () => client.get('/api/products/', { params: { all: true } }).then(r => r.data), events: EVENTS })
|
||||
const { data: zones = [] } = useLiveQuery({ queryKey: ['prep-zones'], queryFn: () => client.get('/api/prep-zones').then(r => r.data) })
|
||||
|
||||
const refresh = () => { qc.invalidateQueries({ queryKey: ['products-all'] }); qc.invalidateQueries({ queryKey: ['categories'] }) }
|
||||
const onError = err => toast.error(errorMessage(err, t))
|
||||
const run = (fn, done) => ({ mutationFn: fn, onSuccess: () => { if (done) toast.success(done); refresh() }, onError })
|
||||
const saveProduct = useMutation({ ...run(b => (editing?.id ? client.put(`/api/products/${editing.id}`, b) : client.post('/api/products/', b)), t('products.saved')), onSuccess: () => { toast.success(t('products.saved')); setEditing(null); refresh() } })
|
||||
const saveCategory = useMutation({ ...run(b => (catEdit?.id ? client.put(`/api/products/categories/${catEdit.id}`, b) : client.post('/api/products/categories', b))), onSuccess: () => { toast.success(t('products.category.saved')); setCatEdit(null); refresh() } })
|
||||
const reorder = useMutation(run(body => client.put('/api/products/reorder', body)))
|
||||
const reorderCats = useMutation(run(({ level, ids }) => client.put(level === 'top' ? '/api/products/categories/reorder' : '/api/products/categories/reorder-subcategories', ids.map((id, i) => ({ id, sort_order: i })))))
|
||||
const reparent = useMutation(run(({ id, parent_id }) => client.put(`/api/products/categories/${id}/reparent`, { parent_id }), t('products.category.moved')))
|
||||
const toggle = useMutation(run(p => client.put(`/api/products/${p.id}`, { is_available: !p.is_available })))
|
||||
|
||||
async function confirmed() {
|
||||
const c = confirm
|
||||
setConfirm(null)
|
||||
try {
|
||||
if (c.kind === 'category') { await client.delete(`/api/products/categories/${c.item.id}`); if (scope === c.item.id) setScope(SCOPES.all) }
|
||||
if (c.kind === 'archive') await client.delete(`/api/products/${c.item.id}`)
|
||||
if (c.kind === 'delete') await client.delete(`/api/products/${c.item.id}`, { params: { hard: true } })
|
||||
if (c.kind === 'bulkArchive') { await Promise.all([...selected].map(id => client.delete(`/api/products/${id}`))); setSelected(new Set()) }
|
||||
toast.success(t(`products.done.${c.kind}`))
|
||||
} catch (err) { onError(err) } finally { refresh() }
|
||||
}
|
||||
async function bulkPut(bodyOf, done) {
|
||||
try {
|
||||
await Promise.all([...selected].map(id => client.put(`/api/products/${id}`, bodyOf(products.find(p => p.id === id)))))
|
||||
toast.success(done)
|
||||
setSelected(new Set())
|
||||
} catch (err) { onError(err) } finally { setBulk(null); refresh() }
|
||||
}
|
||||
async function bulkZones(ids) {
|
||||
try {
|
||||
await client.post('/api/products/bulk-prep-zones', { product_ids: [...selected], prep_zone_ids: ids })
|
||||
toast.success(t('products.bulkZones.done', { count: selected.size }))
|
||||
setSelected(new Set())
|
||||
} catch (err) { onError(err) } finally { setBulk(null); refresh() }
|
||||
}
|
||||
|
||||
if (catsPending || productsPending) return <div className="p-6 flex justify-center"><Spinner /></div>
|
||||
|
||||
const scopeCat = isCategoryScope(scope) ? categories.find(c => c.id === scope) : null
|
||||
const subs = scopeCat && !scopeCat.parent_id ? subsOf(categories, scope) : []
|
||||
const inScope = scopeProducts(products, categories, scope, { showArchived: filters.showArchived })
|
||||
const shown = applyFilters(inScope, { search, priceMin: number(filters.priceMin), priceMax: number(filters.priceMax), quality: filters.quality, unavailableOnly: filters.unavailableOnly })
|
||||
const groups = groupProducts(shown, categories, scope, subs.length ? sub : null)
|
||||
const title = scope === SCOPES.all ? t('products.all') : scope === SCOPES.service ? t('products.service') : scope === SCOPES.none ? t('products.uncategorized')
|
||||
: scope === SCOPES.archived ? t('products.archived') : scopeCat ? (scopeCat.parent_id ? `${categories.find(c => c.id === scopeCat.parent_id)?.name ?? ''} › ${scopeCat.name}` : scopeCat.name) : t('products.title')
|
||||
const newProduct = () => {
|
||||
if (scope === SCOPES.service) return setEditing(emptyProduct({ is_service_item: true, base_price: 0 }))
|
||||
const preset = (subs.length && sub) || (isCategoryScope(scope) ? scope : null)
|
||||
setEditing(emptyProduct(preset ? { category_ids: [preset], primary_category_id: preset } : {}))
|
||||
}
|
||||
const toggleSelect = id => setSelected(s => { const n = new Set(s); if (n.has(id)) n.delete(id); else n.add(id); return n })
|
||||
const allIds = [...new Set(groups.flatMap(g => g.items.map(p => p.id)))]
|
||||
|
||||
return (
|
||||
<div className="flex flex-col md:flex-row h-full min-h-0" data-testid="products-page">
|
||||
<CategoryTree categories={categories} products={products} scope={scope}
|
||||
onScope={s => { setScope(s); setSub(null); setSelected(new Set()) }}
|
||||
onAdd={parent => setCatEdit({ parent_id: parent })} onEdit={setCatEdit} onMove={setCatMove}
|
||||
onDelete={c => setConfirm({ kind: 'category', item: c })}
|
||||
onReorder={(level, ids) => reorderCats.mutate({ level, ids })} />
|
||||
|
||||
<div className="flex-1 min-w-0 min-h-0 flex flex-col">
|
||||
<Toolbar title={title} shown={allIds.length} total={products.filter(p => !isArchived(p)).length}
|
||||
search={search} onSearch={setSearch} filters={filters} onFilters={setFilters} view={view} onView={setView} onNew={newProduct} />
|
||||
{subs.length > 0 && (
|
||||
<SubChips parent={scopeCat} subs={subs} value={sub} onChange={setSub}
|
||||
counts={key => (key == null ? inScope.length : inScope.filter(p => listedIn(p, key)).length)} />
|
||||
)}
|
||||
{selected.size > 0 && (
|
||||
<BulkBar count={selected.size} onClear={() => setSelected(new Set())}
|
||||
onAvailable={() => bulkPut(() => ({ is_available: true }), t('products.updated', { count: selected.size }))}
|
||||
onUnavailable={() => bulkPut(() => ({ is_available: false }), t('products.updated', { count: selected.size }))}
|
||||
onArchive={() => setConfirm({ kind: 'bulkArchive' })} onZones={() => setBulk('zones')} onCategory={() => setBulk('category')} />
|
||||
)}
|
||||
<div className="flex items-center justify-between px-4 md:px-6 py-2 border-b border-line bg-surface-2 text-label text-ink-2">
|
||||
<label className="flex items-center gap-2 cursor-pointer select-none">
|
||||
<input type="checkbox" className="w-4 h-4 accent-[var(--x-accent)]" checked={allIds.length > 0 && allIds.every(id => selected.has(id))}
|
||||
onChange={e => setSelected(e.target.checked ? new Set(allIds) : new Set())} />
|
||||
{selected.size ? t('products.selected', { count: selected.size }) : t('products.selectAll')}
|
||||
</label>
|
||||
<span>{t('products.totals', { active: products.filter(p => !isArchived(p)).length, categories: categories.length, archived: products.filter(isArchived).length })}</span>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-4 md:p-6">
|
||||
{allIds.length === 0
|
||||
? <EmptyState icon={<Package size={28} />} title={t('products.none')} description={t('products.noneHint')} action={<Button onClick={newProduct}>{t('products.new')}</Button>} />
|
||||
: <ProductList groups={groups} view={view} categories={categories} prepZones={zones} selected={selected} onSelect={toggleSelect}
|
||||
onEdit={setEditing} onToggle={p => toggle.mutate(p)} onReorder={body => reorder.mutate(body)}
|
||||
onRemove={p => setConfirm({ kind: isArchived(p) ? 'delete' : 'archive', item: p })} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{editing && (
|
||||
<ProductEditor key={editing.id ?? 'new'} product={editing} categories={categories} prepZones={zones} saving={saveProduct.isPending}
|
||||
onSave={body => saveProduct.mutate(body)} onClose={() => setEditing(null)}
|
||||
onCopy={form => setEditing({ _form: { ...form, name: t('products.copyOf', { name: form.name }) } })} />
|
||||
)}
|
||||
{catEdit && (
|
||||
<CategoryDialog category={catEdit} parentName={categories.find(c => c.id === catEdit.parent_id)?.name} saving={saveCategory.isPending}
|
||||
onClose={() => setCatEdit(null)} onSave={b => saveCategory.mutate({ ...b, parent_id: catEdit.parent_id ?? null })} />
|
||||
)}
|
||||
{catMove && <MoveCategoryDialog category={catMove} categories={categories} onClose={() => setCatMove(null)}
|
||||
onMove={parent => { reparent.mutate({ id: catMove.id, parent_id: parent }); setCatMove(null) }} />}
|
||||
{bulk === 'zones' && <ZonesDialog count={selected.size} zones={zones} onApply={bulkZones} onClose={() => setBulk(null)} />}
|
||||
{bulk === 'category' && <CategoryBulkDialog count={selected.size} categories={categories} onClose={() => setBulk(null)}
|
||||
onApply={(cat, mode) => bulkPut(p => bulkCategories(p, cat, mode), t('products.bulkCategory.done', { count: selected.size }))} />}
|
||||
{confirm && (
|
||||
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t(`products.confirm.${confirm.kind}`, { name: confirm.item?.name, count: selected.size })}
|
||||
footer={<>
|
||||
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('products.cancel')}</Button>
|
||||
<Button variant="danger" onClick={confirmed} data-testid="confirm">{t(`products.confirmButton.${confirm.kind}`)}</Button>
|
||||
</>}>
|
||||
<p>{t(`products.confirmBody.${confirm.kind}`)}</p>
|
||||
</Dialog>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// The products' toolbar (plan step 6.3): the title and count, search (accents ignored, Latin
|
||||
// letters find Greek names), filters (price, missing photo / category, unavailable only,
|
||||
// archived too), list or grid, and "New product". Then the sub-category chips of a top-level
|
||||
// category, and the bar of what to do with the selected products.
|
||||
import { useState } from 'react'
|
||||
import { Archive, Eye, EyeOff, Filter, FolderInput, LayoutGrid, List, Plus, Search, Utensils, X } from 'lucide-react'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, IconButton, Input, cx } from '@xenia/ui'
|
||||
import { Dot } from './CategoryTree'
|
||||
import { NO_FILTERS } from './productsLogic'
|
||||
|
||||
export default function Toolbar({ title, shown, total, search, onSearch, filters, onFilters, view, onView, onNew }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [open, setOpen] = useState(false)
|
||||
const any = JSON.stringify(filters) !== JSON.stringify(NO_FILTERS)
|
||||
const set = (k, v) => onFilters({ ...filters, [k]: v })
|
||||
return (
|
||||
<div className="relative border-b border-line px-4 md:px-6 py-3 flex flex-wrap items-center gap-2">
|
||||
<h1 className="text-title font-semibold text-ink" data-testid="products-title">{title}</h1>
|
||||
<span className="px-2 rounded-full bg-surface-2 text-caption text-ink-2 tabular-nums">{shown}/{total}</span>
|
||||
<div className="relative flex-1 min-w-48">
|
||||
<Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3 pointer-events-none" aria-hidden="true" />
|
||||
<Input size="sm" className="pl-8" value={search} onChange={e => onSearch(e.target.value)} placeholder={t('products.search')} aria-label={t('products.search')} data-testid="products-search" />
|
||||
{search && <IconButton size="sm" variant="ghost" className="absolute right-1 top-1/2 -translate-y-1/2" label={t('products.clear')} onClick={() => onSearch('')}><X size={12} /></IconButton>}
|
||||
</div>
|
||||
<Button size="sm" variant={open ? 'primary' : 'secondary'} icon={<Filter size={14} />} onClick={() => setOpen(o => !o)} aria-expanded={open}>
|
||||
{t('products.filters')}{any && <span className="w-1.5 h-1.5 rounded-full bg-accent" aria-hidden="true" />}
|
||||
</Button>
|
||||
<span className="inline-flex rounded-control border border-line overflow-hidden" role="radiogroup" aria-label={t('products.view')}>
|
||||
{[['list', <List key="l" size={14} />], ['grid', <LayoutGrid key="g" size={14} />]].map(([v, icon]) => (
|
||||
<button key={v} type="button" role="radio" aria-checked={view === v} title={t(`products.view_${v}`)} aria-label={t(`products.view_${v}`)} onClick={() => onView(v)}
|
||||
className={cx('w-9 h-control-sm grid place-items-center', view === v ? 'bg-accent text-accent-fg' : 'text-ink-2 hover:bg-surface-2')}
|
||||
>{icon}</button>
|
||||
))}
|
||||
</span>
|
||||
<Button size="sm" icon={<Plus size={14} />} onClick={onNew} data-testid="product-new">{t('products.new')}</Button>
|
||||
{open && (
|
||||
<div className="absolute z-popover top-full left-4 right-4 md:left-6 md:right-6 mt-1 p-4 rounded-card border border-line bg-surface shadow-popover flex flex-wrap items-end gap-5">
|
||||
<label className="grid gap-1">
|
||||
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('products.price')}</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Input size="sm" className="w-20" inputMode="decimal" value={filters.priceMin} onChange={e => set('priceMin', e.target.value)} placeholder={t('products.from')} aria-label={t('products.from')} />
|
||||
<span className="text-ink-3">–</span>
|
||||
<Input size="sm" className="w-20" inputMode="decimal" value={filters.priceMax} onChange={e => set('priceMax', e.target.value)} placeholder={t('products.to')} aria-label={t('products.to')} />
|
||||
</span>
|
||||
</label>
|
||||
<div className="grid gap-1">
|
||||
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('products.quality')}</span>
|
||||
<span className="flex gap-1">
|
||||
{['all', 'no-photo', 'no-cat'].map(q => <Button key={q} size="sm" variant={filters.quality === q ? 'primary' : 'secondary'} onClick={() => set('quality', q)}>{t(`products.qualityOf.${q}`)}</Button>)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid gap-1">
|
||||
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('products.show')}</span>
|
||||
<span className="flex gap-1">
|
||||
<Button size="sm" variant={filters.unavailableOnly ? 'primary' : 'secondary'} onClick={() => set('unavailableOnly', !filters.unavailableOnly)}>{t('products.unavailableOnly')}</Button>
|
||||
<Button size="sm" variant={filters.showArchived ? 'primary' : 'secondary'} onClick={() => set('showArchived', !filters.showArchived)}>{t('products.withArchived')}</Button>
|
||||
</span>
|
||||
</div>
|
||||
{any && <Button size="sm" variant="ghost" icon={<X size={14} />} className="ml-auto" onClick={() => onFilters(NO_FILTERS)}>{t('products.clearFilters')}</Button>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The sub-categories of a top-level category as chips: all, the category's own list, each sub-category. */
|
||||
export function SubChips({ parent, subs, counts, value, onChange }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const chips = [{ key: null, label: t('products.allOf') }, { key: parent.id, label: parent.name, cat: parent }, ...subs.map(s => ({ key: s.id, label: s.name, cat: s }))]
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1.5 px-4 md:px-6 py-2 border-b border-line">
|
||||
{chips.map(c => (
|
||||
<Button key={String(c.key)} size="sm" variant={value === c.key ? 'primary' : 'secondary'} onClick={() => onChange(c.key)}>
|
||||
{c.cat && <Dot cat={c.cat} />}{c.label}<span className="tabular-nums opacity-70">{counts(c.key)}</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function BulkBar({ count, onClear, onAvailable, onUnavailable, onArchive, onZones, onCategory }) {
|
||||
const { t } = useTranslation('manager')
|
||||
return (
|
||||
<div className="mx-4 md:mx-6 mt-3 px-3 py-2 rounded-card bg-accent text-accent-fg flex flex-wrap items-center gap-2" data-testid="bulk-bar">
|
||||
<IconButton size="sm" variant="ghost" className="text-accent-fg" label={t('products.clearSelection')} onClick={onClear}><X size={14} /></IconButton>
|
||||
<span className="text-label font-semibold flex-1">{t('products.selected', { count })}</span>
|
||||
<Button size="sm" variant="secondary" icon={<Eye size={14} />} onClick={onAvailable}>{t('products.makeAvailable')}</Button>
|
||||
<Button size="sm" variant="secondary" icon={<EyeOff size={14} />} onClick={onUnavailable}>{t('products.makeUnavailable')}</Button>
|
||||
<Button size="sm" variant="secondary" icon={<Archive size={14} />} onClick={onArchive}>{t('products.archive')}</Button>
|
||||
<Button size="sm" variant="secondary" icon={<Utensils size={14} />} onClick={onZones}>{t('products.prepZone')}</Button>
|
||||
<Button size="sm" variant="secondary" icon={<FolderInput size={14} />} onClick={onCategory} data-testid="bulk-category">{t('products.toCategory')}</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// The colours a venue can give a category (plan step 6.3). These are the venue's data (stored on
|
||||
// the category and shown as its dot here and on the phones), not the manager's styling: listed
|
||||
// in tests/v2-guards.test.mjs DATA.
|
||||
export const CATEGORY_COLOURS = ['#6366f1', '#0ea5e9', '#10b981', '#f59e0b', '#ef4444', '#ec4899', '#8b5cf6', '#14b8a6', '#f97316', '#64748b', '#84cc16', '#06b6d4']
|
||||
@@ -0,0 +1,270 @@
|
||||
// The editor's right side (plan step 6.3): what a waiter can choose for the product.
|
||||
// Favourites the choices shown first, in their own order, across the lists below
|
||||
// Quick one-tap add-ons with a price (extra bacon)
|
||||
// Ingredients what the guest can leave out (or pay to add more), optionally in groups
|
||||
// Extras ticked add-ons, each with optional sub-choices (syrup → caramel / vanilla)
|
||||
// Preferences one set per tab (sugar: none / medium / sweet), a default, sub-choices, a
|
||||
// shared sub-set shown for every choice except those marked to hide it
|
||||
import { useRef, useState } from 'react'
|
||||
import { Heart, Plus, Trash2 } from 'lucide-react'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, EmptyState, IconButton, Input, Select, cx } from '@xenia/ui'
|
||||
import { favourites, moveChoice, moveFavourite, moveItem, removeChoice, removeGroup, setSub, toggleFavourite } from './formLogic'
|
||||
import { Check, DefaultToggle, FavouriteToggle, GroupHeader, MoveButtons, PriceInput, SubChoices } from './parts'
|
||||
|
||||
const newSub = () => ({ name: '', extra_cost: 0, is_default: false, allow_multiple: false, is_compact: false })
|
||||
|
||||
export default function ChoicesPanel({ form, setForm }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [tab, setTab] = useState('favourites')
|
||||
const [folded, setFolded] = useState({})
|
||||
const nextKey = useRef(-1)
|
||||
const favCount = favourites(form).length
|
||||
|
||||
const addGroup = type => setForm(f => ({ ...f, modifier_groups: [...f.modifier_groups, { key: nextKey.current--, modifier_type: type, name: t('products.editor.newGroup') }] }))
|
||||
const groups = { form, setForm, folded, fold: key => setFolded(s => ({ ...s, [key]: !s[key] })), addGroup }
|
||||
const addPref = () => {
|
||||
setForm(f => ({ ...f, preference_sets: [...f.preference_sets, { name: '', default_choice_index: -1, choices: [], shared_subset: null, group_id: null, is_favorite: false, favorite_sort_order: 0, allow_multi_select: false, allow_choice_quantity: false }] }))
|
||||
setTab(form.preference_sets.length)
|
||||
}
|
||||
const tabs = [
|
||||
{ key: 'favourites', label: t('products.editor.tab.favourites'), count: favCount },
|
||||
{ key: 'quick', label: t('products.editor.tab.quick'), count: form.quick_options.length },
|
||||
{ key: 'ingredients', label: t('products.editor.tab.ingredients'), count: form.ingredients.length },
|
||||
{ key: 'options', label: t('products.editor.tab.options'), count: form.options.length },
|
||||
...form.preference_sets.map((ps, i) => ({ key: i, label: ps.name || t('products.editor.prefN', { n: i + 1 }), count: ps.choices.length })),
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="flex flex-col min-h-0 h-full">
|
||||
<div className="flex items-end border-b border-line overflow-x-auto shrink-0" role="tablist">
|
||||
{tabs.map(tb => (
|
||||
<button key={String(tb.key)} type="button" role="tab" aria-selected={tab === tb.key} onClick={() => setTab(tb.key)}
|
||||
className={cx('flex items-center gap-1.5 px-4 py-2.5 -mb-px border-b-2 text-label whitespace-nowrap',
|
||||
tab === tb.key ? 'border-accent text-ink font-semibold' : 'border-transparent text-ink-2 hover:text-ink')}>
|
||||
{tb.key === 'favourites' && <Heart size={14} className={favCount ? 'text-danger' : 'text-ink-3'} fill={favCount ? 'currentColor' : 'none'} aria-hidden="true" />}
|
||||
{tb.label}
|
||||
{tb.count > 0 && <span className="px-1.5 rounded-full bg-surface-2 text-caption tabular-nums">{tb.count}</span>}
|
||||
</button>
|
||||
))}
|
||||
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="mb-1 shrink-0" onClick={addPref} data-testid="add-pref">{t('products.editor.addPref')}</Button>
|
||||
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="mb-1 shrink-0" onClick={() => addGroup('preference')}>{t('products.editor.addPrefGroup')}</Button>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-4 md:p-5">
|
||||
{tab === 'favourites' && <Favourites form={form} setForm={setForm} />}
|
||||
{tab === 'quick' && <QuickList form={form} setForm={setForm} />}
|
||||
{tab === 'ingredients' && <GroupedList kind="ingredient" list="ingredients" {...groups} />}
|
||||
{tab === 'options' && <GroupedList kind="option" list="options" {...groups} />}
|
||||
{typeof tab === 'number' && form.preference_sets[tab] && (
|
||||
<PrefSet si={tab} {...groups} onRemoved={() => setTab('favourites')} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Intro({ text, children }) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 mb-3">
|
||||
<p className="text-label text-ink-2">{text}</p>
|
||||
<div className="flex gap-2">{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Favourites({ form, setForm }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const list = favourites(form)
|
||||
return (
|
||||
<div className="grid gap-2">
|
||||
<p className="text-label text-ink-2">{t('products.editor.favouritesHint')}</p>
|
||||
{list.length === 0 && <EmptyState compact title={t('products.editor.noFavourites')} />}
|
||||
{list.map((fav, i) => (
|
||||
<div key={`${fav.kind}-${fav.idx}`} className="flex items-center gap-3 rounded-card border border-line p-2.5">
|
||||
<MoveButtons first={i === 0} last={i === list.length - 1} onUp={() => setForm(f => moveFavourite(f, i, -1))} onDown={() => setForm(f => moveFavourite(f, i, 1))} />
|
||||
<Heart size={16} className="text-danger shrink-0" fill="currentColor" aria-hidden="true" />
|
||||
<span className="flex-1 min-w-0 grid">
|
||||
<span className="text-body font-medium text-ink truncate">{fav.item.name || t('products.editor.unnamed')}</span>
|
||||
<span className="text-caption text-ink-3">{t(`products.editor.kind.${fav.kind}`)}</span>
|
||||
</span>
|
||||
<Button size="sm" variant="ghost" onClick={() => setForm(f => toggleFavourite(f, fav.kind, fav.idx))}>{t('products.editor.remove')}</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function QuickList({ form, setForm }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const set = (i, k, v) => setForm(f => ({ ...f, quick_options: f.quick_options.map((q, j) => (j === i ? { ...q, [k]: v } : q)) }))
|
||||
const add = () => setForm(f => ({ ...f, quick_options: [...f.quick_options, { name: '', price: 0, allow_multiple: false, is_favorite: false, favorite_sort_order: 0, is_compact: false }] }))
|
||||
return (
|
||||
<div>
|
||||
<Intro text={t('products.editor.quickHint')}><Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={add}>{t('products.editor.addQuick')}</Button></Intro>
|
||||
{form.quick_options.length === 0 && <EmptyState compact title={t('products.editor.noQuick')} />}
|
||||
<div className="grid gap-2">
|
||||
{form.quick_options.map((q, i) => (
|
||||
<div key={i} className={cx('flex flex-wrap items-center gap-2 rounded-card border p-2.5', q.is_favorite ? 'border-danger' : 'border-line')}>
|
||||
<MoveButtons first={i === 0} last={i === form.quick_options.length - 1}
|
||||
onUp={() => setForm(f => ({ ...f, quick_options: moveItem(f.quick_options, i, -1) }))} onDown={() => setForm(f => ({ ...f, quick_options: moveItem(f.quick_options, i, 1) }))} />
|
||||
<FavouriteToggle on={q.is_favorite} onClick={() => setForm(f => toggleFavourite(f, 'quick', i))} />
|
||||
<Input className="flex-1 min-w-36" value={q.name} onChange={e => set(i, 'name', e.target.value)} placeholder={t('products.editor.quickPlaceholder')} />
|
||||
<PriceInput className="w-32" value={q.price} onChange={v => set(i, 'price', v)} label={t('products.editor.extraCost')} />
|
||||
<Check checked={q.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Check>
|
||||
<Check checked={q.is_compact} onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Check>
|
||||
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => setForm(f => ({ ...f, quick_options: f.quick_options.filter((_, j) => j !== i) }))}><Trash2 size={14} /></IconButton>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Ingredients or extras, with their groups (folders). */
|
||||
function GroupedList({ kind, list, form, setForm, folded, fold, addGroup }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const items = form[list]
|
||||
const myGroups = form.modifier_groups.filter(g => g.modifier_type === kind)
|
||||
const set = (i, k, v) => setForm(f => ({ ...f, [list]: f[list].map((x, j) => (j === i ? { ...x, [k]: v } : x)) }))
|
||||
const add = () => setForm(f => ({ ...f, [list]: [...f[list], kind === 'option'
|
||||
? { name: '', extra_cost: 0, allow_multiple: false, multi_select: false, is_compact: false, sub_choices: [], is_favorite: false, favorite_sort_order: 0, group_id: null }
|
||||
: { name: '', extra_cost: 0, is_favorite: false, favorite_sort_order: 0, is_compact: false, group_id: null }] }))
|
||||
const row = (x, i) => (
|
||||
<div key={i} className={cx('rounded-card border overflow-hidden', x.is_favorite ? 'border-danger' : 'border-line')}>
|
||||
<div className="flex flex-wrap items-center gap-2 p-2.5">
|
||||
<MoveButtons first={i === 0} last={i === items.length - 1}
|
||||
onUp={() => setForm(f => ({ ...f, [list]: moveItem(f[list], i, -1) }))} onDown={() => setForm(f => ({ ...f, [list]: moveItem(f[list], i, 1) }))} />
|
||||
<FavouriteToggle on={x.is_favorite} onClick={() => setForm(f => toggleFavourite(f, kind, i))} />
|
||||
<Input className="flex-1 min-w-36" value={x.name} onChange={e => set(i, 'name', e.target.value)} placeholder={t(`products.editor.${kind}Placeholder`)} />
|
||||
<PriceInput className="w-32" value={x.extra_cost} allowNegative onChange={v => set(i, 'extra_cost', v)} label={t('products.editor.extraCost')} />
|
||||
{kind === 'option' && <Check checked={x.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Check>}
|
||||
{kind === 'option' && <Check checked={x.multi_select} onChange={v => set(i, 'multi_select', v)}>{t('products.editor.multiSelect')}</Check>}
|
||||
<Check checked={x.is_compact} onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Check>
|
||||
{myGroups.length > 0 && (
|
||||
<Select size="sm" className="w-36" value={x.group_id ?? ''} onChange={e => set(i, 'group_id', e.target.value === '' ? null : Number(e.target.value))} aria-label={t('products.editor.group')}>
|
||||
<option value="">{t('products.editor.noGroup')}</option>
|
||||
{myGroups.map(g => <option key={g.key} value={g.key}>{g.name}</option>)}
|
||||
</Select>
|
||||
)}
|
||||
{kind === 'option' && <Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => set(i, 'sub_choices', [...x.sub_choices, newSub()])}>{t('products.editor.addSubs')}</Button>}
|
||||
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => setForm(f => ({ ...f, [list]: f[list].filter((_, j) => j !== i) }))}><Trash2 size={14} /></IconButton>
|
||||
</div>
|
||||
{kind === 'option' && <SubChoices subs={x.sub_choices} parent={x.name} withMultiple={x.multi_select} onChange={subs => set(i, 'sub_choices', subs)} />}
|
||||
</div>
|
||||
)
|
||||
return (
|
||||
<div>
|
||||
<Intro text={t(`products.editor.${kind}Hint`)}>
|
||||
<Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => addGroup(kind)}>{t('products.editor.addGroup')}</Button>
|
||||
<Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={add}>{t(`products.editor.add.${kind}`)}</Button>
|
||||
</Intro>
|
||||
{items.length === 0 && <EmptyState compact title={t(`products.editor.none.${kind}`)} />}
|
||||
<div className="grid gap-2">
|
||||
{items.map((x, i) => (x.group_id == null ? row(x, i) : null))}
|
||||
{myGroups.map(g => (
|
||||
<div key={g.key}>
|
||||
<GroupHeader group={g} folded={folded[g.key]} onFold={() => fold(g.key)}
|
||||
onRename={name => setForm(f => ({ ...f, modifier_groups: f.modifier_groups.map(x => (x.key === g.key ? { ...x, name } : x)) }))}
|
||||
onRemove={() => setForm(f => removeGroup(f, g.key))} />
|
||||
{!folded[g.key] && (
|
||||
<div className="ml-4 border-l-2 border-accent-soft pl-3 mt-1 grid gap-2">
|
||||
{items.every(x => x.group_id !== g.key) && <p className="text-caption text-ink-3 py-1">{t('products.editor.emptyGroup')}</p>}
|
||||
{items.map((x, i) => (x.group_id === g.key ? row(x, i) : null))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PrefSet({ si, form, setForm, folded, fold, onRemoved }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const ps = form.preference_sets[si]
|
||||
const prefGroups = form.modifier_groups.filter(g => g.modifier_type === 'preference')
|
||||
const put = fn => setForm(f => ({ ...f, preference_sets: f.preference_sets.map((x, i) => (i === si ? fn(x) : x)) }))
|
||||
const set = (k, v) => put(x => ({ ...x, [k]: v }))
|
||||
const setChoice = (ci, k, v) => put(x => ({ ...x, choices: x.choices.map((c, j) => (j === ci ? { ...c, [k]: v } : c)) }))
|
||||
const shared = ps.shared_subset
|
||||
return (
|
||||
<div className="grid gap-4" data-testid="pref-set">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input className="flex-1 min-w-40 font-semibold" value={ps.name} onChange={e => set('name', e.target.value)} placeholder={t('products.editor.prefPlaceholder')} autoFocus data-testid="pref-name" />
|
||||
{prefGroups.length > 0 && (
|
||||
<Select size="sm" className="w-40" value={ps.group_id ?? ''} onChange={e => set('group_id', e.target.value === '' ? null : Number(e.target.value))} aria-label={t('products.editor.group')}>
|
||||
<option value="">{t('products.editor.noGroup')}</option>
|
||||
{prefGroups.map(g => <option key={g.key} value={g.key}>{g.name}</option>)}
|
||||
</Select>
|
||||
)}
|
||||
<FavouriteToggle on={ps.is_favorite} onClick={() => setForm(f => toggleFavourite(f, 'pref', si))} />
|
||||
<Button size="sm" variant="danger" icon={<Trash2 size={14} />}
|
||||
onClick={() => { setForm(f => ({ ...f, preference_sets: f.preference_sets.filter((_, i) => i !== si) })); onRemoved() }}>{t('products.editor.removePref')}</Button>
|
||||
</div>
|
||||
{prefGroups.length > 0 && (
|
||||
<div className="rounded-card bg-accent-soft p-3">
|
||||
<p className="text-caption font-semibold text-accent-ink">{t('products.editor.prefGroups')}</p>
|
||||
{prefGroups.map(g => (
|
||||
<GroupHeader key={g.key} group={g} folded={folded[g.key]} onFold={() => fold(g.key)}
|
||||
onRename={name => setForm(f => ({ ...f, modifier_groups: f.modifier_groups.map(x => (x.key === g.key ? { ...x, name } : x)) }))}
|
||||
onRemove={() => setForm(f => removeGroup(f, g.key))} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-5">
|
||||
<Check checked={ps.allow_multi_select} onChange={v => set('allow_multi_select', v)}>{t('products.editor.multiChoice')}</Check>
|
||||
<Check checked={ps.allow_choice_quantity} onChange={v => set('allow_choice_quantity', v)}>{t('products.editor.choiceQuantity')}</Check>
|
||||
</div>
|
||||
<p className="text-caption text-ink-3">{t('products.editor.prefLegend')}</p>
|
||||
<div className="grid gap-2">
|
||||
{ps.choices.map((c, ci) => (
|
||||
<div key={ci} className="rounded-card border border-line overflow-hidden" data-testid="pref-choice">
|
||||
<div className="flex flex-wrap items-center gap-2 p-2.5">
|
||||
<MoveButtons first={ci === 0} last={ci === ps.choices.length - 1} onUp={() => put(x => moveChoice(x, ci, -1))} onDown={() => put(x => moveChoice(x, ci, 1))} />
|
||||
<DefaultToggle on={ps.default_choice_index === ci} onClick={() => set('default_choice_index', ps.default_choice_index === ci ? -1 : ci)} />
|
||||
<Input className="flex-1 min-w-32" value={c.name} onChange={e => setChoice(ci, 'name', e.target.value)} placeholder={t('products.editor.choicePlaceholder')} />
|
||||
<PriceInput className="w-32" value={c.extra_cost} allowNegative onChange={v => setChoice(ci, 'extra_cost', v)} label={t('products.editor.extraCost')} />
|
||||
<Check checked={c.is_compact} onChange={v => setChoice(ci, 'is_compact', v)}>{t('products.editor.compact')}</Check>
|
||||
{shared && <Check checked={c.disables_subset} onChange={v => setChoice(ci, 'disables_subset', v)}>{t('products.editor.hidesShared')}</Check>}
|
||||
<Button size="sm" variant="ghost" icon={<Plus size={14} />} onClick={() => setChoice(ci, 'sub_choices', [...c.sub_choices, newSub()])}>{t('products.editor.addSubs')}</Button>
|
||||
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => put(x => removeChoice(x, ci))}><Trash2 size={14} /></IconButton>
|
||||
</div>
|
||||
<SubChoices subs={c.sub_choices} parent={c.name} onChange={subs => setChoice(ci, 'sub_choices', subs)} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Button size="sm" variant="secondary" icon={<Plus size={14} />} className="justify-self-start" data-testid="add-choice"
|
||||
onClick={() => put(x => ({ ...x, choices: [...x.choices, { name: '', extra_cost: 0, disables_subset: false, is_compact: false, sub_choices: [] }] }))}>{t('products.editor.addChoice')}</Button>
|
||||
<section className="border-t border-line pt-4 grid gap-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="grid">
|
||||
<span className="text-label font-semibold text-ink">{t('products.editor.shared')}</span>
|
||||
<span className="text-caption text-ink-3">{t('products.editor.sharedHint')}</span>
|
||||
</span>
|
||||
{shared
|
||||
? <Button size="sm" variant="danger" onClick={() => set('shared_subset', null)}>{t('products.editor.remove')}</Button>
|
||||
: <Button size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => set('shared_subset', { name: '', choices: [] })}>{t('products.editor.addShared')}</Button>}
|
||||
</div>
|
||||
{shared && (
|
||||
<div className="rounded-card border border-line bg-surface-2 p-3 grid gap-2">
|
||||
<Input value={shared.name} onChange={e => set('shared_subset', { ...shared, name: e.target.value })} placeholder={t('products.editor.sharedPlaceholder')} aria-label={t('products.editor.sharedName')} />
|
||||
{shared.choices.map((s, i) => (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<MoveButtons first={i === 0} last={i === shared.choices.length - 1}
|
||||
onUp={() => set('shared_subset', { ...shared, choices: moveItem(shared.choices, i, -1) })} onDown={() => set('shared_subset', { ...shared, choices: moveItem(shared.choices, i, 1) })} />
|
||||
<DefaultToggle on={s.is_default} onClick={() => set('shared_subset', { ...shared, choices: setSub(shared.choices, i, 'is_default', !s.is_default) })} />
|
||||
<Input className="flex-1" value={s.name} onChange={e => set('shared_subset', { ...shared, choices: shared.choices.map((x, j) => (j === i ? { ...x, name: e.target.value } : x)) })} />
|
||||
<PriceInput className="w-32" value={s.extra_cost} allowNegative label={t('products.editor.extraCost')}
|
||||
onChange={v => set('shared_subset', { ...shared, choices: shared.choices.map((x, j) => (j === i ? { ...x, extra_cost: v } : x)) })} />
|
||||
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')}
|
||||
onClick={() => set('shared_subset', shared.choices.length > 1 ? { ...shared, choices: shared.choices.filter((_, j) => j !== i) } : null)}><Trash2 size={14} /></IconButton>
|
||||
</div>
|
||||
))}
|
||||
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="justify-self-start"
|
||||
onClick={() => set('shared_subset', { ...shared, choices: [...shared.choices, { name: '', extra_cost: 0, is_default: false }] })}>{t('products.editor.addChoice')}</Button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// The editor's two list fields (plan step 6.3): the product's categories with its main one, and
|
||||
// its allergens.
|
||||
import { Star, X } from 'lucide-react'
|
||||
import { ALLERGENS, nextAllergenLevel, setAllergen } from '@xenia/access'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { IconButton, InfoTip, Select, cx } from '@xenia/ui'
|
||||
import { categoryTree, treeLabel } from '../productsLogic'
|
||||
import { addCategory, removeCategory } from './formLogic'
|
||||
|
||||
/** The categories it's listed in (shown in each), one of them the main one (tickets, reports). */
|
||||
export function CategoriesField({ form, setForm, categories }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const tree = categoryTree(categories)
|
||||
const name = id => {
|
||||
const c = categories.find(x => x.id === id)
|
||||
if (!c) return `#${id}`
|
||||
const parent = c.parent_id ? categories.find(x => x.id === c.parent_id) : null
|
||||
return parent ? `${parent.name} › ${c.name}` : c.name
|
||||
}
|
||||
return (
|
||||
<div className="grid gap-2" data-testid="product-categories">
|
||||
<span className="flex items-center gap-1 text-label font-semibold text-ink">
|
||||
{t('products.editor.categories')}
|
||||
<InfoTip>{t('products.editor.categoriesTip')}</InfoTip>
|
||||
</span>
|
||||
{form.category_ids.length === 0 && <span className="text-label text-ink-3">{t('products.editor.noCategory')}</span>}
|
||||
<ul className="grid gap-1">
|
||||
{form.category_ids.map(id => {
|
||||
const main = form.primary_category_id === id
|
||||
return (
|
||||
<li key={id} className={cx('flex items-center gap-2 pl-3 pr-1 py-1 rounded-control border', main ? 'border-accent bg-accent-soft' : 'border-line bg-surface')}
|
||||
data-testid="product-category" data-id={id} data-main={main}>
|
||||
<span className="flex-1 min-w-0 truncate text-body text-ink">{name(id)}</span>
|
||||
{main
|
||||
? <span className="text-caption font-semibold text-accent-ink">{t('products.editor.main')}</span>
|
||||
: <IconButton size="sm" variant="ghost" label={t('products.editor.makeMain')} onClick={() => setForm(f => ({ ...f, primary_category_id: id }))} data-testid="make-main"><Star size={14} /></IconButton>}
|
||||
<IconButton size="sm" variant="ghost" label={t('products.editor.removeCategory')} onClick={() => setForm(f => removeCategory(f, id))}><X size={14} /></IconButton>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
<Select value="" onChange={e => e.target.value && setForm(f => addCategory(f, Number(e.target.value)))} aria-label={t('products.editor.addCategory')} data-testid="add-category">
|
||||
<option value="">{t('products.editor.addCategory')}</option>
|
||||
{tree.filter(({ cat }) => !form.category_ids.includes(cat.id)).map(({ cat, depth }) => (
|
||||
<option key={cat.id} value={cat.id}>{treeLabel(cat, depth)}</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The 14 EU allergens; a tap goes none → contains → may contain → none. */
|
||||
export function AllergensField({ value, onChange }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { t: tc } = useTranslation('common')
|
||||
return (
|
||||
<div className="grid gap-2" data-testid="product-allergens">
|
||||
<span className="flex items-center gap-1 text-label font-semibold text-ink">
|
||||
{tc('allergens.title')}
|
||||
<InfoTip>{t('products.editor.allergensTip')}</InfoTip>
|
||||
</span>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{ALLERGENS.map(key => {
|
||||
const level = value?.[key] ?? null
|
||||
return (
|
||||
<button key={key} type="button" onClick={() => onChange(setAllergen(value, key, nextAllergenLevel(level)))}
|
||||
aria-label={`${tc(`allergens.${key}`)}: ${level ? tc(`allergens.level.${level}`) : t('products.editor.allergenNone')}`}
|
||||
className={cx('px-2.5 py-1 rounded-full text-label border transition-colors duration-fast',
|
||||
level === 'contains' ? 'bg-warning-soft text-warning-ink border-warning font-semibold'
|
||||
: level === 'may_contain' ? 'bg-surface text-ink border-dashed border-line-strong'
|
||||
: 'bg-surface-2 text-ink-3 border-transparent hover:text-ink')}
|
||||
data-testid={`allergen-${key}`} data-level={level ?? ''}>
|
||||
{tc(`allergens.${key}`)}{level === 'may_contain' && ` · ${t('products.editor.traces')}`}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<span className="text-caption text-ink-3">{t('products.editor.allergensHint')}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
// The editor's left side (plan step 6.3): the product itself (name, description, tags, unit,
|
||||
// price, categories, prep zones, allergens, availability, photo), where it's sold and what the
|
||||
// customer apps show, its cost, and its fiscal fields (when fiscal receipts are on).
|
||||
import { useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Plus, Trash2, X } from 'lucide-react'
|
||||
import { SALES_POINTS } from '@xenia/access'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Field, IconButton, InfoTip, Input, Select, Switch, Textarea, cx } from '@xenia/ui'
|
||||
import MediaField from '../../media/MediaField'
|
||||
import { costOf } from '../productsLogic'
|
||||
import { AllergensField, CategoriesField } from './Fields'
|
||||
import { UNITS, WEIGHED, cleanTag } from './formLogic'
|
||||
import { Check, PriceInput } from './parts'
|
||||
|
||||
export function InfoTab({ form, set, setForm, categories, prepZones }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const service = form.is_service_item
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<Switch checked={service} onChange={v => set('is_service_item', v)} label={t('products.editor.serviceItem')}
|
||||
description={service ? (Number(form.base_price) > 0 ? t('products.editor.servicePaid') : t('products.editor.serviceFree')) : t('products.editor.serviceHint')} />
|
||||
<Field label={t('products.editor.name')} required>
|
||||
<Input value={form.name} onChange={e => set('name', e.target.value)} autoFocus data-testid="product-name"
|
||||
placeholder={service ? t('products.editor.servicePlaceholder') : t('products.editor.namePlaceholder')} />
|
||||
</Field>
|
||||
{!service && (
|
||||
<Field label={t('products.editor.description')} hint={t('products.editor.descriptionHint')}>
|
||||
<Textarea rows={3} value={form.description} onChange={e => set('description', e.target.value)} />
|
||||
</Field>
|
||||
)}
|
||||
{!service && <Tags tags={form.tags} onChange={v => set('tags', v)} />}
|
||||
{!service && (
|
||||
<Field label={t('products.editor.unit')} hint={WEIGHED.has(form.unit_type) ? t('products.editor.unitWeighed') : undefined}>
|
||||
<Select value={form.unit_type} onChange={e => set('unit_type', e.target.value)} options={UNITS.map(u => ({ value: u, label: t(`products.unit.${u}`) }))} />
|
||||
</Field>
|
||||
)}
|
||||
<Field label={service ? t('products.editor.priceOptional') : t('products.editor.price')} required={!service}>
|
||||
<PriceInput className="w-full" value={form.base_price} onChange={v => set('base_price', v)} label={t('products.editor.price')} data-testid="product-price" />
|
||||
</Field>
|
||||
<CategoriesField form={form} setForm={setForm} categories={categories} />
|
||||
<div className="grid gap-2">
|
||||
<span className="flex items-center gap-1 text-label font-semibold text-ink">{t('products.editor.prepZones')}<InfoTip>{t('products.editor.prepZonesTip')}</InfoTip></span>
|
||||
{prepZones.length === 0
|
||||
? <span className="text-label text-ink-3">{t('products.editor.noZones')} <Link className="underline text-accent-ink" to="/management/prep-zones">{t('products.editor.makeZone')}</Link></span>
|
||||
: prepZones.map(z => (
|
||||
<Check key={z.id} checked={form.prep_zone_ids.includes(z.id)}
|
||||
onChange={on => set('prep_zone_ids', on ? [...form.prep_zone_ids, z.id] : form.prep_zone_ids.filter(id => id !== z.id))}>
|
||||
<span className="text-body text-ink">{z.name}</span>{z.description && <span className="text-caption text-ink-3"> · {z.description}</span>}
|
||||
</Check>
|
||||
))}
|
||||
</div>
|
||||
{!service && <AllergensField value={form.allergens} onChange={v => set('allergens', v)} />}
|
||||
{!service && (<>
|
||||
<Switch checked={form.is_available} onChange={v => set('is_available', v)} label={t('products.editor.available')} description={t('products.editor.availableHint')} />
|
||||
<Switch checked={form.quick_add_enabled} onChange={v => set('quick_add_enabled', v)} label={t('products.editor.quickAdd')} description={t('products.editor.quickAddHint')} />
|
||||
<MediaField value={form.image} onChange={image => set('image', image)} nameAfter={form.name} label={t('media.photo')} testid="product-photo" />
|
||||
</>)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Tags({ tags, onChange }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [text, setText] = useState('')
|
||||
const add = () => { const tag = cleanTag(tags, text); if (tag) onChange([...tags, tag]); setText('') }
|
||||
return (
|
||||
<Field label={t('products.editor.tags')} hint={t('products.editor.tagsHint')}>
|
||||
<div className="grid gap-1.5">
|
||||
{tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{tags.map(tag => (
|
||||
<span key={tag} className="inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded-full bg-accent-soft text-accent-ink text-caption font-semibold">
|
||||
{tag}
|
||||
<button type="button" onClick={() => onChange(tags.filter(x => x !== tag))} aria-label={t('products.editor.removeTag', { tag })}><X size={12} /></button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<Input value={text} onChange={e => setText(e.target.value)} onBlur={add}
|
||||
onKeyDown={e => { if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); add() } }} placeholder={t('products.editor.tagsPlaceholder')} />
|
||||
</div>
|
||||
</Field>
|
||||
)
|
||||
}
|
||||
|
||||
export function SoldAtTab({ form, set }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { t: tc } = useTranslation('common')
|
||||
const toggle = sp => set('sold_at', form.sold_at.includes(sp) ? form.sold_at.filter(x => x !== sp) : SALES_POINTS.filter(x => x === sp || form.sold_at.includes(x)))
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<section className="grid gap-2">
|
||||
<h3 className="text-label font-semibold text-ink">{t('products.editor.soldAt')}</h3>
|
||||
<p className="text-caption text-ink-3">{t('products.editor.soldAtHint')}</p>
|
||||
<div className="grid gap-2" data-testid="sold-at">
|
||||
{SALES_POINTS.map(sp => (
|
||||
<label key={sp} className="flex items-start gap-3 cursor-pointer select-none">
|
||||
<input type="checkbox" className="w-4 h-4 mt-0.5 accent-[var(--x-accent)]" checked={form.sold_at.includes(sp)} onChange={() => toggle(sp)} data-testid={`sold-at-${sp}`} />
|
||||
<span className="grid">
|
||||
<span className="text-body font-medium text-ink">{tc(`salesPoints.${sp}.name`)}</span>
|
||||
<span className="text-caption text-ink-3">{tc(`salesPoints.${sp}.hint`)}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-caption text-ink-2 rounded-control bg-surface-2 border border-line px-3 py-2">{t('products.editor.pricePerPoint')}</p>
|
||||
</section>
|
||||
<section className="grid gap-2">
|
||||
<h3 className="text-label font-semibold text-ink">{t('products.editor.online')}</h3>
|
||||
<Switch checked={form.digital_available} onChange={v => set('digital_available', v)} label={t('products.editor.orderableNow')} description={t('products.editor.orderableNowHint')} />
|
||||
</section>
|
||||
<section className="grid gap-3">
|
||||
<h3 className="text-label font-semibold text-ink">{t('products.editor.forCustomers')}</h3>
|
||||
<p className="text-caption text-ink-3">{t('products.editor.forCustomersHint')}</p>
|
||||
<Field label={t('products.editor.customerName')}><Input value={form.digital_name} onChange={e => set('digital_name', e.target.value)} placeholder={form.name} /></Field>
|
||||
<Field label={t('products.editor.customerDescription')}><Textarea rows={3} value={form.digital_description} onChange={e => set('digital_description', e.target.value)} /></Field>
|
||||
<Field label={t('products.editor.customerImage')}><Input value={form.digital_image_url} onChange={e => set('digital_image_url', e.target.value)} placeholder="https://…" /></Field>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function CostTab({ form, set, setForm }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const { formatMoney, formatPercent } = useFormat()
|
||||
const c = costOf({ base_price: form.base_price, cost_simple: form.cost_mode === 'simple' && form.cost_simple !== '' ? form.cost_simple : null,
|
||||
cost_breakdown: form.cost_mode === 'detailed' ? form.cost_breakdown : null })
|
||||
const setLine = (i, k, v) => setForm(f => ({ ...f, cost_breakdown: f.cost_breakdown.map((x, j) => (j === i ? { ...x, [k]: v } : x)) }))
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<p className="text-caption text-ink-3">{t('products.editor.costHint')}</p>
|
||||
<div className="flex gap-1" role="radiogroup" aria-label={t('products.editor.costMode')}>
|
||||
{['simple', 'detailed'].map(m => (
|
||||
<Button key={m} size="sm" variant={form.cost_mode === m ? 'primary' : 'secondary'} role="radio" aria-checked={form.cost_mode === m} onClick={() => set('cost_mode', m)}>
|
||||
{t(`products.editor.cost.${m}`)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
{form.cost_mode === 'simple' ? (
|
||||
<Field label={t('products.editor.costPerUnit')}><PriceInput className="w-full" value={form.cost_simple} onChange={v => set('cost_simple', v)} label={t('products.editor.costPerUnit')} /></Field>
|
||||
) : (
|
||||
<div className="grid gap-2">
|
||||
{form.cost_breakdown.map((e, i) => (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<Input className="flex-1" value={e.label} onChange={ev => setLine(i, 'label', ev.target.value)} placeholder={t('products.editor.costLinePlaceholder')} />
|
||||
<PriceInput className="w-32" value={e.amount} onChange={v => setLine(i, 'amount', v)} label={t('products.editor.costPerUnit')} />
|
||||
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => setForm(f => ({ ...f, cost_breakdown: f.cost_breakdown.filter((_, j) => j !== i) }))}><Trash2 size={14} /></IconButton>
|
||||
</div>
|
||||
))}
|
||||
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="justify-self-start"
|
||||
onClick={() => setForm(f => ({ ...f, cost_breakdown: [...f.cost_breakdown, { label: '', amount: 0 }] }))}>{t('products.editor.addCostLine')}</Button>
|
||||
{form.cost_breakdown.length > 0 && c && <span className="text-label text-ink-2">{t('products.editor.costTotal', { total: formatMoney(c.cost) })}</span>}
|
||||
</div>
|
||||
)}
|
||||
{c && c.cost > 0 && (
|
||||
<p className={cx('text-label font-semibold', c.over ? 'text-danger-ink' : 'text-success-ink')} data-testid="product-margin">
|
||||
{c.over ? t('products.costOverPrice') : c.margin != null ? t('products.margin', { pct: formatPercent(c.margin, { maxDecimals: 1 }) }) : null}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function FiscalTab({ form, set, vatGroups }) {
|
||||
const { t } = useTranslation('manager')
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<p className="text-caption rounded-control bg-info-soft text-info-ink px-3 py-2">{t('products.editor.fiscalHint')}</p>
|
||||
<Field label={t('products.editor.fiscalName')} hint={t('products.editor.fiscalNameHint')}>
|
||||
<Input className="font-mono uppercase" maxLength={30} value={form.fiscal_name} onChange={e => set('fiscal_name', e.target.value.toUpperCase())} placeholder={form.name.toUpperCase()} />
|
||||
</Field>
|
||||
<Field label={t('products.editor.vatGroup')} error={!form.fiscal_vat_group_id ? t('products.editor.vatGroupNeeded') : undefined}>
|
||||
{vatGroups.length === 0
|
||||
? <p className="text-label text-warning-ink">{t('products.editor.noVatGroups')}</p>
|
||||
: <Select value={form.fiscal_vat_group_id ?? ''} onChange={e => set('fiscal_vat_group_id', e.target.value ? Number(e.target.value) : null)}>
|
||||
<option value="">{t('products.editor.noVatGroup')}</option>
|
||||
{vatGroups.map(g => <option key={g.machine_id} value={g.machine_id}>{g.machine_id} · {g.friendly_name}</option>)}
|
||||
</Select>}
|
||||
</Field>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// The product editor (plan step 6.3, was Management/ProductFormModal): the product on the left
|
||||
// (its details, where it's sold, cost, fiscal fields), what a waiter can choose on the right
|
||||
// (ChoicesPanel). A service item (cutlery, a cover charge) has only the left side.
|
||||
// "Copy" opens a new product filled from this one.
|
||||
import { useState } from 'react'
|
||||
import { Copy } from 'lucide-react'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, cx } from '@xenia/ui'
|
||||
import client from '../../../api/client'
|
||||
import { useLiveQuery } from '../../../live/useLiveQuery'
|
||||
import ChoicesPanel from './ChoicesPanel'
|
||||
import { CostTab, FiscalTab, InfoTab, SoldAtTab } from './InfoTabs'
|
||||
import { buildBody, buildForm, canSave } from './formLogic'
|
||||
|
||||
export default function ProductEditor({ product, categories, prepZones, saving, onSave, onCopy, onClose }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [form, setForm] = useState(() => product._form ?? buildForm(product)) // a copy brings its form
|
||||
const [left, setLeft] = useState('info')
|
||||
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
|
||||
const { data: settings } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
|
||||
const fiscalOn = settings?.['fiscal.enabled']?.value === 'true'
|
||||
let vatGroups = []
|
||||
try { vatGroups = JSON.parse(settings?.['fiscal.vat_groups']?.value || '[]') } catch { vatGroups = [] }
|
||||
const service = form.is_service_item
|
||||
const isNew = !product.id
|
||||
const leftTabs = ['info', ...(service ? [] : ['soldAt', 'cost', ...(fiscalOn ? ['fiscal'] : [])])]
|
||||
|
||||
return (
|
||||
<Dialog open onClose={onClose} className="!max-w-[min(1280px,96vw)] h-[94vh]" bodyClass="!p-0 flex"
|
||||
title={isNew ? t('products.editor.newTitle') : t('products.editor.editTitle', { name: product.name })}
|
||||
footer={<div className="flex items-center gap-2 w-full">
|
||||
<Button variant="secondary" onClick={onClose}>{t('products.cancel')}</Button>
|
||||
<span className="flex-1" />
|
||||
{!isNew && <Button variant="secondary" icon={<Copy size={16} />} onClick={() => onCopy(form)}>{t('products.editor.copy')}</Button>}
|
||||
<Button disabled={!canSave(form)} loading={saving} onClick={() => onSave(buildBody(form))} data-testid="product-save">
|
||||
{isNew ? t('products.editor.create') : t('products.save')}
|
||||
</Button>
|
||||
</div>}>
|
||||
<div className="flex-1 flex flex-col md:flex-row min-h-0 w-full overflow-y-auto md:overflow-hidden" data-testid="product-editor">
|
||||
<div className={cx('flex flex-col md:min-h-0 border-b md:border-b-0 md:border-r border-line bg-surface-2', service ? 'w-full' : 'w-full md:w-[34%] md:min-w-[22rem]')}>
|
||||
<div className="flex border-b border-line bg-surface shrink-0 overflow-x-auto" role="tablist">
|
||||
{leftTabs.map(k => (
|
||||
<button key={k} type="button" role="tab" aria-selected={left === k} onClick={() => setLeft(k)} data-testid={`editor-tab-${k}`}
|
||||
className={cx('flex-1 px-3 py-2.5 -mb-px border-b-2 text-label whitespace-nowrap',
|
||||
left === k ? 'border-accent text-ink font-semibold' : 'border-transparent text-ink-2 hover:text-ink')}>
|
||||
{t(`products.editor.left.${k}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex-1 md:min-h-0 md:overflow-y-auto p-4 md:p-5">
|
||||
{left === 'info' && <InfoTab form={form} set={set} setForm={setForm} categories={categories} prepZones={prepZones} />}
|
||||
{left === 'soldAt' && <SoldAtTab form={form} set={set} />}
|
||||
{left === 'cost' && <CostTab form={form} set={set} setForm={setForm} />}
|
||||
{left === 'fiscal' && <FiscalTab form={form} set={set} vatGroups={vatGroups} />}
|
||||
</div>
|
||||
</div>
|
||||
{!service && <div className="flex flex-1 min-w-0 flex-col min-h-[30rem] md:min-h-0"><ChoicesPanel form={form} setForm={setForm} /></div>}
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
// The product editor's form (plan step 6.3): a product → the form, the form → the API body,
|
||||
// and the edits that touch several lists at once (favourites, choice groups). No React
|
||||
// (tests/products.test.mjs). The body's shapes are the API's (schemas/product.py).
|
||||
import { SALES_POINTS } from '@xenia/access/salesPoints'
|
||||
|
||||
export const UNITS = ['piece', 'portion', 'kg', 'liter', 'gram', 'ml']
|
||||
export const WEIGHED = new Set(['kg', 'liter', 'gram', 'ml'])
|
||||
export const LISTS = { quick: 'quick_options', ingredient: 'ingredients', option: 'options', pref: 'preference_sets' }
|
||||
|
||||
const num = v => (v === '' || v == null ? 0 : Number(String(v).replace(',', '.')) || 0)
|
||||
const sub = s => ({ name: s.name ?? '', extra_cost: s.extra_cost ?? 0, is_default: !!s.is_default, allow_multiple: !!s.allow_multiple, is_compact: !!s.is_compact })
|
||||
|
||||
export function emptyProduct(preset = {}) {
|
||||
return { name: '', base_price: '', category_ids: [], primary_category_id: null, is_available: true, lifecycle_status: 'active', ...preset }
|
||||
}
|
||||
|
||||
export function buildForm(p) {
|
||||
return {
|
||||
name: p.name ?? '',
|
||||
description: p.description ?? '',
|
||||
category_ids: [...(p.category_ids ?? (p.category_id ? [p.category_id] : []))],
|
||||
primary_category_id: p.primary_category_id ?? p.category_id ?? (p.category_ids?.[0] ?? null),
|
||||
base_price: p.base_price ?? '',
|
||||
unit_type: p.unit_type ?? 'piece',
|
||||
is_available: p.is_available ?? true,
|
||||
lifecycle_status: p.lifecycle_status ?? 'active',
|
||||
prep_zone_ids: [...(p.prep_zone_ids ?? [])],
|
||||
allergens: { ...(p.allergens ?? {}) },
|
||||
quick_options: (p.quick_options ?? []).map(q => ({
|
||||
name: q.name, price: q.price ?? 0, allow_multiple: !!q.allow_multiple, is_favorite: !!q.is_favorite,
|
||||
favorite_sort_order: q.favorite_sort_order ?? 0, is_compact: !!q.is_compact,
|
||||
})),
|
||||
options: (p.options ?? []).map(o => ({
|
||||
name: o.name, extra_cost: o.extra_cost ?? 0, allow_multiple: !!o.allow_multiple, multi_select: !!o.multi_select,
|
||||
is_compact: !!o.is_compact, sub_choices: (o.sub_choices ?? []).map(sub),
|
||||
is_favorite: !!o.is_favorite, favorite_sort_order: o.favorite_sort_order ?? 0, group_id: o.group_id ?? null,
|
||||
})),
|
||||
ingredients: (p.ingredients ?? []).map(i => ({
|
||||
name: i.name, extra_cost: i.extra_cost ?? 0, is_favorite: !!i.is_favorite, favorite_sort_order: i.favorite_sort_order ?? 0,
|
||||
is_compact: !!i.is_compact, group_id: i.group_id ?? null,
|
||||
})),
|
||||
preference_sets: (p.preference_sets ?? []).map(ps => ({
|
||||
name: ps.name,
|
||||
default_choice_index: ps.choices ? ps.choices.findIndex(c => c.id === ps.default_choice_id) : -1,
|
||||
choices: (ps.choices ?? []).map(c => ({
|
||||
name: c.name, extra_cost: c.extra_cost ?? 0, disables_subset: !!c.disables_subset, is_compact: !!c.is_compact,
|
||||
sub_choices: (c.sub_choices ?? []).map(sub),
|
||||
})),
|
||||
group_id: ps.group_id ?? null,
|
||||
shared_subset: ps.shared_subset ? { name: ps.shared_subset.name ?? '', choices: (ps.shared_subset.choices ?? []).map(sub) } : null,
|
||||
is_favorite: !!ps.is_favorite, favorite_sort_order: ps.favorite_sort_order ?? 0,
|
||||
allow_multi_select: !!ps.allow_multi_select, allow_choice_quantity: !!ps.allow_choice_quantity,
|
||||
})),
|
||||
sold_at: [...(p.sold_at ?? SALES_POINTS)],
|
||||
digital_available: p.digital_available ?? true,
|
||||
digital_name: p.digital_name ?? '',
|
||||
digital_description: p.digital_description ?? '',
|
||||
digital_image_url: p.digital_image_url ?? '',
|
||||
image: p.image ?? null,
|
||||
cost_mode: p.cost_breakdown?.length ? 'detailed' : 'simple',
|
||||
cost_simple: p.cost_simple ?? '',
|
||||
cost_breakdown: (p.cost_breakdown ?? []).map(e => ({ label: e.label, amount: e.amount })),
|
||||
quick_add_enabled: p.quick_add_enabled ?? true,
|
||||
tags: [...(p.tags ?? [])],
|
||||
is_service_item: !!p.is_service_item,
|
||||
fiscal_name: p.fiscal_name ?? '',
|
||||
fiscal_vat_group_id: p.fiscal_vat_group_id ?? null,
|
||||
// choice groups (folders) keyed by a form id; the API takes their index
|
||||
modifier_groups: (p.modifier_groups ?? []).map(g => ({ key: g.id, modifier_type: g.modifier_type, name: g.name })),
|
||||
}
|
||||
}
|
||||
|
||||
export function buildBody(f) {
|
||||
const groupIndex = key => (key == null ? null : f.modifier_groups.findIndex(g => g.key === key))
|
||||
const subOut = s => ({ name: s.name, extra_cost: num(s.extra_cost), is_default: !!s.is_default, allow_multiple: !!s.allow_multiple, is_compact: !!s.is_compact })
|
||||
return {
|
||||
name: f.name.trim(),
|
||||
description: f.description.trim() || null,
|
||||
category_ids: f.category_ids,
|
||||
primary_category_id: f.category_ids.includes(f.primary_category_id) ? f.primary_category_id : (f.category_ids[0] ?? null),
|
||||
base_price: num(f.base_price),
|
||||
unit_type: f.unit_type || 'piece',
|
||||
is_available: f.is_available,
|
||||
lifecycle_status: f.lifecycle_status,
|
||||
prep_zone_ids: f.prep_zone_ids,
|
||||
allergens: f.allergens,
|
||||
quick_options: f.quick_options.map((q, i) => ({
|
||||
name: q.name, price: num(q.price), allow_multiple: q.allow_multiple, sort_order: i,
|
||||
is_favorite: q.is_favorite, favorite_sort_order: q.favorite_sort_order, is_compact: q.is_compact,
|
||||
})),
|
||||
modifier_groups: f.modifier_groups.map((g, i) => ({ modifier_type: g.modifier_type, name: g.name, sort_order: i })),
|
||||
options: f.options.map(o => ({
|
||||
name: o.name, extra_cost: num(o.extra_cost), allow_multiple: o.allow_multiple, multi_select: o.multi_select,
|
||||
is_compact: o.is_compact, sub_choices: o.sub_choices.map(subOut),
|
||||
is_favorite: o.is_favorite, favorite_sort_order: o.favorite_sort_order, group_id: groupIndex(o.group_id),
|
||||
})),
|
||||
ingredients: f.ingredients.map(i => ({
|
||||
name: i.name, extra_cost: num(i.extra_cost), is_favorite: i.is_favorite, favorite_sort_order: i.favorite_sort_order,
|
||||
is_compact: i.is_compact, group_id: groupIndex(i.group_id),
|
||||
})),
|
||||
preference_sets: f.preference_sets.map(ps => ({
|
||||
name: ps.name,
|
||||
default_choice_index: ps.default_choice_index >= 0 ? ps.default_choice_index : null,
|
||||
shared_subset: ps.shared_subset?.choices?.length
|
||||
? { name: ps.shared_subset.name || '', choices: ps.shared_subset.choices.map(s => ({ name: s.name, extra_cost: num(s.extra_cost), is_default: !!s.is_default })) }
|
||||
: null,
|
||||
choices: ps.choices.map(c => ({
|
||||
name: c.name, extra_cost: num(c.extra_cost), disables_subset: c.disables_subset, is_compact: c.is_compact,
|
||||
sub_choices: c.sub_choices.map(s => ({ name: s.name, extra_cost: num(s.extra_cost), is_default: !!s.is_default, is_compact: !!s.is_compact })),
|
||||
})),
|
||||
is_favorite: ps.is_favorite, favorite_sort_order: ps.favorite_sort_order, group_id: groupIndex(ps.group_id),
|
||||
allow_multi_select: ps.allow_multi_select, allow_choice_quantity: ps.allow_choice_quantity,
|
||||
})),
|
||||
sold_at: f.sold_at,
|
||||
digital_available: f.digital_available,
|
||||
digital_name: f.digital_name.trim() || null,
|
||||
digital_description: f.digital_description.trim() || null,
|
||||
digital_image_url: f.digital_image_url.trim() || null,
|
||||
cost_simple: f.cost_mode === 'simple' && f.cost_simple !== '' ? num(f.cost_simple) : null,
|
||||
cost_breakdown: f.cost_mode === 'detailed' && f.cost_breakdown.length
|
||||
? f.cost_breakdown.map(e => ({ label: e.label, amount: num(e.amount) })) : null,
|
||||
quick_add_enabled: f.quick_add_enabled,
|
||||
tags: f.tags,
|
||||
is_service_item: f.is_service_item,
|
||||
fiscal_name: f.fiscal_name.trim() || null,
|
||||
fiscal_vat_group_id: f.fiscal_vat_group_id ? Number(f.fiscal_vat_group_id) : null,
|
||||
media_id: f.image?.id ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/** Can it be saved: a name, and a price unless it's a service item. */
|
||||
export const canSave = f => !!f.name.trim() && (f.is_service_item || (f.base_price !== '' && f.base_price != null))
|
||||
|
||||
// ── categories ──────────────────────────────────────────────────────────────
|
||||
|
||||
/** Add a category (the first one becomes the main one). */
|
||||
export function addCategory(f, id) {
|
||||
if (f.category_ids.includes(id)) return f
|
||||
return { ...f, category_ids: [...f.category_ids, id], primary_category_id: f.primary_category_id ?? id }
|
||||
}
|
||||
/** Remove a category; when it was the main one, the next listed one takes over. */
|
||||
export function removeCategory(f, id) {
|
||||
const ids = f.category_ids.filter(c => c !== id)
|
||||
return { ...f, category_ids: ids, primary_category_id: f.primary_category_id === id ? (ids[0] ?? null) : f.primary_category_id }
|
||||
}
|
||||
|
||||
// ── favourites: the choices a waiter sees first, across the four lists ────────
|
||||
|
||||
export function favourites(f) {
|
||||
return Object.entries(LISTS).flatMap(([kind, list]) =>
|
||||
f[list].map((item, idx) => ({ kind, idx, item })).filter(x => x.item.is_favorite))
|
||||
.sort((a, b) => a.item.favorite_sort_order - b.item.favorite_sort_order)
|
||||
}
|
||||
|
||||
const patch = (f, kind, idx, fields) => ({ ...f, [LISTS[kind]]: f[LISTS[kind]].map((x, i) => (i === idx ? { ...x, ...fields } : x)) })
|
||||
|
||||
export function toggleFavourite(f, kind, idx) {
|
||||
const on = f[LISTS[kind]][idx]?.is_favorite
|
||||
const last = favourites(f).reduce((m, x) => Math.max(m, x.item.favorite_sort_order), -1)
|
||||
return patch(f, kind, idx, on ? { is_favorite: false, favorite_sort_order: 0 } : { is_favorite: true, favorite_sort_order: last + 1 })
|
||||
}
|
||||
|
||||
/** Swap a favourite with its neighbour (step -1 / +1). */
|
||||
export function moveFavourite(f, at, step) {
|
||||
const list = favourites(f)
|
||||
const a = list[at]
|
||||
const b = list[at + step]
|
||||
if (!a || !b) return f
|
||||
return patch(patch(f, a.kind, a.idx, { favorite_sort_order: b.item.favorite_sort_order }), b.kind, b.idx, { favorite_sort_order: a.item.favorite_sort_order })
|
||||
}
|
||||
|
||||
// ── list helpers ────────────────────────────────────────────────────────────
|
||||
|
||||
export function moveItem(arr, i, step) {
|
||||
const j = i + step
|
||||
if (j < 0 || j >= arr.length) return arr
|
||||
const next = [...arr]
|
||||
;[next[i], next[j]] = [next[j], next[i]]
|
||||
return next
|
||||
}
|
||||
|
||||
/** A preference set's choices moved, keeping which one is the default. */
|
||||
export function moveChoice(ps, i, step) {
|
||||
const j = i + step
|
||||
if (j < 0 || j >= ps.choices.length) return ps
|
||||
const d = ps.default_choice_index
|
||||
return { ...ps, choices: moveItem(ps.choices, i, step), default_choice_index: d === i ? j : d === j ? i : d }
|
||||
}
|
||||
|
||||
/** A choice removed, the default index following it. */
|
||||
export function removeChoice(ps, i) {
|
||||
const d = ps.default_choice_index
|
||||
return { ...ps, choices: ps.choices.filter((_, k) => k !== i), default_choice_index: d === i ? -1 : d > i ? d - 1 : d }
|
||||
}
|
||||
|
||||
/** Set a field of one sub-choice; marking one as the default unmarks the others. */
|
||||
export function setSub(subs, i, key, value) {
|
||||
return subs.map((s, k) => (k === i ? { ...s, [key]: value } : key === 'is_default' && value ? { ...s, is_default: false } : s))
|
||||
}
|
||||
|
||||
/** Remove a choice group: its members go back to "no group". */
|
||||
export function removeGroup(f, key) {
|
||||
const free = x => (x.group_id === key ? { ...x, group_id: null } : x)
|
||||
return { ...f, modifier_groups: f.modifier_groups.filter(g => g.key !== key), options: f.options.map(free), ingredients: f.ingredients.map(free), preference_sets: f.preference_sets.map(free) }
|
||||
}
|
||||
|
||||
/** A tag typed by hand: trimmed, lower case, no commas; null when empty or already there. */
|
||||
export function cleanTag(tags, text) {
|
||||
const tag = String(text ?? '').trim().toLowerCase().replace(/,/g, '')
|
||||
return tag && !tags.includes(tag) ? tag : null
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// Small controls of the product editor (plan step 6.3).
|
||||
import { useState } from 'react'
|
||||
import { ChevronDown, ChevronUp, Heart, Minus, Pencil, Plus, Trash2 } from 'lucide-react'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, IconButton, Input, cx } from '@xenia/ui'
|
||||
|
||||
/** A price with − / + of 0.10 (negative allowed for choices that lower the price). */
|
||||
export function PriceInput({ value, onChange, allowNegative = false, className, label, ...rest }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const n = Number(String(value ?? '').replace(',', '.')) || 0
|
||||
const step = d => {
|
||||
const next = Math.round((n + d) * 100) / 100
|
||||
onChange(allowNegative ? next : Math.max(0, next))
|
||||
}
|
||||
return (
|
||||
<span className={cx('inline-flex items-stretch rounded-control border border-line bg-surface h-control overflow-hidden', className)}>
|
||||
<button type="button" className="px-2 text-ink-2 hover:bg-surface-2" onClick={() => step(-0.1)} aria-label={t('products.editor.less')}><Minus size={14} /></button>
|
||||
<input type="text" inputMode="decimal" value={value ?? ''} onChange={e => onChange(e.target.value)} placeholder="0.00" aria-label={label}
|
||||
className="w-full min-w-0 text-center text-body bg-transparent outline-none tabular-nums" {...rest} />
|
||||
<button type="button" className="px-2 text-ink-2 hover:bg-surface-2" onClick={() => step(0.1)} aria-label={t('products.editor.more')}><Plus size={14} /></button>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** ▲ / ▼ to move a row. */
|
||||
export function MoveButtons({ onUp, onDown, first, last }) {
|
||||
const { t } = useTranslation('manager')
|
||||
return (
|
||||
<span className="flex flex-col shrink-0">
|
||||
<IconButton size="sm" variant="ghost" className="!h-5" label={t('products.moveUp')} disabled={first} onClick={onUp}><ChevronUp size={14} /></IconButton>
|
||||
<IconButton size="sm" variant="ghost" className="!h-5" label={t('products.moveDown')} disabled={last} onClick={onDown}><ChevronDown size={14} /></IconButton>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** The round "default" marker of a choice. */
|
||||
export function DefaultToggle({ on, onClick }) {
|
||||
const { t } = useTranslation('manager')
|
||||
return (
|
||||
<button type="button" onClick={onClick} aria-pressed={on} title={t('products.editor.default')} aria-label={t('products.editor.default')}
|
||||
className={cx('w-6 h-6 shrink-0 rounded-full border-2 grid place-items-center', on ? 'border-accent bg-accent' : 'border-line-strong bg-surface hover:border-accent')}>
|
||||
{on && <span className="w-2.5 h-2.5 rounded-full bg-accent-fg" />}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** The heart: shown first to the waiter. */
|
||||
export function FavouriteToggle({ on, onClick }) {
|
||||
const { t } = useTranslation('manager')
|
||||
return (
|
||||
<IconButton size="sm" variant="ghost" label={on ? t('products.editor.unfavourite') : t('products.editor.favourite')} aria-pressed={on} onClick={onClick}
|
||||
className={on ? 'text-danger' : 'text-ink-3'}>
|
||||
<Heart size={16} fill={on ? 'currentColor' : 'none'} />
|
||||
</IconButton>
|
||||
)
|
||||
}
|
||||
|
||||
/** A small labelled checkbox. */
|
||||
export function Check({ checked, onChange, children }) {
|
||||
return (
|
||||
<label className="inline-flex items-center gap-1.5 text-label text-ink-2 cursor-pointer select-none shrink-0">
|
||||
<input type="checkbox" className="w-4 h-4 accent-[var(--x-accent)]" checked={!!checked} onChange={e => onChange(e.target.checked)} />
|
||||
{children}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
/** The sub-choices under a choice ("Syrup" → Caramel, Vanilla). */
|
||||
export function SubChoices({ subs, parent, onChange, withMultiple = false }) {
|
||||
const { t } = useTranslation('manager')
|
||||
if (!subs?.length) return null
|
||||
const set = (i, k, v) => onChange(subs.map((s, j) => (j === i ? { ...s, [k]: v } : k === 'is_default' && v ? { ...s, is_default: false } : s)))
|
||||
const move = (i, d) => { const j = i + d; if (j < 0 || j >= subs.length) return; const n = [...subs]; [n[i], n[j]] = [n[j], n[i]]; onChange(n) }
|
||||
return (
|
||||
<div className="border-t border-line bg-surface-2 px-3 py-2 grid gap-2">
|
||||
<p className="text-caption font-semibold text-ink-2">{t('products.editor.subsOf', { name: parent || '…' })}</p>
|
||||
{subs.map((s, i) => (
|
||||
<div key={i} className="flex flex-wrap items-center gap-2 pl-4">
|
||||
<MoveButtons first={i === 0} last={i === subs.length - 1} onUp={() => move(i, -1)} onDown={() => move(i, 1)} />
|
||||
<DefaultToggle on={s.is_default} onClick={() => set(i, 'is_default', !s.is_default)} />
|
||||
<Input size="sm" className="flex-1 min-w-28" value={s.name} onChange={e => set(i, 'name', e.target.value)} placeholder={t('products.editor.subPlaceholder')} />
|
||||
<PriceInput className="w-28" value={s.extra_cost} allowNegative onChange={v => set(i, 'extra_cost', v)} label={t('products.editor.extraCost')} />
|
||||
{withMultiple && <Check checked={s.allow_multiple} onChange={v => set(i, 'allow_multiple', v)}>{t('products.editor.multiple')}</Check>}
|
||||
<Check checked={s.is_compact} onChange={v => set(i, 'is_compact', v)}>{t('products.editor.compact')}</Check>
|
||||
<IconButton size="sm" variant="ghost" label={t('products.editor.remove')} onClick={() => onChange(subs.filter((_, j) => j !== i))}><Trash2 size={14} /></IconButton>
|
||||
</div>
|
||||
))}
|
||||
<Button size="sm" variant="ghost" icon={<Plus size={14} />} className="justify-self-start ml-4"
|
||||
onClick={() => onChange([...subs, { name: '', extra_cost: 0, is_default: false, allow_multiple: false, is_compact: false }])}>{t('products.editor.addSub')}</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** A choice group's header (a folder of choices): fold, rename, remove. */
|
||||
export function GroupHeader({ group, folded, onFold, onRename, onRemove }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [name, setName] = useState(group.name)
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 mt-2">
|
||||
<button type="button" onClick={onFold} aria-expanded={!folded}
|
||||
className="flex-1 flex items-center gap-2 px-3 py-2 rounded-control bg-accent-soft text-accent-ink text-label font-semibold text-left">
|
||||
<ChevronDown size={14} className={cx('transition-transform duration-fast', folded && '-rotate-90')} aria-hidden="true" />
|
||||
{editing
|
||||
? <input className="flex-1 min-w-0 bg-surface text-ink rounded px-1" autoFocus value={name} onChange={e => setName(e.target.value)}
|
||||
onClick={e => e.stopPropagation()} onBlur={() => { onRename(name); setEditing(false) }} onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} />
|
||||
: <span className="flex-1 truncate">{group.name || t('products.editor.unnamedGroup')}</span>}
|
||||
</button>
|
||||
<IconButton size="sm" variant="ghost" label={t('products.editor.renameGroup')} onClick={() => { setName(group.name); setEditing(true) }}><Pencil size={14} /></IconButton>
|
||||
<IconButton size="sm" variant="ghost" label={t('products.editor.removeGroup')} onClick={onRemove}><Trash2 size={14} /></IconButton>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// The products page's arithmetic (plan step 6.3), without React (tests/products.test.mjs).
|
||||
//
|
||||
// A product is listed in one or more categories (D-23): `category_ids` (main one first) and
|
||||
// `categories` [{category_id, sort_order}] = its position in each list. The main category
|
||||
// (`primary_category_id`) decides tickets and reports. The page shows a product in every
|
||||
// category it's listed in, and orders each category's list on its own.
|
||||
import { latin } from '@xenia/i18n/latin'
|
||||
|
||||
/** The filters when nothing is filtered. */
|
||||
export const NO_FILTERS = { priceMin: '', priceMax: '', quality: 'all', unavailableOnly: false, showArchived: false }
|
||||
|
||||
export const SCOPES = { all: null, service: '__service__', none: '__uncategorized__', archived: '__archived__' }
|
||||
const SPECIAL = new Set(Object.values(SCOPES))
|
||||
export const isCategoryScope = scope => !SPECIAL.has(scope)
|
||||
|
||||
const bySort = (a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0) || a.id - b.id
|
||||
|
||||
export const topLevel = (categories = []) => categories.filter(c => !c.parent_id).sort(bySort)
|
||||
export const subsOf = (categories = [], id) => categories.filter(c => c.parent_id === id).sort(bySort)
|
||||
|
||||
/** The categories as a tree for pickers: [{cat, depth}] top level first, each followed by its sub-categories. */
|
||||
export const categoryTree = (categories = []) =>
|
||||
topLevel(categories).flatMap(c => [{ cat: c, depth: 0 }, ...subsOf(categories, c.id).map(s => ({ cat: s, depth: 1 }))])
|
||||
|
||||
/** A category's name in a picker: sub-categories indented under their parent. */
|
||||
export const treeLabel = (cat, depth) => (depth ? `${String.fromCharCode(160, 160)}↳ ${cat.name}` : cat.name)
|
||||
|
||||
export const listedIn = (p, catId) => (p.category_ids ?? []).includes(catId)
|
||||
export const isArchived = p => p.lifecycle_status === 'archived'
|
||||
|
||||
/** Its position in a category's list (falls back to the old global order). */
|
||||
export function positionIn(p, catId) {
|
||||
const m = (p.categories ?? []).find(x => x.category_id === catId)
|
||||
return m ? m.sort_order : (p.sort_order ?? 0)
|
||||
}
|
||||
|
||||
/** How many live products a category lists (a top-level one counts its sub-categories' too, each product once). */
|
||||
export function countIn(products = [], categories = [], catId) {
|
||||
const ids = new Set([catId, ...subsOf(categories, catId).map(c => c.id)])
|
||||
return products.filter(p => !isArchived(p) && (p.category_ids ?? []).some(c => ids.has(c))).length
|
||||
}
|
||||
|
||||
/** The products a scope shows, before filters. */
|
||||
export function scopeProducts(products = [], categories = [], scope, { showArchived = false } = {}) {
|
||||
const live = p => showArchived || !isArchived(p)
|
||||
if (scope === SCOPES.archived) return products.filter(isArchived)
|
||||
if (scope === SCOPES.service) return products.filter(p => p.is_service_item && !isArchived(p))
|
||||
if (scope === SCOPES.none) return products.filter(p => !(p.category_ids ?? []).length && !p.is_service_item && !isArchived(p))
|
||||
if (scope == null) return products.filter(p => !p.is_service_item && live(p))
|
||||
const ids = new Set([scope, ...subsOf(categories, scope).map(c => c.id)])
|
||||
return products.filter(p => live(p) && (p.category_ids ?? []).some(c => ids.has(c)))
|
||||
}
|
||||
|
||||
/** Search (accents ignored, Latin letters find Greek names), price range, missing photo / category, unavailable. */
|
||||
export function applyFilters(list, { search = '', priceMin = null, priceMax = null, quality = 'all', unavailableOnly = false } = {}) {
|
||||
const fold = v => latin(v).toLowerCase()
|
||||
const q = fold(search.trim())
|
||||
return list.filter(p => (!q || fold(p.name).includes(q))
|
||||
&& (priceMin == null || p.base_price >= priceMin)
|
||||
&& (priceMax == null || p.base_price <= priceMax)
|
||||
&& (quality !== 'no-photo' || !p.image_url)
|
||||
&& (quality !== 'no-cat' || !(p.category_ids ?? []).length)
|
||||
&& (!unavailableOnly || !p.is_available))
|
||||
}
|
||||
|
||||
/**
|
||||
* The list in groups, each a category's list in its own order:
|
||||
* all products → by main category (each product once);
|
||||
* a top-level category → itself and each sub-category (a product listed in two shows in both);
|
||||
* `sub` narrows it to one of them;
|
||||
* a sub-category → that list; the special scopes → one group without a category.
|
||||
* Each group: { key (category id or '__none__'), cat, items }.
|
||||
*/
|
||||
export function groupProducts(list, categories = [], scope, sub = null) {
|
||||
const catOf = id => categories.find(c => c.id === id) ?? null
|
||||
const make = (key, items) => {
|
||||
const cat = key === '__none__' ? null : catOf(key)
|
||||
return { key, cat, items: [...items].sort((a, b) => (key === '__none__' ? bySort(a, b) : positionIn(a, key) - positionIn(b, key) || a.id - b.id)) }
|
||||
}
|
||||
if (!isCategoryScope(scope) && scope !== null) return list.length ? [make('__none__', list)] : []
|
||||
if (scope === null) {
|
||||
const groups = new Map()
|
||||
for (const p of list) {
|
||||
const key = p.primary_category_id ?? '__none__'
|
||||
if (!groups.has(key)) groups.set(key, [])
|
||||
groups.get(key).push(p)
|
||||
}
|
||||
const order = new Map(categoryTree(categories).map(({ cat }, i) => [cat.id, i]))
|
||||
return [...groups.entries()].map(([k, items]) => make(k, items))
|
||||
.sort((a, b) => (order.get(a.key) ?? 1e9) - (order.get(b.key) ?? 1e9))
|
||||
}
|
||||
const keys = [scope, ...subsOf(categories, scope).map(c => c.id)].filter(k => sub == null || k === sub)
|
||||
return keys.map(k => make(k, list.filter(p => listedIn(p, k)))).filter(g => g.items.length)
|
||||
}
|
||||
|
||||
/** Move `fromId` before/after `toId` in a group: the body for PUT /api/products/reorder (per category). */
|
||||
export function reorderBody(group, fromId, toId, after = false) {
|
||||
const items = group.items.filter(p => p.id !== fromId)
|
||||
const moved = group.items.find(p => p.id === fromId)
|
||||
if (!moved || fromId === toId) return null
|
||||
const at = items.findIndex(p => p.id === toId)
|
||||
if (at < 0) return null
|
||||
items.splice(after ? at + 1 : at, 0, moved)
|
||||
const category_id = group.key === '__none__' ? null : group.key
|
||||
return items.map((p, i) => ({ id: p.id, sort_order: i, ...(category_id != null ? { category_id } : {}) }))
|
||||
}
|
||||
|
||||
/** One step up (-1) or down (+1) in a group; null at the ends. */
|
||||
export function stepBody(group, id, step) {
|
||||
const i = group.items.findIndex(p => p.id === id)
|
||||
const j = i + step
|
||||
if (i < 0 || j < 0 || j >= group.items.length) return null
|
||||
return reorderBody(group, id, group.items[j].id, step > 0)
|
||||
}
|
||||
|
||||
/** Reorder ids: move `fromId` to where `toId` is. */
|
||||
export function moveId(ids, fromId, toId) {
|
||||
const from = ids.indexOf(fromId)
|
||||
const to = ids.indexOf(toId)
|
||||
if (from < 0 || to < 0 || from === to) return null
|
||||
const next = [...ids]
|
||||
next.splice(to, 0, next.splice(from, 1)[0])
|
||||
return next
|
||||
}
|
||||
|
||||
/** What it costs the venue (the breakdown's sum, else the simple cost) and the margin; null without a cost. */
|
||||
export function costOf(p) {
|
||||
const cost = p.cost_breakdown?.length ? p.cost_breakdown.reduce((s, e) => s + (Number(e.amount) || 0), 0)
|
||||
: (p.cost_simple ?? null)
|
||||
if (cost == null || cost === '') return null
|
||||
const price = Number(p.base_price) || 0
|
||||
return { cost: Number(cost), over: Number(cost) > price, margin: price > 0 ? (price - cost) / price : null }
|
||||
}
|
||||
|
||||
/** A product's categories after a bulk change: 'move' = only that one, 'add' = also that one. */
|
||||
export function bulkCategories(p, catId, mode) {
|
||||
if (mode === 'move') return { category_ids: [catId], primary_category_id: catId }
|
||||
const ids = [...new Set([...(p.category_ids ?? []), catId])]
|
||||
return { category_ids: ids, primary_category_id: p.primary_category_id ?? catId }
|
||||
}
|
||||
Reference in New Issue
Block a user