feat(manager): products on the page rule, a wide product editor, alternate prices per sales point

- Products: the categories and the list as two containers side by side (the tree sticky), the
  toolbar on the shared controls (search, filters, list/grid, New all one height), archive /
  delete red in a container.
- Product editor: a wide dialog (Dialog size=wide: ~88% of a 16:9 screen, capped on ultrawides),
  the shared tab strip (no up/down scrollbar), one name and description with a language switch
  above them, unit (modern dropdown) and price on one row, 'Edit alternate prices' under Where
  it's sold (the product's own price per sales point: default / set / +- amount / +- %, rounding).
- Pricing: shared tabs in the address, a new 'Order channel prices' tab (rules per product,
  category or sales point, multi-select, the most precise wins).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 15:11:35 +02:00
co-authored by Claude Opus 5.5
parent 94c10944ed
commit 476c55abc0
17 changed files with 636 additions and 104 deletions
@@ -0,0 +1,152 @@
// Pricing → Order channel prices (2026-11-20): a product's price at a sales point. A rule is for
// one or more sales points and names products, categories, or neither (the whole channel); it
// sets the price (one product), adds an amount or a percentage (with rounding). The most precise
// rule wins: the product's own, then its category's, then the channel's. Backend:
// /api/pricing/channel-prices (services/channel_prices.py). Quick edit per product: the product
// editor's "Edit alternate prices" (ProductChannelPricesDialog).
import { useMemo, useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Pencil, Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { SALES_POINTS } from '@xenia/access'
import { Button, Dialog, Dropdown, EmptyState, Field, IconButton, Input, Segmented, Spinner, Switch } from '@xenia/ui'
import { Pill } from '../overview/parts'
import { useLiveQuery } from '../../live/useLiveQuery'
import * as api from './pricingApi'
import { ACTIONS, ROUNDINGS, blankRule, levelOf, roundingKey, ruleBody, ruleProblems, ruleToForm } from './channelPricing'
import { useCatalog } from './useCatalog'
import { useActionText } from './useActionText'
const LEVEL_TONE = { product: 'accent', category: 'info', channel: 'neutral' }
export default function ChannelPricesTab() {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
const qc = useQueryClient()
const catalog = useCatalog()
const actionText = useActionText()
const { data: rules, isPending } = useLiveQuery({ queryKey: ['pricing', 'channel-prices'], queryFn: api.listChannelPrices, events: api.PRICING_EVENTS })
const [edit, setEdit] = useState(null) // a rule (or blank) being edited
const [removing, setRemoving] = useState(null)
const names = useMemo(() => ({
product: Object.fromEntries(catalog.products.map(p => [p.id, p.name])),
category: Object.fromEntries(catalog.categories.map(c => [c.id, c.plain])),
}), [catalog])
const refresh = () => qc.invalidateQueries({ queryKey: ['pricing', 'channel-prices'] })
const remove = useMutation({
mutationFn: r => api.deleteChannelPrice(r.id),
onSuccess: () => { setRemoving(null); refresh(); toast.success(t('pricing.channels.removed')) },
onError: e => toast.error(errorMessage(e, t)),
})
const toggle = useMutation({
mutationFn: r => api.saveChannelPrice(r.id, { ...ruleBody(ruleToForm(r)), is_active: !r.is_active }),
onSuccess: refresh, onError: e => toast.error(errorMessage(e, t)),
})
const order = { product: 0, category: 1, channel: 2 }
const list = [...(rules ?? [])].sort((a, b) => order[levelOf(a)] - order[levelOf(b)] || b.id - a.id)
return (
<div className="grid gap-4" data-testid="channel-prices">
<div className="flex flex-wrap items-start gap-3">
<p className="flex-1 min-w-64 text-body text-ink-2 max-w-3xl">{t('pricing.channels.intro')}</p>
<Button icon={<Plus size={16} />} onClick={() => setEdit(blankRule())} data-testid="channel-price-new">{t('pricing.channels.new')}</Button>
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !list.length ? <EmptyState title={t('pricing.channels.none')} description={t('pricing.channels.noneHint')} />
: (
<ul className="grid gap-3">
{list.map(r => {
const lv = levelOf(r)
const what = lv === 'channel' ? t('pricing.channels.everything')
: (lv === 'product' ? r.product_ids : r.category_ids).map(id => names[lv][id] ?? `#${id}`).join(', ')
return (
<li key={r.id} className={`px-card py-card-y rounded-card border border-line bg-surface shadow-raised flex flex-wrap items-center gap-3 ${r.is_active ? '' : 'opacity-60'}`} data-testid="channel-price">
<Pill tone={LEVEL_TONE[lv]}>{t(`pricing.channels.level.${lv}`)}</Pill>
<span className="flex-1 min-w-56 grid">
<span className="text-body font-semibold text-ink">{r.name || what}</span>
<span className="text-label text-ink-2">
{r.name && `${what} · `}{r.sales_points.map(sp => tc(`salesPoints.${sp}.name`)).join(', ')}
</span>
</span>
<span className="text-body font-semibold tabular-nums text-ink" data-testid="channel-price-action">{actionText(r)}</span>
<span className="flex items-center gap-1.5">
<IconButton size="sm" variant="ghost" tone="accent" label={t('pricing.channels.edit')} onClick={() => setEdit(ruleToForm(r))}><Pencil size={15} /></IconButton>
<IconButton size="sm" variant="ghost" tone="danger" label={t('pricing.channels.remove')} onClick={() => setRemoving(r)}><Trash2 size={15} /></IconButton>
<Switch className="ml-2" checked={r.is_active} onChange={() => toggle.mutate(r)} aria-label={t('pricing.channels.active')} />
</span>
</li>
)
})}
</ul>
)}
{edit && <RuleDialog rule={edit} catalog={catalog} onClose={() => setEdit(null)} onSaved={() => { setEdit(null); refresh() }} />}
{removing && (
<Dialog open size="sm" onClose={() => setRemoving(null)} title={t('pricing.channels.removeTitle')}
footer={<>
<Button variant="secondary" onClick={() => setRemoving(null)}>{t('pricing.channels.cancel')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing)} data-testid="channel-price-remove">{t('pricing.channels.remove')}</Button>
</>}>
<p className="text-body text-ink-2">{t('pricing.channels.removeBody')}</p>
</Dialog>
)}
</div>
)
}
function RuleDialog({ rule, catalog, onClose, onSaved }) {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
const [f, setF] = useState(rule)
const [tried, setTried] = useState(false)
const set = (k, v) => setF(x => ({ ...x, [k]: v }))
const wrong = ruleProblems(f)
const save = useMutation({
mutationFn: () => api.saveChannelPrice(f.id, ruleBody(f)),
onSuccess: () => { toast.success(t('pricing.channels.saved')); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (!wrong.length) save.mutate() }
const err = k => (tried && wrong.includes(k) ? t(`pricing.channels.wrong.${k}`) : undefined)
return (
<Dialog open size="lg" onClose={onClose} title={f.id ? t('pricing.channels.editTitle') : t('pricing.channels.newTitle')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('pricing.channels.cancel')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="channel-price-save">{t('pricing.channels.save')}</Button>
</>}>
<div className="grid gap-4" data-testid="channel-price-dialog">
<Field label={t('pricing.channels.points')} required error={err('points')}>
<Dropdown multiple value={f.sales_points} onChange={v => set('sales_points', v)} placeholder={t('pricing.channels.pickPoints')} data-testid="channel-price-points"
options={SALES_POINTS.map(sp => ({ value: sp, label: tc(`salesPoints.${sp}.name`) }))} />
</Field>
<div className="grid gap-4 sm:grid-cols-2">
<Field label={t('pricing.channels.products')} hint={t('pricing.channels.productsHint')} error={err('set_one')}>
<Dropdown multiple value={f.product_ids} onChange={v => set('product_ids', v)} placeholder={t('pricing.channels.none_')} searchable data-testid="channel-price-products"
options={catalog.products.map(p => ({ value: p.id, label: p.name }))} />
</Field>
<Field label={t('pricing.channels.categories')} hint={t('pricing.channels.categoriesHint')}>
<Dropdown multiple value={f.category_ids} onChange={v => set('category_ids', v)} placeholder={t('pricing.channels.none_')} searchable data-testid="channel-price-categories"
options={catalog.categories.map(c => ({ value: c.id, label: c.name }))} />
</Field>
</div>
<Field label={t('pricing.channels.change')}>
<Segmented value={f.action_type} onChange={v => set('action_type', v)}
options={ACTIONS.map(a => ({ value: a, label: t(`pricing.channels.action.${a}`), testId: `channel-price-action-${a}` }))} />
</Field>
<div className="grid gap-4 sm:grid-cols-2">
<Field label={t(`pricing.channels.valueOf.${f.action_type}`)} hint={f.action_type === 'set' ? undefined : t('pricing.channels.valueHint')} required error={err('value')}>
<Input inputMode="decimal" value={f.value} onChange={e => set('value', e.target.value)} placeholder={f.action_type === 'add_percent' ? '-10' : '0,00'} data-testid="channel-price-value" />
</Field>
<Field label={t('pricing.channels.rounding')}>
<Dropdown value={f.round_to} onChange={v => set('round_to', v)} options={ROUNDINGS.map(r => ({ value: r, label: t(`pricing.roundings.${roundingKey(r)}`) }))} />
</Field>
</div>
<Field label={t('pricing.channels.name')} hint={t('pricing.channels.nameHint')}>
<Input value={f.name} onChange={e => set('name', e.target.value)} maxLength={120} />
</Field>
<p className="text-caption text-ink-2 rounded-control bg-surface-2 border border-line px-3 py-2">{t('pricing.channels.order')}</p>
</div>
</Dialog>
)
}
@@ -1,35 +1,30 @@
// Management → Pricing (plan step 6.7): price rules, price groups, deals and the waiters' discount
// limits, one tab each. Changes reach the counter, the phones and the tablets at once: new prices
// apply to what is added to orders from then on (lines already on an order keep their price).
import { useState } from 'react'
// Management → Pricing (plan step 6.7): price rules, price groups, deals, the waiters' discount
// limits and (2026-11-20) order channel prices, one tab each. Changes reach the counter, the phones
// and the tablets at once: new prices apply to what is added to orders from then on (lines already
// on an order keep their price). The tab is in the address (?tab=).
import { useSearchParams } from 'react-router-dom'
import { useTranslation } from '@xenia/i18n'
import { Page } from '@xenia/ui'
import { Page, PageHeader, Tabs } from '@xenia/ui'
import ChannelPricesTab from './ChannelPricesTab'
import DealsTab from './DealsTab'
import DiscountsTab from './DiscountsTab'
import ModifiersTab from './ModifiersTab'
import PriceGroupsTab from './PriceGroupsTab'
const TABS = ['rules', 'groups', 'deals', 'discounts']
const TABS = ['rules', 'channels', 'groups', 'deals', 'discounts']
export default function PricingPage() {
const { t } = useTranslation('manager')
const [tab, setTab] = useState('rules')
const [params, setParams] = useSearchParams()
const tab = TABS.includes(params.get('tab')) ? params.get('tab') : 'rules'
const setTab = v => setParams(p => { const n = new URLSearchParams(p); n.set('tab', v); return n }, { replace: true })
return (
<Page testId="pricing-page">
<header className="grid gap-1">
<h1 className="text-heading font-semibold text-ink">{t('pricing.pageTitle')}</h1>
<p className="text-body text-ink-2 max-w-3xl">{t('pricing.intro')}</p>
</header>
<div className="flex flex-wrap gap-1 border-b border-line" role="tablist" aria-label={t('pricing.pageTitle')}>
{TABS.map(k => (
<button key={k} type="button" role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`pricing-tab-${k}`}
className={`px-3 py-2 -mb-px border-b-2 text-label font-medium transition-colors duration-fast
${tab === k ? 'border-accent text-accent-ink' : 'border-transparent text-ink-2 hover:text-ink'}`}>
{t(`pricing.tabs.${k}`)}
</button>
))}
</div>
<Page testId="pricing-page"
top={<Tabs size="lg" value={tab} onChange={setTab} aria-label={t('pricing.pageTitle')}
tabs={TABS.map(k => ({ id: k, label: t(`pricing.tabs.${k}`), testId: `pricing-tab-${k}` }))} />}>
<PageHeader title={t('pricing.pageTitle')} subtitle={t('pricing.intro')} />
{tab === 'rules' && <ModifiersTab />}
{tab === 'channels' && <ChannelPricesTab />}
{tab === 'groups' && <PriceGroupsTab />}
{tab === 'deals' && <DealsTab />}
{tab === 'discounts' && <DiscountsTab />}
@@ -0,0 +1,95 @@
// The product editor's "Edit alternate prices" (2026-11-20): this product's own price at each sales
// point it is sold at — the default price, a set price, ± an amount or ± a percentage (rounded).
// "Default" leaves it to the category's or the channel's rule (Pricing → Order channel prices),
// shown greyed. Saves only this product's own rules (PUT /api/pricing/channel-prices/product/{id}).
import { useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Dropdown, EmptyState, Input, Spinner, cx } from '@xenia/ui'
import * as api from './pricingApi'
import { ACTIONS, ROUNDINGS, pointRowFromApi, pointsBody, roundingKey, rowPrice, rowProblem } from './channelPricing'
import { useActionText } from './useActionText'
export default function ProductChannelPricesDialog({ product, onClose }) {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
const { formatMoney } = useFormat()
const actionText = useActionText()
const [rows, setRows] = useState(null)
const [busy, setBusy] = useState(false)
const [error, setError] = useState(null)
useEffect(() => {
api.productChannelPrices(product.id).then(d => setRows(d.points.map(pointRowFromApi))).catch(e => setError(errorMessage(e, t)))
}, [product.id, t])
const set = (i, k, v) => setRows(rs => rs.map((r, j) => (j === i ? { ...r, [k]: v } : r)))
const bad = (rows ?? []).some(rowProblem)
const save = async () => {
setBusy(true)
try {
await api.saveProductChannelPrices(product.id, pointsBody(rows))
toast.success(t('pricing.channels.savedFor', { name: product.name }))
onClose()
} catch (e) { toast.error(errorMessage(e, t)) }
setBusy(false)
}
return (
<Dialog open size="xl" onClose={onClose} title={t('pricing.channels.productTitle', { name: product.name })}
description={t('pricing.channels.productIntro', { price: formatMoney(product.base_price ?? 0) })}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('pricing.channels.cancel')}</Button>
<Button loading={busy} disabled={!rows || bad} onClick={save} data-testid="product-channel-save">{t('pricing.channels.save')}</Button>
</>}>
{error ? <EmptyState title={error} /> : !rows ? <div className="py-10 flex justify-center"><Spinner /></div>
: !rows.length ? <EmptyState title={t('pricing.channels.notSold')} />
: (
<div className="rounded-card border border-line overflow-x-auto" data-testid="product-channel-prices">
<table className="w-full text-label">
<thead className="bg-surface-2 text-ink-3">
<tr className="text-overline font-semibold uppercase tracking-wide">
<th className="px-card py-2 text-left">{t('pricing.channels.point')}</th>
<th className="px-2 py-2 text-left w-48">{t('pricing.channels.change')}</th>
<th className="px-2 py-2 text-left w-32">{t('pricing.channels.value')}</th>
<th className="px-2 py-2 text-left w-52">{t('pricing.channels.rounding')}</th>
<th className="px-card py-2 text-right w-28">{t('pricing.channels.price')}</th>
</tr>
</thead>
<tbody className="divide-y divide-line">
{rows.map((r, i) => {
const price = rowPrice(r)
const own = r.mode !== 'default'
return (
<tr key={r.sales_point} className="align-middle" data-testid="product-channel-row" data-point={r.sales_point}>
<td className="px-card py-2.5">
<span className="grid">
<span className="text-body font-medium text-ink">{tc(`salesPoints.${r.sales_point}.name`)}</span>
{!own && r.inherited && <span className="text-caption text-ink-3">{t(`pricing.channels.from.${r.inherited.level}`, { what: actionText(r.inherited) })}</span>}
</span>
</td>
<td className="px-2 py-2">
<Dropdown size="sm" value={r.mode} onChange={v => set(i, 'mode', v)} data-testid="product-channel-mode"
options={[{ value: 'default', label: t('pricing.channels.action.default') }, ...ACTIONS.map(a => ({ value: a, label: t(`pricing.channels.action.${a}`) }))]} />
</td>
<td className="px-2 py-2">
<Input size="sm" inputMode="decimal" disabled={!own} value={r.value} onChange={e => set(i, 'value', e.target.value)}
placeholder={r.mode === 'add_percent' ? '-10' : '0,00'} aria-label={t('pricing.channels.value')} data-testid="product-channel-value"
className={cx(own && rowProblem(r) && 'border-danger')} />
</td>
<td className="px-2 py-2">
<Dropdown size="sm" disabled={!own || r.mode === 'set'} value={r.round_to} onChange={v => set(i, 'round_to', v)}
options={ROUNDINGS.map(x => ({ value: x, label: t(`pricing.roundings.${roundingKey(x)}`) }))} />
</td>
<td className={cx('px-card py-2 text-right tabular-nums font-semibold', own ? 'text-ink' : 'text-ink-3')} data-testid="product-channel-price">
{price == null ? '—' : formatMoney(price)}
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
<p className="mt-4 text-caption text-ink-2">{t('pricing.channels.order')}</p>
</Dialog>
)
}
@@ -0,0 +1,76 @@
// Order channel prices (2026-11-20): a product's price at a sales point, as the backend makes it
// (services/channel_prices.py). Plain JS, unit-tested (tests/channelPricing.test.mjs).
// set the price there (one product only)
// add_amount ± euros on the default price
// add_percent ± % of the default price, then optionally rounded
// The most precise rule wins: the product's own > its category's > the whole channel's.
import { parseNumber } from '@xenia/i18n/number'
export const ACTIONS = ['set', 'add_amount', 'add_percent']
export const ROUNDINGS = ['', '0.05', '0.10', '0.20', '0.50', 'x.99', 'x.00']
export const roundingKey = r => (r ? r.replace('.', '_') : 'none')
const num = text => parseNumber(String(text ?? ''), { decimals: 2, allowNegative: true })
/** As services/pricing.py _round_to. */
export function roundTo(v, mode) {
if (mode === '0.05') return Math.round(v / 0.05) * 0.05
if (mode === '0.10') return Math.round(v / 0.10) * 0.10
if (mode === '0.20') return Math.round(v / 0.20) * 0.20
if (mode === '0.50') return Math.round(v / 0.50) * 0.50
if (mode === 'x.99') return v >= 1 ? Math.trunc(v) + 0.99 : v
if (mode === 'x.00') return Math.round(v)
return v
}
/** The price a rule makes from the default price (never below zero). */
export function applyRule(base, { action_type: a, value, round_to: r }) {
const v = Number(value) || 0
let out = a === 'set' ? v : a === 'add_amount' ? base + v : a === 'add_percent' ? base * (1 + v / 100) : base
out = Math.max(0, out)
return Math.round(roundTo(out, r || '') * 100) / 100
}
/** Which level a rule works at. */
export const levelOf = rule => (rule.product_ids?.length ? 'product' : rule.category_ids?.length ? 'category' : 'channel')
export const blankRule = () => ({ name: '', sales_points: [], product_ids: [], category_ids: [], action_type: 'add_percent', value: '', round_to: '', is_active: true })
export const ruleToForm = r => ({ ...blankRule(), ...r, name: r.name ?? '', value: String(r.value), round_to: r.round_to ?? '' })
/** What is wrong with the form: points, value, set_one (a set price needs exactly one product, no categories). */
export function ruleProblems(f) {
const out = []
if (!f.sales_points.length) out.push('points')
const v = num(f.value)
if (v == null || (f.action_type === 'set' && v < 0)) out.push('value')
if (f.action_type === 'set' && (f.product_ids.length !== 1 || f.category_ids.length)) out.push('set_one')
return out
}
export function ruleBody(f) {
return { name: f.name.trim() || null, sales_points: f.sales_points, product_ids: f.product_ids, category_ids: f.category_ids,
action_type: f.action_type, value: num(f.value), round_to: f.round_to || null, is_active: f.is_active }
}
/** The product editor's quick edit: a row per sales point → { action_type, value, round_to } or null. */
export function pointsBody(rows) {
return Object.fromEntries(rows.map(r => [r.sales_point, r.mode === 'default' ? null
: { action_type: r.mode, value: num(r.value), round_to: r.round_to || null }]))
}
export function pointRowFromApi(p) {
return { sales_point: p.sales_point, mode: p.own?.action_type ?? 'default', value: p.own ? String(p.own.value) : '',
round_to: p.own?.round_to ?? '', inherited: p.fallback ?? null, base: p.base_price }
}
/** The price a quick-edit row shows: its own rule's, else what the category / channel rule makes, else the default. */
export function rowPrice(row) {
if (row.mode !== 'default') {
const v = num(row.value)
return v == null ? null : applyRule(row.base, { action_type: row.mode, value: v, round_to: row.round_to })
}
return row.inherited ? applyRule(row.base, row.inherited) : row.base
}
export const rowProblem = row => row.mode !== 'default' && (num(row.value) == null || (row.mode === 'set' && num(row.value) < 0))
@@ -33,3 +33,10 @@ export const listProducts = () => client.get('/api/products/', { params: { all:
export const listCategories = () => client.get('/api/products/categories').then(data)
export const listPrepZones = () => client.get('/api/prep-zones').then(data)
export const listTags = () => client.get('/api/products/tags').then(data)
// Order channel prices (2026-11-20)
export const listChannelPrices = () => client.get('/api/pricing/channel-prices').then(data)
export const saveChannelPrice = (id, body) => (id ? client.put(`/api/pricing/channel-prices/${id}`, body) : client.post('/api/pricing/channel-prices', body)).then(data)
export const deleteChannelPrice = id => client.delete(`/api/pricing/channel-prices/${id}`)
export const productChannelPrices = id => client.get(`/api/pricing/channel-prices/product/${id}`).then(data)
export const saveProductChannelPrices = (id, points) => client.put(`/api/pricing/channel-prices/product/${id}`, { points }).then(data)
@@ -0,0 +1,15 @@
// A channel price's change as text: "€2.80", "+€0.50", "−10 % · To the nearest €0.50" (2026-11-20).
import { useFormat, useTranslation } from '@xenia/i18n'
import { roundingKey } from './channelPricing'
export function useActionText() {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
return r => {
const v = Number(r.value)
const text = r.action_type === 'set' ? formatMoney(v)
: r.action_type === 'add_amount' ? `${v >= 0 ? '+' : '−'}${formatMoney(Math.abs(v))}`
: `${v >= 0 ? '+' : '−'}${Math.abs(v)} %`
return r.round_to ? `${text} · ${t(`pricing.roundings.${roundingKey(r.round_to)}`)}` : text
}
}
@@ -51,14 +51,14 @@ export default function CategoryTree({ categories, products, scope, onScope, onA
{!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>
<IconButton size="sm" variant="ghost" tone="danger" 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">
<aside className="rounded-card border border-line bg-surface shadow-raised flex flex-col min-h-0 overflow-hidden md:sticky md:top-0 md:max-h-[calc(100dvh-7.5rem)]" data-testid="category-tree">
<div className="flex items-center gap-2 px-card pt-card-y 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>
@@ -147,7 +147,7 @@ function Row({ p, g, first, last, categories, prepZones, selected, onSelect, onE
</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>
<IconButton size="sm" variant="ghost" tone="danger" label={archived ? t('products.delete') : t('products.archive')} onClick={() => onRemove(p)} data-testid="product-remove">{archived ? <Trash2 size={16} /> : <Archive size={16} />}</IconButton>
</span>
</div>
)
@@ -165,7 +165,7 @@ function Card({ p, categories, selected, onSelect, onEdit, onRemove, onToggle })
<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>
<IconButton size="sm" variant="secondary" tone="danger" label={archived ? t('products.delete') : t('products.archive')} onClick={() => onRemove(p)}>{archived ? <Trash2 size={14} /> : <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')}
@@ -8,7 +8,7 @@ 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 { Button, Dialog, EmptyState, Page, Spinner } from '@xenia/ui'
import { Package } from 'lucide-react'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
@@ -97,14 +97,15 @@ export default function ProductsPage() {
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">
<Page testId="products-page">
<div className="grid gap-5 md:grid-cols-[minmax(17rem,22rem)_minmax(0,1fr)] items-start">
<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">
<section className="min-w-0 rounded-card border border-line bg-surface shadow-raised" data-testid="products-panel">
<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 && (
@@ -117,7 +118,7 @@ export default function ProductsPage() {
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">
<div className="flex items-center justify-between px-card py-2.5 border-y 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())} />
@@ -125,14 +126,15 @@ export default function ProductsPage() {
</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">
<div className="p-card">
{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>
</section>
</div>
{editing && (
<ProductEditor key={editing.id ?? 'new'} product={editing} categories={categories} prepZones={zones} saving={saveProduct.isPending}
@@ -157,6 +159,6 @@ export default function ProductsPage() {
<p>{t(`products.confirmBody.${confirm.kind}`)}</p>
</Dialog>
)}
</div>
</Page>
)
}
@@ -3,9 +3,9 @@
// 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 { Archive, Eye, EyeOff, Filter, FolderInput, LayoutGrid, List, Plus, Utensils, X } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { Button, IconButton, Input, cx } from '@xenia/ui'
import { Button, IconButton, Input, SearchInput, Segmented, Toolbar as Bar } from '@xenia/ui'
import { Dot } from './CategoryTree'
import { NO_FILTERS } from './productsLogic'
@@ -15,25 +15,20 @@ export default function Toolbar({ title, shown, total, search, onSearch, filters
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 className="relative px-card py-card-y grid gap-3">
<div className="flex 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>
<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>
<Bar>
<SearchInput value={search} onChange={onSearch} placeholder={t('products.search')} data-testid="products-search" />
<Button variant={open ? 'primary' : 'secondary'} icon={<Filter size={16} />} 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>
<Segmented aria-label={t('products.view')} value={view} onChange={onView}
options={[['list', <List key="l" size={16} />], ['grid', <LayoutGrid key="g" size={16} />]].map(([v, icon]) => ({ value: v, icon, label: <span className="sr-only">{t(`products.view_${v}`)}</span>, testId: `products-view-${v}` }))} />
<Button icon={<Plus size={16} />} onClick={onNew} data-testid="product-new">{t('products.new')}</Button>
</Bar>
{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">
@@ -69,7 +64,7 @@ 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">
<div className="flex flex-wrap gap-1.5 px-card pb-card-y">
{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>
@@ -82,7 +77,7 @@ export function SubChips({ parent, subs, counts, value, onChange }) {
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">
<div className="mx-card mb-card-y 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>
@@ -3,10 +3,11 @@
// 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, translatedLanguages, useAccess } from '@xenia/access'
import { BadgeEuro, Plus, Trash2, X } from 'lucide-react'
import { SALES_POINTS, translatedLanguages, useAccess, useCan, useModule } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Field, IconButton, InfoTip, Input, Select, Switch, Textarea, cx } from '@xenia/ui'
import { Button, Dropdown, Field, IconButton, InfoTip, Input, Segmented, Select, Switch, Textarea, cx } from '@xenia/ui'
import ProductChannelPricesDialog from '../../pricing/ProductChannelPricesDialog'
import MediaField from '../../media/MediaField'
import { costOf } from '../productsLogic'
import { AllergensField, CategoriesField } from './Fields'
@@ -18,42 +19,54 @@ export function InfoTab({ form, set, setForm, categories, prepZones }) {
const { venue } = useAccess()
const service = form.is_service_item
const others = translatedLanguages(venue?.language)
const main = venue?.language || 'el'
const [lang, setLang] = useState(main)
const tr = lang !== main && others.includes(lang)
const trOf = k => form.translations?.[lang]?.[k] ?? ''
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 && others.length > 0 && (
// one name and one description; the switch picks the language being typed (2026-11-20)
<div className="flex items-center gap-2" data-testid="product-lang">
<Segmented size="sm" value={lang} onChange={setLang} aria-label={t('products.editor.langOf')}
options={[main, ...others].map(l => ({ value: l, testId: `product-lang-${l}`,
label: l === main ? t('products.editor.mainLang', { language: t(`products.editor.lang.${l}`) }) : t(`products.editor.lang.${l}`) }))} />
<InfoTip>{t('products.editor.translationTip')}</InfoTip>
</div>
)}
{!service && others.map(l => (
<section key={l} className="grid gap-3 rounded-card border border-line bg-surface p-3" data-testid={`translation-${l}`}>
<span className="flex items-center gap-1 text-label font-semibold text-ink">
{t('products.editor.inLanguage', { language: t(`products.editor.lang.${l}`) })}
<InfoTip>{t('products.editor.translationTip')}</InfoTip>
</span>
<Field label={t('products.editor.trName')} hint={t('products.editor.trNameHint')}>
<Input value={form.translations?.[l]?.name ?? ''} onChange={e => setForm(f => setTranslation(f, l, 'name', e.target.value))} placeholder={form.name} data-testid={`translation-${l}-name`} />
{tr ? (
<div className="grid gap-4" data-testid={`translation-${lang}`}>
<Field label={t('products.editor.name')} hint={t('products.editor.trNameHint')}>
<Input value={trOf('name')} onChange={e => setForm(f => setTranslation(f, lang, 'name', e.target.value))} placeholder={form.name} data-testid={`translation-${lang}-name`} />
</Field>
<Field label={t('products.editor.trDescription')}>
<Textarea rows={2} value={form.translations?.[l]?.description ?? ''} onChange={e => setForm(f => setTranslation(f, l, 'description', e.target.value))} placeholder={form.description} />
<Field label={t('products.editor.description')}>
<Textarea rows={3} value={trOf('description')} onChange={e => setForm(f => setTranslation(f, lang, 'description', e.target.value))} placeholder={form.description} />
</Field>
</section>
))}
</div>
) : (<>
<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}`) }))} />
<div className={cx('grid gap-3', !service && 'grid-cols-2')}>
{!service && (
<Field label={t('products.editor.unit')} hint={WEIGHED.has(form.unit_type) ? t('products.editor.unitWeighed') : undefined}>
<Dropdown value={form.unit_type} onChange={v => set('unit_type', v)} data-testid="product-unit" 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>
)}
<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>
</div>
<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>
@@ -100,9 +113,12 @@ function Tags({ tags, onChange }) {
)
}
export function SoldAtTab({ form, set }) {
export function SoldAtTab({ form, set, product }) {
const { t } = useTranslation('manager')
const { t: tc } = useTranslation('common')
const pricingOn = useModule('pricing')
const canPrice = useCan('pricing.manage')
const [altPrices, setAltPrices] = useState(false)
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">
@@ -120,7 +136,18 @@ export function SoldAtTab({ form, set }) {
</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>
<div className="grid gap-2 rounded-control bg-surface border border-line px-3 py-3">
<p className="text-caption text-ink-2">{t('products.editor.pricePerPoint')}</p>
{pricingOn && canPrice && (
<span className="flex items-center gap-2">
<Button size="sm" variant="secondary" icon={<BadgeEuro size={14} />} disabled={!product?.id} onClick={() => setAltPrices(true)} data-testid="product-alt-prices">
{t('products.editor.altPrices')}
</Button>
{!product?.id && <span className="text-caption text-ink-3">{t('products.editor.altPricesHint')}</span>}
</span>
)}
</div>
{altPrices && <ProductChannelPricesDialog product={{ ...product, base_price: product.base_price }} onClose={() => setAltPrices(false)} />}
</section>
<section className="grid gap-2">
<h3 className="text-label font-semibold text-ink">{t('products.editor.online')}</h3>
@@ -5,7 +5,7 @@
import { useState } from 'react'
import { Copy } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, cx } from '@xenia/ui'
import { Button, Dialog, Tabs, cx } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import ChoicesPanel from './ChoicesPanel'
@@ -26,7 +26,7 @@ export default function ProductEditor({ product, categories, prepZones, saving,
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"
<Dialog open size="wide" onClose={onClose} className="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>
@@ -37,19 +37,12 @@ export default function ProductEditor({ product, categories, prepZones, saving,
</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={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-[24rem]')}>
<Tabs className="px-card bg-surface shrink-0" value={left} onChange={setLeft}
tabs={leftTabs.map(k => ({ id: k, label: t(`products.editor.left.${k}`), testId: `editor-tab-${k}` }))} />
<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 === 'soldAt' && <SoldAtTab form={form} set={set} product={product} />}
{left === 'cost' && <CostTab form={form} set={set} setForm={setForm} />}
{left === 'fiscal' && <FiscalTab form={form} set={set} vatGroups={vatGroups} />}
</div>