Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fix: a period typed into Edit prices on a comma-decimal market saved a hundred times the price (#14730)

Damian Legawiec6742c1a868ac
diff --git a/.changeset/dashboard-comma-decimal-prices.md b/.changeset/dashboard-comma-decimal-prices.md
new file mode 100644
index 0000000000..169579f008
--- /dev/null
+++ b/.changeset/dashboard-comma-decimal-prices.md
@@ -0,0 +1,7 @@
+---
+"@spree/dashboard": patch
+"@spree/dashboard-core": patch
+"@spree/dashboard-ui": patch
+---
+
+Fixed the Edit prices grid on a market with a comma decimal saving a typed `19.50` as 1950. A period followed by anything other than three digits is now read as a decimal point, and the grid shows exactly the amount it will save.
diff --git a/packages/dashboard-core/src/products/normalize-money.test.ts b/packages/dashboard-core/src/products/normalize-money.test.ts
index d7e3a9f802..ee53f5a6e3 100644
--- a/packages/dashboard-core/src/products/normalize-money.test.ts
+++ b/packages/dashboard-core/src/products/normalize-money.test.ts
@@ -14,6 +14,15 @@ describe('normalizeMoneyInput', () => {
expect(normalizeMoneyInput('1.000.000,00', 'de')).toBe('1000000.00')
})
+ it('reads a lone group separator not followed by three digits as the decimal', () => {
+ expect(normalizeMoneyInput('19.50', 'de')).toBe('19.50')
+ expect(normalizeMoneyInput('0.5', 'de')).toBe('0.5')
+ expect(normalizeMoneyInput('19.50 €', 'de')).toBe('19.50')
+ expect(normalizeMoneyInput('19,50', 'en')).toBe('19.50')
+ expect(normalizeMoneyInput('1.500 €', 'de')).toBe('1500')
+ expect(normalizeMoneyInput('1.234.567', 'de')).toBe('1234567')
+ })
+
it('handles fr narrow-space grouping', () => {
// fr groups with U+202F (narrow no-break space) and uses a comma decimal.
expect(normalizeMoneyInput('1 234,56', 'fr')).toBe('1234.56')
diff --git a/packages/dashboard-core/src/products/normalize-money.ts b/packages/dashboard-core/src/products/normalize-money.ts
index d6b291cdfd..1e126f96b4 100644
--- a/packages/dashboard-core/src/products/normalize-money.ts
+++ b/packages/dashboard-core/src/products/normalize-money.ts
@@ -30,6 +30,7 @@ function separatorsFor(locale: string): { decimal: string; group: string } {
* - `"1.234,56"` under `de` → `"1234.56"`
* - `"1 234,56"` under `fr` → `"1234.56"` (narrow-space grouping)
* - `"19.99"` under `en` → `"19.99"`
+ * - `"19.50"` under `de` → `"19.50"` (a period can't be grouping before two digits)
* - `""` / whitespace → `""`
*
* Strips the locale's group separator and any whitespace, standardizes the
@@ -48,6 +49,17 @@ export function normalizeMoneyInput(raw: string | null | undefined, locale: stri
const { decimal, group } = separatorsFor(locale)
let out = trimmed
+ // A group separator is always followed by exactly three digits, so a lone
+ // one that is not (`19.50` under `de`) is the merchant typing the other
+ // decimal mark. `1.500` stays ambiguous and is read the locale's way.
+ const groupParts = group.trim() === '' ? [] : out.split(group)
+ if (
+ groupParts.length === 2 &&
+ !out.includes(decimal) &&
+ groupParts[1].replace(/\D/g, '').length !== 3
+ ) {
+ out = groupParts.join(decimal)
+ }
// Remove the locale's grouping separator (explicit char) plus any whitespace
// (covers narrow/no-break spaces used by some locales as the group char).
if (group) out = out.split(group).join('')
diff --git a/packages/dashboard-ui/src/spree/data-grid/cells.tsx b/packages/dashboard-ui/src/spree/data-grid/cells.tsx
index 5c865b7089..823cda5f52 100644
--- a/packages/dashboard-ui/src/spree/data-grid/cells.tsx
+++ b/packages/dashboard-ui/src/spree/data-grid/cells.tsx
@@ -144,30 +144,26 @@ interface MoneyCellProps extends BaseCellProps {
/** Canonical decimal string (`12.50`) coming back from the API, or
* `null`/blank for unset. */
value: string | null
- /** Receives the user's raw input — locale-formatted strings like
- * `"12,50"` are fine, the backend's `Spree::LocalizedNumber` does the
- * parsing. `null` only when the user explicitly blanks the field. */
+ /** Receives the user's raw, locale-formatted input (`"12,50"`). The caller
+ * normalizes it to canonical and passes that back as `value`, so the cell
+ * always shows what will be saved. `null` only when the user explicitly
+ * blanks the field. */
onChange: (next: string | null) => void
/** Currency symbol rendered as a non-editable prefix (`$`, `€`, `kr`, …).
* Omit for a plain decimal cell with no prefix. */
symbol?: string
/**
* Locale decimal separator used only for display (canonical `.` →
- * locale char). Whatever the user types is shipped as-is; the
- * backend handles thousands separators, grouped digits, and so on.
- * Default `.`.
+ * locale char). Default `.`.
*/
decimal?: string
}
/**
* Editable money cell. Like `NumberCell` but keeps decimals (no truncation)
- * and renders a currency-symbol prefix. Mirrors the rails admin's
- * `edit_prices` bulk editor: format the API's canonical value with the
- * locale's decimal mark for display, but ship the user's raw input
- * untouched on save. `Spree::LocalizedNumber.parse` on the backend handles
- * locale-aware parsing (thousands separators, decimal comma, etc.) so the
- * SPA doesn't have to reimplement it.
+ * and renders a currency-symbol prefix. Formats the canonical value with the
+ * locale's decimal mark for display and hands the user's raw input to
+ * `onChange` for the caller to normalize.
*/
export function MoneyCell({
coords,
@@ -219,9 +215,7 @@ export function MoneyCell({
})
function commit() {
- // Ship the user's raw input; the backend's `Spree::LocalizedNumber`
- // handles locale-aware parsing. Empty string is the only "clear"
- // signal we generate frontend-side.
+ // Empty string is the only "clear" signal we generate frontend-side.
onChange(draft.trim() ? draft : null)
}
diff --git a/packages/dashboard/e2e/price-lists.spec.ts b/packages/dashboard/e2e/price-lists.spec.ts
index f8a7a7dce8..967967c6c1 100644
--- a/packages/dashboard/e2e/price-lists.spec.ts
+++ b/packages/dashboard/e2e/price-lists.spec.ts
@@ -538,12 +538,30 @@ test.describe('price lists', () => {
await expect(dialog.getByText(/unsaved change/i)).toBeHidden({ timeout: 15_000 })
// Switch to EUR — the grid reloads with that currency's (empty) prices and
- // formats in the EUR market locale (de: comma decimal). Enter a localized
- // amount `55,55`; it must persist as 55.55 (not 5555).
+ // formats in the EUR market locale (de: comma decimal). A period typed
+ // there is still a decimal point: `19.50` shows and saves as 19,50, never
+ // 1950.
await currencyTrigger.click()
await page.getByRole('option', { name: 'EUR' }).click()
await expect(currencyTrigger).toContainText('EUR')
+ await priceCell().dblclick()
+ await priceCell().fill('19.50')
+ await priceCell().press('Enter')
+ await expect(priceCell()).toHaveValue('19,50')
+ await dialog.getByRole('button', { name: /^save prices$/i }).click()
+ await expect(dialog.getByText(/unsaved change/i)).toBeHidden({ timeout: 15_000 })
+
+ // Reload EUR from the server, then enter a localized amount `55,55`; it
+ // must persist as 55.55 (not 5555).
+ await currencyTrigger.click()
+ await page.getByRole('option', { name: 'USD' }).click()
+ await expect(currencyTrigger).toContainText('USD')
+ await currencyTrigger.click()
+ await page.getByRole('option', { name: 'EUR' }).click()
+ await expect(currencyTrigger).toContainText('EUR')
+ await expect(priceCell()).toHaveValue(/^19,50?$/, { timeout: 15_000 })
+
await priceCell().dblclick()
await priceCell().fill('55,55')
await priceCell().press('Enter')
diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
index 45385a2ae4..fe6c9dcc8e 100644
--- a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
+++ b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx
@@ -150,8 +150,8 @@ export function BulkPriceEditor({
const filterKey = useMemo(() => stableFilterKey(sanitizedFilter), [sanitizedFilter])
// Format the grid in the currency's market locale (e.g. EUR → `de`, comma
- // decimal). The same locale normalizes amounts to canonical form on save (see
- // `save`), so what the merchant types matches what the API receives. Falls
+ // decimal). The same locale normalizes each typed amount to canonical form as the
+ // cell commits (see `handleChange`), so the grid shows what Save sends. Falls
// back to `en` (canonical period-decimal), NOT the UI language — money
// formatting/parsing must never depend on the dashboard's language.
const marketLocale = localeForCurrency(currency) || 'en'
@@ -370,8 +370,6 @@ export function BulkPriceEditor({
// Releases a saved edit once the refetched row agrees with it, so the cell
// hands over to server data without ever showing the value it replaced.
- // Compared on the canonical decimal, since the edit holds the merchant's
- // locale-formatted input.
useEffect(() => {
if (savedPending.size === 0) return
@@ -387,8 +385,7 @@ export function BulkPriceEditor({
const baseline = baselineRows.find((row) => (row.priceId ?? row.id) === key)
if (!baseline) continue
- const saved = normalizeMoneyInput(edit.amount ?? '', marketLocale || 'en')
- if ((baseline.amount ?? '') === (saved === '' ? '' : saved)) settled.push(key)
+ if ((baseline.amount ?? null) === edit.amount) settled.push(key)
}
if (settled.length === 0) return
@@ -402,7 +399,7 @@ export function BulkPriceEditor({
for (const key of settled) out.delete(key)
return out
})
- }, [baselineRows, edits, savedPending, marketLocale])
+ }, [baselineRows, edits, savedPending])
// Hands a saved draft over to the row the server now returns, once that row
// has actually arrived. Doing this on save instead would blank the rung for
@@ -470,25 +467,22 @@ export function BulkPriceEditor({
// Typing a price into the trailing blank row is what creates the rung.
const promoted = promoteBlankRow(rowId)
const targetId = promoted ?? rowId
+ // Normalized on commit, from the currency's market locale, so an edit
+ // holds the same canonical `"1234.56"` the API returns. The cell then
+ // shows exactly what Save will send (docs/plans/5.5-client-side-money-normalization.md).
+ const canonical = normalizeMoneyInput(next, marketLocale) || null
setEdits((prev) => {
// A draft rung has no stored row, so it is found by its own id.
const baseline = baselineRows.find((r) => (r.priceId ?? r.id) === rowId)
if (!baseline?.variantId) return prev
- // Baseline is the API's canonical decimal (`12.50`); the cell
- // ships the user's raw locale-formatted input (`12,50`). Seed the
- // baseline in display form so an untouched field naturally matches
- // when the other field is edited — otherwise an edit to `compareAt`
- // alone would falsely mark `amount` dirty under a comma-decimal locale.
- const displayBaseAmount = baseline.amount ? baseline.amount.replace('.', decimal) : null
- const displayBaseCompare = baseline.compareAt
- ? baseline.compareAt.replace('.', decimal)
- : null
+ const baseAmount = baseline.amount ?? null
+ const baseCompare = baseline.compareAt ?? null
const current = prev.get(targetId) ?? {
variantId: baseline.variantId,
minQuantity: baseline.minQuantity,
- amount: displayBaseAmount,
- compareAt: displayBaseCompare,
+ amount: baseAmount,
+ compareAt: baseCompare,
}
// An edit already holding a quantity keeps it: the merchant may have
// typed the quantity first, and the baseline still says what the
@@ -497,16 +491,16 @@ export function BulkPriceEditor({
const merged = {
...current,
minQuantity: prev.get(targetId)?.minQuantity ?? baseline.minQuantity,
- [field]: next,
+ [field]: canonical,
// Blanking the price of a rung the server already has is how it is
// deleted, the same as the row's remove control. On a rung that was
// never stored there is nothing to delete — it is simply unfinished,
// and the save refuses it rather than reporting a removal.
...(field === 'amount'
- ? { removing: !next && baseline.priceId ? (true as const) : undefined }
+ ? { removing: !canonical && baseline.priceId ? (true as const) : undefined }
: {}),
}
- if (merged.amount === displayBaseAmount && merged.compareAt === displayBaseCompare) {
+ if (merged.amount === baseAmount && merged.compareAt === baseCompare) {
const out = new Map(prev)
out.delete(targetId)
return out
@@ -516,7 +510,7 @@ export function BulkPriceEditor({
return out
})
},
- [baselineRows, decimal, promoteBlankRow],
+ [baselineRows, marketLocale, promoteBlankRow],
)
// The plus on the blank row does the same thing a keystroke does — it is
@@ -633,15 +627,6 @@ export function BulkPriceEditor({
// — that's what the server upserts on. `id` is not used by the bulk
// endpoint; we already have the lookup columns on screen so there's
// no point making the server backfill them.
- // Normalize each amount from the grid's display locale (the currency's
- // market locale, e.g. EUR → `de`) into the canonical `"1234.56"` the API
- // expects. The server is never asked to parse comma-vs-period — see
- // docs/plans/5.5-client-side-money-normalization.md.
- const toCanonical = (v: string | null) => {
- if (v == null) return null
- const normalized = normalizeMoneyInput(v, marketLocale || 'en')
- return normalized === '' ? null : normalized
- }
const payload: PriceBulkUpsertRow[] = savedKeys.flatMap((priceId) => {
const edit = edits.get(priceId) as CellEdit
const row: PriceBulkUpsertRow = {
@@ -650,10 +635,10 @@ export function BulkPriceEditor({
...(priceListId ? { price_list_id: priceListId } : {}),
// Absent on a variant's own price, which is the ladder's bottom rung.
...(edit.minQuantity ? { min_quantity: Number(edit.minQuantity) } : {}),
- amount: toCanonical(edit.amount),
+ amount: edit.amount,
// A break carries no compare-at; sending one would claim a former
// price for a contracted figure.
- ...(edit.minQuantity ? {} : { compare_at_amount: toCanonical(edit.compareAt) }),
+ ...(edit.minQuantity ? {} : { compare_at_amount: edit.compareAt }),
}
// A rung whose quantity moved is an insert at the new one, since that
// is what the endpoint keys on — so the row it left behind is cleared
@@ -695,7 +680,7 @@ export function BulkPriceEditor({
)
return false
}
- }, [edits, savedPending, currency, priceListId, bulkUpsertAsync, marketLocale, t])
+ }, [edits, savedPending, currency, priceListId, bulkUpsertAsync, t])
const discard = useCallback(() => {
setSaveError(null)