Files
xenia-pos-local/terminal/src/apps/pos/PosScreen.jsx
T
bonaminandClaude Opus 5.5 f2182dcb37 feat(pos): refunds at the counter on a fiscal driver layer (platform-v2 3.3e)
- services/fiscal/: one driver interface (prepare_receipt / prepare_credit_note -> send,
  credit_notes flag, status); the dTEC100extra folder bridge moved into txt_file.py as the
  first driver, same command files. fiscal_service.py removed, callers moved.
- Refunds: models/refund.py + Alembic 0016 (refunds, refund_items; ordering.refunds for
  existing owners/managers). services/refunds.py: today's business day, the cashier's open
  shift, partial quantities, items from another shift need ordering.refunds or a manager's
  approval (check()/authorize() return the override row). Paid items are never edited.
- POS: GET /api/pos/receipts, GET /api/pos/receipts/{id}, POST /api/pos/orders/{id}/refund
  (cash opens the drawer; fiscal "manual" when the driver can't issue credit notes).
- Shift totals subtract refunds and now count discounts; day close and business-day
  reports carry refunds.
- Terminal: Receipts mode (ReceiptsView, ReceiptPanel, logic/refunds.js), en/el texts.
- Tests: test_pos_refunds.py (12), terminal unit +1, terminal.mjs +7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:44:17 +02:00

259 lines
14 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// The counter POS screen (plan steps 3.3a–e). Up to four modes, switched at the top left:
// - Sale: categories on the left, the product grid with a search, the quick-sale cart on the
// right (SaleCart: Charge → payment, 3.3b).
// - Tables: the zones on the left and the table list (TablesView); a table opens with the
// product grid again and the table's order on the right (TablePanel).
// - Online (when online orders are on and the cashier handles them): new / in progress /
// finished on the left, the orders (OnlineView) and the picked one (OnlinePanel). A new
// order rings (and again every 30 s while one waits for an answer) and shows a notice in any
// mode; the mode's badge counts the orders waiting.
// - Receipts: today's paid orders (the cashier's shift or everyone's) and the picked one
// (ReceiptPanel) to give money back for some or all of its items (3.3e).
// A tap adds a product (or opens its choices when it has preferences to pick); the (i) button
// checks its price without adding it. Every price is the backend's.
import { useEffect, useMemo, useState } from 'react'
import { Globe, Info, LayoutGrid, Receipt, Search, ShoppingBag, X } from 'lucide-react'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { useCan, useModule } from '@xenia/access'
import { EmptyState, IconButton, Input, Spinner, useToast } from '@xenia/ui'
import { useLiveEvent } from '../../device/context'
import { playChime } from './chime'
import { addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, toLine, unitOf } from './logic/cart'
import { findOnline, ONLINE_LISTS } from './logic/online'
import { zoneCounts } from './logic/tables'
import OnlinePanel from './OnlinePanel'
import OnlineView from './OnlineView'
import ProductDialog from './ProductDialog'
import ReceiptPanel from './ReceiptPanel'
import ReceiptsView from './ReceiptsView'
import SaleCart from './SaleCart'
import TablePanel from './TablePanel'
import TablesView from './TablesView'
import { useMenu, useOnline, useReceipts, useTables } from './usePos'
const REMIND_MS = 30_000
export default function PosScreen() {
const { t } = useTranslation('terminal')
const { menu } = useMenu()
if (!menu) return <div className="absolute inset-0 flex items-center justify-center bg-canvas"><Spinner /></div>
return <Counter menu={menu} key={menu.settings.start_category_id ?? 'all'} t={t} />
}
function Counter({ menu, t }) {
const { language } = useLanguage()
const { formatMoney } = useFormat()
const [mode, setMode] = useState('sale') // sale | tables | online | receipts
const [tableId, setTableId] = useState(null) // the open table (tables mode)
const [zone, setZone] = useState(null)
const [category, setCategory] = useState(() => menu.settings.start_category_id ?? null)
const [query, setQuery] = useState('')
const [orderType, setOrderType] = useState(menu.settings.default_order_type)
const [saleCart, setSaleCart] = useState([])
const [tableCart, setTableCart] = useState([])
const [dialog, setDialog] = useState(null) // product
const tables = useTables()
const canDiscount = useCan('ordering.prices.modify')
const toast = useToast()
const onlineModule = useModule('connect_orders')
const handlesOnline = useCan('connect_orders.manage')
const onlineOn = onlineModule && handlesOnline
const online = useOnline(onlineOn)
const [onlineList, setOnlineList] = useState('incoming')
const [onlineId, setOnlineId] = useState(null)
const [now, setNow] = useState(() => Date.now())
const [chimes, setChimes] = useState(0)
const waiting = online.data?.incoming.length ?? 0
const [receiptScope, setReceiptScope] = useState('mine')
const [receiptId, setReceiptId] = useState(null)
const receipts = useReceipts(receiptScope, mode === 'receipts')
const ring = () => { playChime(); setChimes(c => c + 1) }
useLiveEvent('online_order_received', data => {
if (!onlineOn) return
ring()
if (mode !== 'online') toast.info(t('pos.online.arrived', { count: data?.count ?? 1 }))
})
// a reminder while an order waits for an answer; the waiting minutes move on too
useEffect(() => {
const id = setInterval(() => {
setNow(Date.now())
if (waiting > 0) { playChime(); setChimes(c => c + 1) }
}, REMIND_MS)
return () => clearInterval(id)
}, [waiting])
// a table that left the cashier's list (zone changed) shows the list again
const table = tableId != null ? tables.data?.tables.find(x => x.id === tableId) ?? null : null
const atTable = mode === 'tables' && table != null
const picking = mode === 'tables' && !atTable
const onlineOrder = findOnline(online.data, onlineId)
const setCart = atTable ? setTableCart : setSaleCart
const leaveTable = () => { setTableId(null); setTableCart([]) }
const byId = useMemo(() => new Map(menu.products.map(p => [p.id, p])), [menu.products])
const categories = useMemo(() => categoriesWithProducts(menu.categories, menu.products), [menu])
const shown = useMemo(() => (query.trim() ? searchProducts(menu.products, query) : productsIn(menu.products, category)),
[menu.products, query, category])
const counts = useMemo(() => zoneCounts(tables.data?.tables ?? []), [tables.data])
const tap = product => {
if (needsChoices(product)) { setDialog(product); return }
const unit = unitOf(product)
setCart(c => addLine(c, toLine(product, defaultSelection(product), unit ? unit.start : 1)))
}
return (
<div className="absolute inset-0 grid grid-cols-[13rem_1fr_24rem] bg-canvas text-ink" data-testid="pos-screen" data-chimes={chimes} lang={language}>
<nav className="border-r border-line bg-surface min-h-0 flex flex-col">
<div className={`p-2 grid gap-1 border-b border-line ${onlineOn ? 'grid-cols-2' : 'grid-cols-3'}`} role="tablist" aria-label={t('pos.mode.label')}>
<ModeButton active={mode === 'sale'} onClick={() => setMode('sale')} icon={ShoppingBag} testId="mode-sale">{t('pos.mode.sale')}</ModeButton>
<ModeButton active={mode === 'tables'} onClick={() => { setMode('tables'); leaveTable() }} icon={LayoutGrid} testId="mode-tables"
badge={counts.all.busy || null}>{t('pos.mode.tables')}</ModeButton>
{onlineOn && (
<ModeButton active={mode === 'online'} onClick={() => setMode('online')} icon={Globe} testId="mode-online"
badge={waiting || null} alert={waiting > 0}>{t('pos.mode.online')}</ModeButton>
)}
<ModeButton active={mode === 'receipts'} onClick={() => setMode('receipts')} icon={Receipt} testId="mode-receipts">{t('pos.mode.receipts')}</ModeButton>
</div>
<div className="flex-1 overflow-y-auto p-2 grid content-start gap-1"
data-testid={mode === 'online' ? 'online-lists' : mode === 'receipts' ? 'receipt-scopes' : picking ? 'pos-zones' : 'pos-categories'}>
{mode === 'receipts' ? (
['mine', 'all'].map(sc => (
<NavButton key={sc} active={receiptScope === sc} onClick={() => setReceiptScope(sc)} testId={`receipts-${sc}`}>
{t(`pos.receipts.scope.${sc}`)}
</NavButton>
))
) : mode === 'online' ? (
ONLINE_LISTS.map(list => (
<NavButton key={list} active={onlineList === list} onClick={() => setOnlineList(list)} testId={`online-list-${list}`}
tally={list === 'finished' ? null : online.data?.[list].length}>
{t(`pos.online.lists.${list}`)}
</NavButton>
))
) : picking ? (
<>
<NavButton active={zone == null} onClick={() => setZone(null)} count={counts.all}>{t('pos.tables.allZones')}</NavButton>
{(tables.data?.groups ?? []).map(g => (
<NavButton key={g.id} colour={g.color} active={zone === g.id} onClick={() => setZone(g.id)} count={counts[g.id]} testId={`zone-${g.id}`}>{g.name}</NavButton>
))}
</>
) : (
<>
<NavButton active={category == null && !query} onClick={() => { setCategory(null); setQuery('') }}>{t('pos.allProducts')}</NavButton>
{categories.map(c => (
<NavButton key={c.id} colour={c.color} active={category === c.id && !query} onClick={() => { setCategory(c.id); setQuery('') }} testId={`category-${c.id}`}>
{c.name}
</NavButton>
))}
</>
)}
</div>
</nav>
{mode === 'receipts' ? (
<>
<main className="flex flex-col min-h-0 min-w-0">
<ReceiptsView data={receipts.data} scope={receiptScope} picked={receiptId} onPick={setReceiptId} />
</main>
<ReceiptPanel orderId={receiptId} />
</>
) : mode === 'online' ? (
<>
<main className="flex flex-col min-h-0 min-w-0">
<OnlineView data={online.data} list={onlineList} picked={onlineId} onPick={setOnlineId} now={now} />
</main>
<OnlinePanel key={onlineOrder?.id ?? 'none'} order={onlineOrder}
onChanged={(result, move) => {
online.reload()
if (move?.list) setOnlineList(move.list)
if (move?.clear) setOnlineId(null)
if (result?.change > 0) toast.success(t('pos.done.toastChange', { change: formatMoney(result.change) }))
}} />
</>
) : picking ? (
<main className="col-span-2 flex flex-col min-h-0 min-w-0">
<TablesView data={tables.data} zone={zone} onPick={id => { setTableId(id); setTableCart([]) }} />
</main>
) : (
<>
<main className="flex flex-col min-h-0 min-w-0">
<div className="p-3 border-b border-line bg-surface flex items-center gap-2">
<div className="relative flex-1">
<Search size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3 pointer-events-none" />
<Input value={query} onChange={e => setQuery(e.target.value)} placeholder={t('pos.search')} className="pl-10" data-testid="pos-search" aria-label={t('pos.search')} />
</div>
{query && <IconButton label={t('pos.clearSearch')} onClick={() => setQuery('')}><X size={18} /></IconButton>}
</div>
<div className="flex-1 overflow-y-auto p-3">
{shown.length === 0 ? (
<EmptyState title={query ? t('pos.noResults', { query }) : t('pos.noProducts')} />
) : (
<div className="grid gap-3" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(9.5rem, 1fr))' }} data-testid="pos-grid">
{shown.map(p => <ProductCard key={p.id} product={p} onTap={() => tap(p)} onInfo={() => setDialog(p)} />)}
</div>
)}
</div>
</main>
{atTable
? <TablePanel key={table.id} table={table} cart={tableCart} setCart={setTableCart} byId={byId} canDiscount={canDiscount}
onBack={leaveTable} onTablesChanged={tables.reload} />
: <SaleCart cart={saleCart} setCart={setSaleCart} orderType={orderType} setOrderType={setOrderType} byId={byId} canDiscount={canDiscount} />}
</>
)}
{dialog && (
<ProductDialog product={dialog} orderType={atTable ? 'here' : orderType} onClose={() => setDialog(null)}
onAdd={line => setCart(c => addLine(c, line))} />
)}
</div>
)
}
function ModeButton({ active, onClick, icon: Icon, badge, alert, children, testId }) {
return (
<button type="button" role="tab" aria-selected={active} onClick={onClick} data-testid={testId} data-badge={badge ?? 0}
className={`relative min-h-[var(--x-control-lg)] rounded-control flex flex-col items-center justify-center gap-0.5 text-label font-semibold transition-colors duration-fast
${active ? 'bg-accent text-accent-fg' : 'bg-surface-2 text-ink-2 hover:bg-surface-3'}`}>
<Icon size={18} aria-hidden="true" />{children}
{badge ? <span className={`absolute top-1 right-1 min-w-5 h-5 px-1 rounded-full bg-warning text-warning-fg text-caption font-bold flex items-center justify-center ${alert ? 'animate-pulse' : ''}`}>{badge}</span> : null}
</button>
)
}
function NavButton({ active, colour, onClick, children, testId, count, tally }) {
return (
<button type="button" onClick={onClick} data-testid={testId} aria-pressed={active}
className={`min-h-[var(--x-control-lg)] px-3 rounded-control text-left text-body font-medium flex items-center gap-2 transition-colors duration-fast
${active ? 'bg-accent-soft text-accent-ink' : 'text-ink hover:bg-surface-2'}`}>
{colour && <span className="size-2.5 rounded-full shrink-0" style={{ background: colour }} aria-hidden="true" />}
<span className="flex-1 truncate">{children}</span>
{count && <span className="text-caption text-ink-3">{count.busy}/{count.total}</span>}
{tally != null && <span className="text-caption text-ink-3">{tally}</span>}
</button>
)
}
function ProductCard({ product, onTap, onInfo }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const unit = unitOf(product)
return (
<div className="relative bg-surface border border-line rounded-card shadow-raised overflow-hidden flex flex-col" data-testid="pos-product" data-product={product.id}>
<button type="button" onClick={onTap} className="flex-1 flex flex-col text-left active:scale-[0.98] transition-transform duration-fast">
{product.image_url
? <img src={product.image_url} alt="" loading="lazy" className="w-full aspect-[4/3] object-cover bg-surface-2" />
: <span className="w-full aspect-[4/3] bg-surface-2 flex items-center justify-center text-heading text-ink-3" aria-hidden="true">{product.name.slice(0, 1)}</span>}
<span className="p-2 grid gap-0.5">
<span className="text-body font-medium text-ink line-clamp-2">{product.name}</span>
<span className="text-label text-ink-2">{formatMoney(product.price)}{unit ? ` / ${unit.label}` : ''}</span>
</span>
</button>
<IconButton label={t('pos.checkPrice', { name: product.name })} size="sm" variant="secondary" onClick={onInfo}
className="absolute top-1.5 right-1.5" data-testid="product-info">
<Info size={16} />
</IconButton>
</div>
)
}