feat(manager,waiter): money and weights typed with a comma or a dot everywhere

Owner 2026-11-23 (plan 6F.2): new DecimalInput / MoneyInput in @xenia/ui (keeps what is typed,
reports a number, null when empty, NaN when not a number) on parseNumber. The waiter app's starting
cash, weighed quantity and typed prices were type=number + parseFloat (a Greek keypad's comma was
dropped: 12,50 became 12 or nothing); now text fields read with parseNumber, and a wrong starting
cash shows a message. The manager's price rules, deals and order-total condition use the new
fields; every Number(x.replace(',', '.')) now reads through parseNumber (1.234,50 too). Guard test
packages/i18n/tests/typed-numbers.test.mjs refuses parseFloat, .replace(',', '.') and decimal
type=number fields in the apps. e2e: shift close with 20,50, waiter starting cash 25,50.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 07:08:54 +02:00
co-authored by Claude Opus 5.5
parent e708202f3a
commit e3f4f3eeee
27 changed files with 216 additions and 46 deletions
+1
View File
@@ -53,6 +53,7 @@ Every page is on `<Page>` except Inventory → Stock (a placeholder). Two-column
| A small panel under a button | `Popover` (`open`, `anchor` = the button's ref, `onClose`) | a colour picker, an "Add…" menu. Drawn over everything (portal), flips above, stays inside the window: **never an `absolute` panel inside a section** (it is clipped and makes the section scroll) |
| A colour (a venue's: data) | `ColourField` (`auto`, `opacity`, `presets`) | a field with its swatch and code; its panel (over the page) has 12 ready colours, the picker, the opacity (`#rrggbbaa`) and the code. `auto` = a first choice that leaves it to something else ("As the slide"). **Never** a bare `<input type="color">` |
| An icon from a set | `IconPicker` (`icons` = { key: component }) | a field showing the icon; a grid of the set over the page, "No icon" first |
| Money, a weight, any number with decimals | `MoneyInput` (€, cents), `DecimalInput` (`decimals`, `allowNegative`, `suffix`) | typed with a comma **or** a dot ("12,50", "1.234,50"); reports a number, `null` when empty, `NaN` when it isn't a number (show the error). **Never** `type="number"` with a decimal step, `parseFloat` or `.replace(',', '.')`: they drop the comma a Greek keypad types (6F.2; guarded by `packages/i18n/tests/typed-numbers.test.mjs`). Fields kept as text read it with `parseNumber` |
| A whole number (seconds, counts) | `NumberInput` (`min`, `max`, `suffix`) | − / + on its sides, as tall as an input; it may be emptied while typing (`onChange(null)`): the form shows the error and blocks saving. **Never** clamp on every key (the user can't clear the field). With a `min` below 0 a minus may be typed in front |
| A note in a box (what works, a caution) | `Notice` (`tone`, `title`, `icon`, `items` = [{ tone, label, text }]) | a tinted box with a bar on its left; `items` are points with a tone dot and a bold label. **Never** a local `bg-info-soft` paragraph rebuilt per page |
| A slider with its value | `Slider` (`suffix`) | framed and as tall as the fields beside it; the value sits as close to it as the frame's padding. **Never** a bare `<input type="range">` |
@@ -2,11 +2,12 @@
// evaluated by the backend's engine (local_backend/services/fees.py, the same file the cloud
// runs); this file only turns forms into request bodies and rules into readable lines.
// Pure: unit-tested in Node (tests/fees.test.mjs).
import { parseNumber } from '@xenia/i18n/number'
export const ACTIONS = ['set', 'add', 'percent', 'free', 'minimum']
export const DAYS = [0, 1, 2, 3, 4, 5, 6] // Monday = 0
const num = v => (v === '' || v == null ? null : Number(String(v).replace(',', '.')))
const num = v => (v === '' || v == null ? null : (parseNumber(String(v)) ?? NaN))
/** Postcodes typed with commas, semicolons or new lines → a tidy list without duplicates. */
export function parsePostcodes(text) {
@@ -8,7 +8,7 @@ import toast from 'react-hot-toast'
import { Ban, CreditCard, Percent, Printer, Receipt } from 'lucide-react'
import { useCan, useModule } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, cx } from '@xenia/ui'
import client from '../../api/client'
import { Pill } from '../overview/parts'
@@ -123,7 +123,7 @@ function DiscountDialog({ orderId, itemIds, amount, onClose, onDone }) {
const { formatMoney } = useFormat()
const [pct, setPct] = useState('10')
const [note, setNote] = useState('')
const value = Number(String(pct).replace(',', '.'))
const value = parseNumber(String(pct)) ?? NaN
const ok = value > 0 && value <= 100
const apply = useMutation({
mutationFn: () => client.post(`/api/orders/${orderId}/items/discount`, { item_ids: itemIds, discount_percent: value, note: note.trim() || null }),
@@ -9,7 +9,7 @@ import toast from 'react-hot-toast'
import { Plus } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, Select, Spinner, Switch } from '@xenia/ui'
import { Button, DecimalInput, Dialog, EmptyState, Field, Input, Select, Spinner, Switch } from '@xenia/ui'
import { useLiveQuery } from '../../live/useLiveQuery'
import * as api from './pricingApi'
import { ColourPicker, ConditionList, Missing, PickSeveral, RuleCard, Segmented, TabHead, TagPicker, TargetList } from './PricingParts'
@@ -145,8 +145,8 @@ function DealDialog({ deal, catalog, rules, busy, onClose, onSave }) {
)}
{['set_price', 'add_amount', 'add_percent'].includes(a) && (
<Field label={t(`pricing.actions.valueLabel.${a === 'set_price' ? 'set' : a}`)} hint={a !== 'set_price' ? t('pricing.actions.minusHint') : undefined}>
<Input type="number" step={a === 'add_percent' ? 1 : 0.1} className="w-36" value={Number.isFinite(f.action_value) ? f.action_value : ''}
onChange={e => set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} />
<DecimalInput allowNegative decimals={2} suffix={a === 'add_percent' ? '%' : '€'} className="w-36" value={f.action_value}
onChange={v => set('action_value', v ?? NaN)} />
</Field>
)}
<ColourPicker value={f.color} onChange={v => set('color', v)} label={t('pricing.colour')} />
@@ -12,7 +12,7 @@ import toast from 'react-hot-toast'
import { Layers, Plus } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui'
import { Button, DecimalInput, Dialog, EmptyState, Field, InfoTip, Input, Select, Spinner, Switch } from '@xenia/ui'
import { useLiveQuery } from '../../live/useLiveQuery'
import * as api from './pricingApi'
import { ColourPicker, ConditionList, Missing, RuleCard, Segmented, TabHead, TargetList } from './PricingParts'
@@ -147,8 +147,8 @@ function RuleDialog({ rule, catalog, busy, onClose, onSave }) {
options={MODIFIER_ACTIONS.map(v => ({ value: v, label: t(`pricing.actions.${v}`) }))} />
<div className="grid sm:grid-cols-2 gap-3">
<Field label={t(`pricing.actions.valueLabel.${f.action_type}`)} hint={f.action_type !== 'set' ? t('pricing.actions.minusHint') : undefined}>
<Input type="number" step={f.action_type === 'add_percent' ? 1 : 0.1} value={Number.isFinite(f.action_value) ? f.action_value : ''}
onChange={e => set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} data-testid="pricing-rule-value" />
<DecimalInput allowNegative decimals={2} suffix={f.action_type === 'add_percent' ? '%' : '€'} value={f.action_value}
onChange={v => set('action_value', v ?? NaN)} data-testid="pricing-rule-value" />
</Field>
{f.action_type === 'add_percent' && (
<Field label={t('pricing.rules.rounding')}>
@@ -4,7 +4,7 @@ import { useState } from 'react'
import { ArrowDown, ArrowUp, Check, Pencil, Plus, Power, Trash2, X } from 'lucide-react'
import { SALES_POINTS, normalizeSalesPoints } from '@xenia/access'
import { latin, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dropdown, IconButton, Input, Select, cx } from '@xenia/ui'
import { Button, Dropdown, IconButton, Input, MoneyInput, Select, cx } from '@xenia/ui'
import { COLOURS } from './useCatalog'
import { OLD_PLACEHOLDERS, WEEKDAYS, blankCondition, conditionComplete, toggleIn } from './pricingLogic'
@@ -202,7 +202,13 @@ function ConditionFields({ cond, onChange, catalog }) {
case 'specific_date': return <DateList value={p.dates ?? []} onChange={v => set('dates', v)} />
case 'day_of_week': return <DayPicker value={p.days ?? []} onChange={v => set('days', v)} />
case 'min_item_quantity': return <label className="flex items-center gap-2 text-label text-ink-2">{num('min', 1, 1)}{t('pricing.condition.ofTheDish')}</label>
case 'min_order_value': return <label className="flex items-center gap-2 text-label text-ink-2">{num('min', 0, 0.5)}{t('pricing.condition.orderTotal')}</label>
case 'min_order_value': return (
<label className="flex items-center gap-2 text-label text-ink-2">
<MoneyInput size="sm" className="w-32" value={p.min ?? null} aria-label={t('pricing.condition.fields.min_order_value')}
onChange={v => set('min', Number.isFinite(v) ? v : null)} />
{t('pricing.condition.orderTotal')}
</label>
)
case 'min_category_qty': return (
<div className="flex flex-wrap items-center gap-2">
{num('min', 1, 1)}
@@ -2,6 +2,7 @@
// (modifier) and a deal, what they send to the server, what's missing before they can be saved,
// and their one-line summaries. Tested in tests/pricing-logic.test.mjs.
// The server's engine: local_backend/services/pricing.py (conditions AND-ed, targets OR-ed).
import { parseNumber } from '@xenia/i18n/number'
export const WEEKDAYS = [0, 1, 2, 3, 4, 5, 6] // Monday = 0, as the server counts
@@ -226,9 +227,9 @@ export const COUNT_LIMITS = new Set(['max_items_per_shift', 'max_items_per_workd
/** A limit typed in a box: '' = no limit; a comma works as the decimal point. null when it isn't a number ≥ 0. */
export function parseLimit(text, count = false) {
const s = String(text ?? '').trim().replace(',', '.')
const s = String(text ?? '').trim()
if (s === '') return { ok: true, value: null }
const v = Number(s)
const v = parseNumber(s) ?? NaN
if (!Number.isFinite(v) || v < 0 || (count && !Number.isInteger(v))) return { ok: false, value: null }
return { ok: true, value: v }
}
@@ -7,7 +7,7 @@ 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 { parseNumber, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Page, Pane, Spinner } from '@xenia/ui'
import { Package } from 'lucide-react'
import client from '../../api/client'
@@ -23,7 +23,7 @@ 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(',', '.')))
const number = v => (v === '' ? null : (parseNumber(String(v)) ?? NaN))
export default function ProductsPage() {
const { t } = useTranslation('manager')
@@ -4,7 +4,7 @@
// with a price: printed in its own SERVICE section and counted in the takings.
import { useState } from 'react'
import { DEFAULT_LANGUAGE } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { parseNumber, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field } from '@xenia/ui'
import { PrepZonesField } from './InfoTabs'
import { LanguagePicker, TrInput } from './LanguageFields'
@@ -19,7 +19,7 @@ export default function ServiceItemDialog({ product, prepZones, saving, onSave,
const [lang, setLang] = useState(DEFAULT_LANGUAGE)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const isNew = !product.id
const paid = Number(String(form.base_price ?? '').replace(',', '.')) > 0
const paid = (parseNumber(String(form.base_price ?? '')) ?? 0) > 0
return (
<EditLang.Provider value={editLangOf(lang, venue)}>
<Dialog open size="md" onClose={onClose}
@@ -7,12 +7,13 @@
// language picker picks which language the fields edit; "Default" is the venue's language.
import { SALES_POINTS } from '@xenia/access/salesPoints'
import { MENU_LANGUAGES, shownText } from '@xenia/access/menuLanguages'
import { parseNumber } from '@xenia/i18n/number'
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 num = v => (v === '' || v == null ? 0 : parseNumber(String(v)) || 0)
const sub = s => ({ name: s.name ?? '', tr: { ...(s.translations ?? {}) }, extra_cost: s.extra_cost ?? 0, is_default: !!s.is_default, allow_multiple: !!s.allow_multiple, is_compact: !!s.is_compact })
const field = (tr, k) => Object.fromEntries(Object.entries(tr ?? {}).filter(([, v]) => v?.[k]).map(([l, v]) => [l, v[k]]))
@@ -3,7 +3,7 @@
// language picked at the top of the editor.
import { useState } from 'react'
import { ChevronDown, ChevronUp, Heart, Minus, Pencil, Plus, Trash2 } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { parseNumber, useTranslation } from '@xenia/i18n'
import { Button, FilterChip, IconButton, cx } from '@xenia/ui'
import { TrInput } from './LanguageFields'
import { useEditLang } from './editLang'
@@ -12,7 +12,7 @@ import { labelIn } from './formLogic'
/** A price with − / + of 0.10 (negative allowed for choices that lower the price). */
export function PriceInput({ value, onChange, allowNegative = false, size = 'md', className, label, ...rest }) {
const { t } = useTranslation('manager')
const n = Number(String(value ?? '').replace(',', '.')) || 0
const n = parseNumber(String(value ?? '')) || 0
const step = d => {
const next = Math.round((n + d) * 100) / 100
onChange(allowNegative ? next : Math.max(0, next))
@@ -1,4 +1,5 @@
// The staff page as plain data (plan step 6.11), tested in tests/staff.test.mjs.
import { parseNumber } from '@xenia/i18n/number'
/** The roles in the order the page lists them (backend roles.py); names are i18n `roles.*`. */
export const ROLES = ['owner', 'store_manager', 'staff_manager', 'chef', 'assistant_chef', 'barista', 'barman', 'waiter', 'assistant_waiter', 'custom']
@@ -58,8 +59,9 @@ export function staffProblems(form, isNew) {
if (!form.full_name.trim()) out.push('full_name')
if (!form.nickname.trim()) out.push('nickname')
if (!/^[^\s]{2,}$/.test(form.username.trim())) out.push('username')
const rate = String(form.hourly_rate).trim().replace(',', '.')
if (rate && !(Number(rate) >= 0)) out.push('hourly_rate')
const rate = String(form.hourly_rate ?? '').trim()
const rateValue = rate ? parseNumber(rate) : null
if (rate && !(rateValue != null && rateValue >= 0)) out.push('hourly_rate')
if (isNew && !validPin(form.pin)) out.push('pin')
if (isNew && form.password && !validPassword(form.password)) out.push('password')
return out
@@ -68,11 +70,11 @@ export function staffProblems(form, isNew) {
/** POST /api/waiters/ (new) or PUT /api/waiters/{id} (edit). */
export function staffBody(form, isNew) {
const text = v => (v ?? '').trim() || null
const rate = String(form.hourly_rate).trim().replace(',', '.')
const rate = String(form.hourly_rate ?? '').trim()
const body = {
full_name: form.full_name.trim(), nickname: form.nickname.trim(), username: form.username.trim(), role: form.role,
mobile_phone: text(form.mobile_phone), email: text(form.email), note: text(form.note),
hourly_rate: rate ? Number(rate) : null, language: form.language || '',
hourly_rate: rate ? parseNumber(rate, { decimals: 2 }) : null, language: form.language || '',
}
if (isNew) {
body.pin = form.pin
+1
View File
@@ -9729,6 +9729,7 @@
"name": "@xenia/ui",
"version": "0.0.0",
"peerDependencies": {
"@xenia/i18n": "*",
"qrcode.react": "^4.2.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
+2 -1
View File
@@ -29,7 +29,8 @@
"startQuestion": "Θέλεις να ξεκινήσεις τη βάρδια σου;",
"startingCash": "Αρχικά μετρητά (προαιρετικό)",
"starting": "Εκκίνηση…",
"startShift": "Έναρξη Βάρδιας"
"startShift": "Έναρξη Βάρδιας",
"badAmount": "Γράψτε ένα ποσό, π.χ. 50 ή 50,00."
},
"nav": {
"tables": "Τραπέζια",
+2 -1
View File
@@ -29,7 +29,8 @@
"startQuestion": "Start your shift?",
"startingCash": "Starting cash (optional)",
"starting": "Starting…",
"startShift": "Start shift"
"startShift": "Start shift",
"badAmount": "Type an amount, e.g. 50 or 50,00."
},
"nav": {
"tables": "Tables",
@@ -0,0 +1,46 @@
// Guard (plan 6F.2, owner 2026-11-23): numbers people type are read with parseNumber (a comma or
// a dot for the decimals, "1.234,50" too), never with parseFloat / Number(x.replace(',', '.')),
// and a field for money or a weight is never <input type="number"> with a decimal step: a phone's
// Greek keypad types a comma, which such a field silently drops ("12,50" became 12 or nothing).
// Use DecimalInput / MoneyInput (@xenia/ui) or a text field with inputMode="decimal" + parseNumber.
import assert from 'node:assert/strict'
import { readdirSync, readFileSync, statSync } from 'node:fs'
import path from 'node:path'
import { test } from 'node:test'
import { fileURLToPath } from 'node:url'
const CS = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..')
const ROOTS = ['manager_dashboard/src', 'waiter_pwa/src', 'terminal/src', 'packages/ui/src']
// reading CSS lengths, not typed numbers (the older TVs' layer)
const SKIP = new Set(['terminal/src/compat.js'])
function* files(dir) {
for (const name of readdirSync(dir)) {
const p = path.join(dir, name)
if (statSync(p).isDirectory()) yield* files(p)
else if (/\.(jsx?|mjs)$/.test(name)) yield p
}
}
const RULES = [
[/\bparseFloat\(/, 'parseFloat'],
[/\.replace\(\s*['"],['"]\s*,\s*['"]\.['"]\s*\)/, ".replace(',', '.')"],
[/type=["']number["'][^>]*\bstep=(?:["']0?\.\d|\{[^}]*\b0?\.\d)/, 'type="number" with a decimal step'],
]
test('typed numbers are read with parseNumber, never parseFloat or a type="number" decimal field', () => {
const bad = []
for (const root of ROOTS) {
for (const file of files(path.join(CS, root))) {
const rel = path.relative(CS, file).replace(/\\/g, '/')
if (SKIP.has(rel)) continue
const text = readFileSync(file, 'utf8')
// a JSX element can span lines: look at each tag as one piece
const flat = text.replace(/<input\b[^>]*>/gs, m => m.replace(/\s+/g, ' '))
flat.split('\n').forEach((line, i) => {
for (const [re, what] of RULES) if (re.test(line)) bad.push(`${rel}:${i + 1} ${what}`)
})
}
}
assert.deepEqual(bad, [])
})
+1
View File
@@ -20,6 +20,7 @@
"test": "node --test \"tests/*.test.mjs\""
},
"peerDependencies": {
"@xenia/i18n": "*",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"qrcode.react": "^4.2.0"
+3
View File
@@ -501,6 +501,9 @@
font: inherit; font-size: var(--x-text-body); text-align: center; font-variant-numeric: tabular-nums;
}
.x-number__suffix { align-self: center; padding-right: var(--x-space-1); color: var(--x-ink-3); font-size: var(--x-text-label); }
/* DecimalInput / MoneyInput (6F.2): the number frame without − / +, text from the left */
.x-decimal__input { text-align: left; padding: 0 var(--x-space-3); }
.x-decimal__suffix { padding-right: var(--x-space-3); }
/* ── Slider (2026-11-21): framed like a field, its value beside it ──────────────── */
.x-slider {
@@ -0,0 +1,50 @@
import { useEffect, useRef, useState } from 'react'
import { cx } from '../internal/cx.js'
import { readDecimal } from './decimal.js'
const shown = v => (v == null || Number.isNaN(v) ? '' : String(v))
/**
* A number with decimals typed with a comma or a dot (owner 2026-11-23, plan 6F.2): "12,50",
* "12.50" and "1.234,50" all work, on every keyboard (a phone's Greek keypad has only a comma).
* The field keeps what is being typed ("12," on the way to "12,50") and reports a number:
* onChange(number) a number onChange(null) empty onChange(NaN) not a number (show an error)
* Never `type="number"` + parseFloat for money or quantities: those read "12,50" as 12 or nothing.
*
* <DecimalInput value={kg} onChange={setKg} decimals={3} suffix="kg" />
* decimals: rounds what is reported; allowNegative (default false); suffix: shown at the end.
*/
export function DecimalInput({ value, onChange, decimals, allowNegative = false, suffix, size = 'md', invalid = false, disabled = false, className, inputClassName, ...rest }) {
const [text, setText] = useState(() => shown(value))
const [focus, setFocus] = useState(false)
const reported = useRef(value)
// a value set from outside (a reset, − / + elsewhere) replaces the text; our own report doesn't
useEffect(() => {
if (Object.is(value, reported.current)) return
reported.current = value
setText(shown(value))
}, [value])
const bad = invalid || Number.isNaN(value)
return (
<span className={cx('x-number', 'x-decimal', `x-number--${size}`, bad && 'x-number--invalid', focus && 'x-number--focus', disabled && 'x-number--disabled', className)}>
<input type="text" inputMode="decimal" autoComplete="off" className={cx('x-number__input', 'x-decimal__input', inputClassName)} value={text} disabled={disabled}
aria-invalid={bad || undefined}
onChange={e => {
const s = e.target.value
setText(s)
const out = readDecimal(s, { decimals, allowNegative })
reported.current = out
onChange?.(out, s)
}}
onFocus={e => { setFocus(true); e.target.select() }}
onBlur={() => setFocus(false)}
{...rest} />
{suffix && <span className="x-number__suffix x-decimal__suffix" aria-hidden="true">{suffix}</span>}
</span>
)
}
/** An amount of money: DecimalInput with cents and "€" (6F.2). */
export function MoneyInput({ suffix = '€', ...rest }) {
return <DecimalInput decimals={2} suffix={suffix} {...rest} />
}
+9
View File
@@ -0,0 +1,9 @@
import { parseNumber } from '@xenia/i18n/number'
/** What a DecimalInput reports for the typed text (6F.2): a number, null (empty) or NaN (not a number). */
export function readDecimal(text, { decimals, allowNegative = false } = {}) {
const s = String(text ?? '')
if (s.trim() === '') return null
const n = parseNumber(s, { decimals, allowNegative })
return n == null ? NaN : n
}
+2
View File
@@ -18,6 +18,8 @@ export { ToastProvider } from './components/Toast.jsx'
export { useToast } from './components/toastContext.js'
export { PinPad } from './components/PinPad.jsx'
export { INFOTIP_HOVER_MS, InfoTip } from './components/InfoTip.jsx'
export { DecimalInput, MoneyInput } from './components/DecimalInput.jsx'
export { readDecimal } from './components/decimal.js'
export { EmptyState } from './components/EmptyState.jsx'
export { Spinner } from './components/Spinner.jsx'
export { Field, Input, Textarea, Select } from './components/Field.jsx'
+21
View File
@@ -0,0 +1,21 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { readDecimal } from '../src/components/decimal.js'
test('money typed with a comma or a dot (6F.2)', () => {
assert.equal(readDecimal('12,50', { decimals: 2 }), 12.5)
assert.equal(readDecimal('12.50', { decimals: 2 }), 12.5)
assert.equal(readDecimal('1.234,50', { decimals: 2 }), 1234.5)
assert.equal(readDecimal('0,05', { decimals: 2 }), 0.05)
assert.equal(readDecimal('€ 7,3', { decimals: 2 }), 7.3)
assert.equal(readDecimal('0,125', { decimals: 3 }), 0.125)
})
test('empty is null, nonsense is NaN, negatives only when allowed', () => {
assert.equal(readDecimal(''), null)
assert.equal(readDecimal(' '), null)
assert.ok(Number.isNaN(readDecimal('abc')))
assert.ok(Number.isNaN(readDecimal('12,5,0')))
assert.ok(Number.isNaN(readDecimal('-2,5')))
assert.equal(readDecimal('-2,5', { allowNegative: true }), -2.5)
})
+5 -2
View File
@@ -955,8 +955,11 @@ try {
await page.keyboard.press('Escape')
await ovRow.getByTestId('shift-end').click()
await page.getByTestId('shift-next').click()
await page.getByTestId('shift-counted').fill('18')
r.check(`${ov} ending it: €18 handed over shows "short"`, await page.getByTestId('shift-check').getAttribute('data-state').catch(() => '') === 'short')
// a comma or a dot for the cents (6F.2): "20,50" is exactly the expected €20.50, "18.5" is short
await page.getByTestId('shift-counted').fill('20,50')
r.check(`${ov} ending it: "20,50" typed with a comma is exactly what's expected`, await page.getByTestId('shift-check').getAttribute('data-state').catch(() => '') === 'even')
await page.getByTestId('shift-counted').fill('18.5')
r.check(`${ov} ending it: €18.5 handed over shows "short"`, await page.getByTestId('shift-check').getAttribute('data-state').catch(() => '') === 'short')
await page.screenshot({ path: path.join(OUT, 'manager-overview-shift.png') })
await page.getByTestId('shift-end-confirm').click()
await ovRow.waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
+16 -2
View File
@@ -54,6 +54,10 @@ try {
await api('POST', '/api/business-day/open', { token: boss, body: {} }).catch(() => {})
const waiters = await api('GET', '/api/auth/waiters')
const maria = waiters.find(w => (w.full_name || '').includes('Κωνσταντίνου'))
// no shift left from the demo data: the phone then shows the start-shift gate (6F.2 checks it)
for (const sh of (await api('GET', '/api/shifts/?active_only=true', { token: boss })).shifts.filter(x => x.waiter_id === maria?.id)) {
await api('POST', `/api/shifts/manager/end/${sh.id}`, { token: boss, body: {} }).catch(() => {})
}
// ── login-by-id is gone ────────────────────────────────────────────────────
const old = await api('POST', '/api/auth/login-by-id', { body: { waiter_id: maria?.id, pin: '3302' }, raw: true })
@@ -77,9 +81,19 @@ try {
const sessions = await api('GET', '/api/auth/sessions', { token: boss })
r.check('the session is a "waiter" session', sessions.some(s => s.username === 'demo_maria' && s.client === 'waiter'), JSON.stringify(sessions.map(s => [s.username, s.client])))
// start the shift on the phone (the gate after sign-in)
// start the shift on the phone (the gate after sign-in), the starting cash typed with a comma (6F.2)
const cashBox = a.getByPlaceholder('0,00')
await cashBox.fill('abc', { timeout: 10_000 }).catch(() => {})
await a.getByRole('button', { name: /Start shift/ }).click({ timeout: 10_000 }).catch(() => {})
await a.waitForURL(u => u.pathname.startsWith('/tables'), { timeout: 10_000 }).catch(() => {})
await sleep(500)
r.check('starting cash that is not a number: a message, the gate stays, no shift', await cashBox.isVisible()
&& (await a.getByText('Type an amount').count()) > 0
&& !(await api('GET', '/api/shifts/?active_only=true', { token: boss })).shifts.some(x => x.waiter_id === maria?.id))
await cashBox.fill('25,50').catch(() => {})
await a.getByRole('button', { name: /Start shift/ }).click({ timeout: 10_000 }).catch(() => {})
await cashBox.waitFor({ state: 'detached', timeout: 10_000 }).catch(() => {})
const started = (await api('GET', '/api/shifts/?active_only=true', { token: boss })).shifts.find(x => x.waiter_id === maria?.id)
r.check('starting cash "25,50" is kept as €25.50', started?.starting_cash === 25.5, JSON.stringify(started?.starting_cash))
await sleep(1500)
// ── One session per waiter (refuse_new) ────────────────────────────────────
+7 -4
View File
@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'
import { BrowserRouter, Routes, Route, Navigate, Outlet, useNavigate } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { AccessProvider, useAccess, useCan, useModule } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { parseNumber, useTranslation } from '@xenia/i18n'
import { i18n } from './i18n'
import useAuthStore from './store/authStore'
import useShiftStore from './store/shiftStore'
@@ -120,10 +120,13 @@ function StartShiftScreen({ username, onStart, onLogout }) {
const [error, setError] = useState(null)
async function handleStart() {
// a comma or a dot for the cents (6F.2): a Greek keypad only has the comma
const amount = startingCash.trim() === '' ? null : parseNumber(startingCash, { decimals: 2, allowNegative: false })
if (startingCash.trim() !== '' && amount == null) { setError(t('gate.badAmount')); return }
setStarting(true)
setError(null)
try {
await onStart(startingCash ? parseFloat(startingCash) : null)
await onStart(amount)
} catch (e) {
setError(apiError(e, t('gate.startFailed')))
setStarting(false)
@@ -146,9 +149,9 @@ function StartShiftScreen({ username, onStart, onLogout }) {
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ color: 'var(--muted)', fontWeight: 700 }}>€</span>
<input
type="number" step="0.01" min="0" placeholder="0.00"
type="text" inputMode="decimal" autoComplete="off" placeholder="0,00"
value={startingCash}
onChange={e => setStartingCash(e.target.value)}
onChange={e => { setStartingCash(e.target.value); setError(null) }}
onKeyDown={e => e.key === 'Enter' && handleStart()}
style={{
flex: 1, background: 'var(--bg3)', border: '1px solid var(--border)',
+9 -7
View File
@@ -3,7 +3,7 @@ import { useCan } from '@xenia/access'
import useWaiterFavoritesStore from '../store/waiterFavoritesStore'
import { assetUrl } from '../config/server'
import { money } from '../i18n'
import { useTranslation } from '@xenia/i18n'
import { parseNumber, useTranslation } from '@xenia/i18n'
// ── Helpers ──────────────────────────────────────────────────────────────────
@@ -723,13 +723,14 @@ function QuantityTab({ unitCfg, qty, setQty }) {
{editingQty ? (
<input
ref={inputRef}
type="number"
type="text"
inputMode="decimal"
autoComplete="off"
value={qtyInput}
onChange={e => setQtyInput(e.target.value)}
onBlur={() => {
const v = parseFloat(qtyInput)
if (!isNaN(v)) setQty(clamp(v))
const v = parseNumber(qtyInput, { decimals: 3, allowNegative: false })
if (v != null) setQty(clamp(v))
setEditingQty(false)
}}
onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }}
@@ -830,8 +831,8 @@ function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj }) {
}
function commitInput() {
const v = parseFloat(rawInput.replace(',', '.'))
if (!isNaN(v) && v >= 0.01) {
const v = parseNumber(rawInput, { decimals: 2, allowNegative: false })
if (v != null && v >= 0.01) {
setPriceAdj(Math.round((v - basePrice) * 100) / 100)
}
setEditing(false)
@@ -853,8 +854,9 @@ function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj }) {
{editing ? (
<input
ref={inputRef}
type="number"
type="text"
inputMode="decimal"
autoComplete="off"
value={rawInput}
onChange={e => setRawInput(e.target.value)}
onBlur={commitInput}
+6 -5
View File
@@ -15,7 +15,7 @@ import { queueOfflineSplit, queueOfflinePayment as queueOfflinePaymentOp } from
import { TransferIcon, MergeIcon, FlagsIcon, WaiterIcon, PrintIcon } from '../components/Icons'
import usePaymentSettingsStore from '../store/paymentSettingsStore'
import useTableViewStore from '../store/tableViewStore'
import { useTranslation } from '@xenia/i18n'
import { parseNumber, useTranslation } from '@xenia/i18n'
import { fade } from '../logic/colour'
import SeatsHint from '../components/SeatsHint'
@@ -143,8 +143,8 @@ function PriceAdjustModal({ item, onConfirm, onClose }) {
}
function commitEdit() {
const parsed = parseFloat(rawInput.replace(',', '.'))
if (!isNaN(parsed)) {
const parsed = parseNumber(rawInput, { decimals: 2, allowNegative: false })
if (parsed != null) {
setAdj(Math.round((parsed - basePrice) * 100) / 100)
}
setEditing(false)
@@ -166,8 +166,9 @@ function PriceAdjustModal({ item, onConfirm, onClose }) {
{editing ? (
<input
ref={inputRef}
type="number"
step="0.01"
type="text"
inputMode="decimal"
autoComplete="off"
value={rawInput}
onChange={e => setRawInput(e.target.value)}
onBlur={commitEdit}