diff --git a/docs/DESIGN.md b/docs/DESIGN.md index f9ce538..bf990b0 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -53,6 +53,7 @@ Every page is on `` 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 `` | | 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 `` | diff --git a/manager_dashboard/src/pages/online/feesLogic.js b/manager_dashboard/src/pages/online/feesLogic.js index d8787c6..6cc5d3b 100644 --- a/manager_dashboard/src/pages/online/feesLogic.js +++ b/manager_dashboard/src/pages/online/feesLogic.js @@ -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) { diff --git a/manager_dashboard/src/pages/orders/OrderLines.jsx b/manager_dashboard/src/pages/orders/OrderLines.jsx index 0af11e9..7a84bda 100644 --- a/manager_dashboard/src/pages/orders/OrderLines.jsx +++ b/manager_dashboard/src/pages/orders/OrderLines.jsx @@ -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 }), diff --git a/manager_dashboard/src/pages/pricing/DealsTab.jsx b/manager_dashboard/src/pages/pricing/DealsTab.jsx index 4e84ab8..d305ce5 100644 --- a/manager_dashboard/src/pages/pricing/DealsTab.jsx +++ b/manager_dashboard/src/pages/pricing/DealsTab.jsx @@ -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) && ( - set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} /> + set('action_value', v ?? NaN)} /> )} set('color', v)} label={t('pricing.colour')} /> diff --git a/manager_dashboard/src/pages/pricing/ModifiersTab.jsx b/manager_dashboard/src/pages/pricing/ModifiersTab.jsx index d6147a6..e432b1b 100644 --- a/manager_dashboard/src/pages/pricing/ModifiersTab.jsx +++ b/manager_dashboard/src/pages/pricing/ModifiersTab.jsx @@ -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}`) }))} />
- set('action_value', e.target.value === '' ? NaN : Number(e.target.value))} data-testid="pricing-rule-value" /> + set('action_value', v ?? NaN)} data-testid="pricing-rule-value" /> {f.action_type === 'add_percent' && ( diff --git a/manager_dashboard/src/pages/pricing/PricingParts.jsx b/manager_dashboard/src/pages/pricing/PricingParts.jsx index 5414375..e340a95 100644 --- a/manager_dashboard/src/pages/pricing/PricingParts.jsx +++ b/manager_dashboard/src/pages/pricing/PricingParts.jsx @@ -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 set('dates', v)} /> case 'day_of_week': return set('days', v)} /> case 'min_item_quantity': return - case 'min_order_value': return + case 'min_order_value': return ( + + ) case 'min_category_qty': return (
{num('min', 1, 1)} diff --git a/manager_dashboard/src/pages/pricing/pricingLogic.js b/manager_dashboard/src/pages/pricing/pricingLogic.js index b8fcfe6..f7a8085 100644 --- a/manager_dashboard/src/pages/pricing/pricingLogic.js +++ b/manager_dashboard/src/pages/pricing/pricingLogic.js @@ -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 } } diff --git a/manager_dashboard/src/pages/products/ProductsPage.jsx b/manager_dashboard/src/pages/products/ProductsPage.jsx index 1418790..3c62756 100644 --- a/manager_dashboard/src/pages/products/ProductsPage.jsx +++ b/manager_dashboard/src/pages/products/ProductsPage.jsx @@ -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') diff --git a/manager_dashboard/src/pages/products/editor/ServiceItemDialog.jsx b/manager_dashboard/src/pages/products/editor/ServiceItemDialog.jsx index 504ab61..221086b 100644 --- a/manager_dashboard/src/pages/products/editor/ServiceItemDialog.jsx +++ b/manager_dashboard/src/pages/products/editor/ServiceItemDialog.jsx @@ -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 ( (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]])) diff --git a/manager_dashboard/src/pages/products/editor/parts.jsx b/manager_dashboard/src/pages/products/editor/parts.jsx index 28873c4..7c77ed8 100644 --- a/manager_dashboard/src/pages/products/editor/parts.jsx +++ b/manager_dashboard/src/pages/products/editor/parts.jsx @@ -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)) diff --git a/manager_dashboard/src/pages/staff/staffLogic.js b/manager_dashboard/src/pages/staff/staffLogic.js index 35cc7d0..64ab5b6 100644 --- a/manager_dashboard/src/pages/staff/staffLogic.js +++ b/manager_dashboard/src/pages/staff/staffLogic.js @@ -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 diff --git a/package-lock.json b/package-lock.json index edb13c0..2611db4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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" diff --git a/packages/i18n/locales/el/waiter.json b/packages/i18n/locales/el/waiter.json index b71b653..1694245 100644 --- a/packages/i18n/locales/el/waiter.json +++ b/packages/i18n/locales/el/waiter.json @@ -29,7 +29,8 @@ "startQuestion": "Θέλεις να ξεκινήσεις τη βάρδια σου;", "startingCash": "Αρχικά μετρητά (προαιρετικό)", "starting": "Εκκίνηση…", - "startShift": "Έναρξη Βάρδιας" + "startShift": "Έναρξη Βάρδιας", + "badAmount": "Γράψτε ένα ποσό, π.χ. 50 ή 50,00." }, "nav": { "tables": "Τραπέζια", diff --git a/packages/i18n/locales/en/waiter.json b/packages/i18n/locales/en/waiter.json index 7f29efc..5d6d6b3 100644 --- a/packages/i18n/locales/en/waiter.json +++ b/packages/i18n/locales/en/waiter.json @@ -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", diff --git a/packages/i18n/tests/typed-numbers.test.mjs b/packages/i18n/tests/typed-numbers.test.mjs new file mode 100644 index 0000000..efef649 --- /dev/null +++ b/packages/i18n/tests/typed-numbers.test.mjs @@ -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 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(/]*>/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, []) +}) diff --git a/packages/ui/package.json b/packages/ui/package.json index ba9fa2e..4be59d6 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -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" diff --git a/packages/ui/src/components.css b/packages/ui/src/components.css index f5ed1f0..4852a10 100644 --- a/packages/ui/src/components.css +++ b/packages/ui/src/components.css @@ -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 { diff --git a/packages/ui/src/components/DecimalInput.jsx b/packages/ui/src/components/DecimalInput.jsx new file mode 100644 index 0000000..c7090ec --- /dev/null +++ b/packages/ui/src/components/DecimalInput.jsx @@ -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. + * + * + * 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 ( + + { + 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 && } + + ) +} + +/** An amount of money: DecimalInput with cents and "€" (6F.2). */ +export function MoneyInput({ suffix = '€', ...rest }) { + return +} diff --git a/packages/ui/src/components/decimal.js b/packages/ui/src/components/decimal.js new file mode 100644 index 0000000..13d0fc7 --- /dev/null +++ b/packages/ui/src/components/decimal.js @@ -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 +} diff --git a/packages/ui/src/index.js b/packages/ui/src/index.js index efff895..41ff0b8 100644 --- a/packages/ui/src/index.js +++ b/packages/ui/src/index.js @@ -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' diff --git a/packages/ui/tests/decimal.test.mjs b/packages/ui/tests/decimal.test.mjs new file mode 100644 index 0000000..7cd3693 --- /dev/null +++ b/packages/ui/tests/decimal.test.mjs @@ -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) +}) diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index 6ea718c..c2bd5f7 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -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(() => {}) diff --git a/tests/e2e/waiter.mjs b/tests/e2e/waiter.mjs index 979f01b..c5176d9 100644 --- a/tests/e2e/waiter.mjs +++ b/tests/e2e/waiter.mjs @@ -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) ──────────────────────────────────── diff --git a/waiter_pwa/src/App.jsx b/waiter_pwa/src/App.jsx index 95187c4..92d2032 100644 --- a/waiter_pwa/src/App.jsx +++ b/waiter_pwa/src/App.jsx @@ -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 }) {
€ 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)', diff --git a/waiter_pwa/src/components/OrderDrawer.jsx b/waiter_pwa/src/components/OrderDrawer.jsx index 2a6dd74..944c7c9 100644 --- a/waiter_pwa/src/components/OrderDrawer.jsx +++ b/waiter_pwa/src/components/OrderDrawer.jsx @@ -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 ? ( 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 ? ( setRawInput(e.target.value)} onBlur={commitInput} diff --git a/waiter_pwa/src/pages/TableDetailPage.jsx b/waiter_pwa/src/pages/TableDetailPage.jsx index c828faf..9071030 100644 --- a/waiter_pwa/src/pages/TableDetailPage.jsx +++ b/waiter_pwa/src/pages/TableDetailPage.jsx @@ -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 ? ( setRawInput(e.target.value)} onBlur={commitEdit}