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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fixed: make dashboard money entry handle localized currencies (e.g. E… (#14183)
Damian Legawiecf7bc94d4ab32
diff --git a/docs/api-reference/admin-api/monetary-amounts.mdx b/docs/api-reference/admin-api/monetary-amounts.mdxindex 185263ee83..66164e7c05 100644--- a/docs/api-reference/admin-api/monetary-amounts.mdx+++ b/docs/api-reference/admin-api/monetary-amounts.mdx@@ -4,7 +4,7 @@ sidebarTitle: "Monetary Amounts"description: "How the Admin API represents money as decimal strings, why JSON numbers are avoided, and how to send prices, costs, and amounts safely in requests."----All monetary values in the Admin API are **strings** (e.g., `"29.99"`, `"0.0"`), both in responses and in request bodies. This preserves decimal precision and avoids the floating-point rounding issues common with JSON numbers — critical when an admin is setting prices and costs.+All monetary values in the Admin API are **canonical decimal strings** (e.g., `"29.99"`, `"0.0"` — period decimal, no thousands grouping), both in responses and in request bodies. Strings preserve decimal precision and avoid the floating-point rounding issues common with JSON numbers — critical when an admin is setting prices and costs. The format is the same regardless of locale; localized formatting is a presentation concern handled by the client (see [Canonical format](#canonical-format-not-localized)).## Reading@@ -42,26 +42,11 @@ spree api post /products -d '{"name":"Classic Tee","prices":[{"currency":"USD","JSON numbers are also accepted (`"amount": 29.99`), but strings are recommended: they round-trip with what the API returns and sidestep float precision. A `null` clears the value.-### Localized input+### Canonical format — not localized-Amounts may be sent in the active locale's number format — Spree parses the locale's decimal separator and thousands delimiter. Under a `de` context, `1.299,00` parses to `1299.00`:+Amounts are **canonical**: a period decimal separator and no thousands grouping (`"1234.56"`), independent of any locale. The Admin API does **not** parse locale-specific formats — do not send `"1.234,56"` or `"1,234.56"`.-<CodeGroup>--```typescript Admin SDK-await client.products.create({- name: 'Designer Bag',- prices: [{ currency: 'EUR', amount: '1.299,00' }],-})-```--```bash CLI-spree api post /products -d '{"name":"Designer Bag","prices":[{"currency":"EUR","amount":"1.299,00"}]}'-```--</CodeGroup>--Only the string form can express a localized amount — a JSON number literal cannot represent `1.299,00`.+If you are taking input from a merchant in a localized format, normalize it to canonical form **before** sending. The Spree dashboard does this in the browser: a EUR price typed as `1.234,56` becomes `1234.56` on the wire. This matches how other commerce APIs handle money (canonical decimal or minor-unit integers; localization is a presentation concern).## Affected types@@ -81,7 +66,7 @@ This convention applies to all monetary fields across all resources, including b### Amounts inside `preferences`-Calculators and some promotion rules carry their amounts inside an untyped `preferences` object (`Record<string, unknown>`) rather than as top-level fields. The same string convention applies to the money-valued keys within that hash — they read back as strings and accept strings (and localized strings) on write. The keys that are money:+Calculators and some promotion rules carry their amounts inside an untyped `preferences` object (`Record<string, unknown>`) rather than as top-level fields. The same canonical-string convention applies to the money-valued keys within that hash — they read back as strings and accept canonical decimal strings on write. The keys that are money:| Resource | Money keys in `preferences` ||----------|------------------------------|diff --git a/docs/plans/5.5-client-side-money-normalization.md b/docs/plans/5.5-client-side-money-normalization.mdnew file mode 100644index 0000000000..3c64b055c6--- /dev/null+++ b/docs/plans/5.5-client-side-money-normalization.md@@ -0,0 +1,145 @@+# Client-Side Monetary Normalization (Admin API + React Dashboard)++**Status:** In Progress+**Target:** Spree 5.5+**Depends on:** `5.4-store-api-naming-standardization.md` (monetary string convention)+**Author:** Damian + Claude+**Last updated:** 2026-06-16++## Summary++The React dashboard and Admin API should follow the industry-standard model for monetary amounts: **clients send a canonical decimal string (`"1234.56"`, period decimal, no grouping); localization is a presentation-layer concern only.** The dashboard parses the merchant's locale-formatted input (`"1.234,56"`) into canonical form **in the browser** before it reaches the API. No request locale (`x-spree-locale`) is needed to parse money.++This replaces the in-progress approach where the dashboard sent the raw localized string and relied on the server's `Spree::LocalizedNumber.parse` (keyed off the request locale) to decode it. That approach is non-standard, couples money entry to an `x-spree-locale` header the SDK had to send, and breaks down where one request carries amounts in multiple currencies (the product PATCH batches USD + EUR prices — a single locale can't parse both).++**`Spree::LocalizedNumber.parse` stays in the models, unchanged.** The legacy Rails admin keeps relying on it (its inputs are locale-formatted and parsed server-side under the session locale). A canonical `"19.99"` parses correctly under *any* locale, so a dashboard that always sends canonical strings needs no server change — the pivot is client-side only.++## Why (industry research)++Every major commerce platform treats the money API format as canonical and locale-agnostic; localized parsing happens client-side or not at all:++| Platform | API money format | Localized input parsing |+|----------|------------------|-------------------------|+| **Shopify** | Decimal scalar string, always `"19.99"` (period, no grouping), independent of admin locale (`MoneyInput.amount: Decimal!`) | Display only (`Intl.NumberFormat` / Liquid filters) |+| **Saleor** | `Money { amount: Float!, currency }` | Display only — docs: "use the internationalization API provided by the browser" |+| **Vendure** | Integer minor units (cents); `12345` = 123.45 | **Client-side** — admin `CurrencyInputComponent` "displays currency in decimal format, whilst working with the integer cent value in the background" |+| **Medusa** | Integer minor units (cents) for API I/O | Client-side / N/A (integers have no separator ambiguity) |++None parse comma-vs-period strings on the server. Spree's `x-spree-locale`-driven server parse is the outlier.++## Two independent locales — do not conflate (drives the SDK decision)++There are two unrelated "locales" in the dashboard, and keeping them separate is what makes this design correct:++| | Controls | Lives in | Sent to the API? |+|---|---|---|---|+| **Dashboard UI language** | The chrome — buttons, labels, toasts ("Save", "Issue store credit") | React SPA state (i18next `i18n.language`) | **Never** |+| **Store content locale** | The data — product names, descriptions; the canonical source of truth | Server (store's main/canonical locale) | Dashboard always uses canonical |++Motivating scenario: a back-office worker in a cheaper country operates a **US store**. They set the dashboard to **German UI** so they can read the interface — but every product, price, and order they manage is still the store's **canonical US/English/USD data**. The German-UI preference is "what language are my buttons in," not "show me German product data."++Consequences (binding):++- **The dashboard UI language is i18next-only SPA state and must NEVER become an `x-spree-locale` header.** If it leaked into the API it would (a) silently scope every read to translations the store may not have, and (b) re-break canonical money parsing (`"19.99"` under `de` → 1999).+- **The `@spree/admin-sdk` has NO client-level locale/currency switching** (unlike the Store SDK's `setLocale`/`setCurrency`/`setCountry`). The dashboard is a back-office tool operating in the canonical locale; a global locale default is wrong for it and a money footgun.+- **Deliberate per-locale/per-currency needs use a per-request override** — `options.locale` / `options.currency` on a single call. This already works via the generic `RequestOptions` path (no client-level state). Examples: a translations editor writing a German *product* name (`{ locale: 'de' }` on that update); a currency-scoped price read (`{ currency: 'EUR' }` on that GET).++## Key Decisions (do not deviate without discussion)++- **Admin API money contract is canonical decimal strings.** Read and write: `"19.99"` — period decimal, no thousands separator, matching what serializers already emit (see `docs/api-reference/admin-api/monetary-amounts.mdx`). This is already the *read* format; this plan makes it the explicit *write* format too.+- **The React dashboard normalizes localized input → canonical before sending.** A shared util parses the merchant's input in the active display locale (currency's market locale) and emits `"1234.56"`. Built on `Intl.NumberFormat(...).formatToParts` to derive the locale's separators, then strip grouping and standardize the decimal to `.`.+- **No `x-spree-locale` is sent to drive money parsing.** Revert the per-form locale overrides AND the client-level admin-sdk locale support added on the feature branch. The admin-sdk has no `setLocale`/`setCurrency`/`AdminClientConfig.locale` (see "Two independent locales" above) — deliberate per-locale/per-currency calls use the generic per-request `options.locale`/`options.currency`.+- **`Spree::LocalizedNumber.parse` is NOT removed and NOT changed.** It remains the parser for the legacy Rails admin and any other locale-formatted caller. Because canonical `"19.99"` is locale-invariant, no model/controller change is required for the dashboard pivot.+- **Rails admin (legacy `spree/admin`) is out of scope.** It keeps submitting locale-formatted values parsed server-side under the session locale. Untouched.+- **Store API is out of scope.** Audited: the Store API v3 accepts no client-supplied amount that reaches a `LocalizedNumber`-guarded setter (amounts are derived server-side; `Spree::Payment#amount=` has its own parser). No change needed.++## Why this is safe with the existing model setters (important)++The model money setters (`Spree::Price#amount=`, `Spree::StoreCredit#amount=`, etc. — ~11 of them) stay **unchanged**: `self[:amount] = Spree::LocalizedNumber.parse(amount)`. This is safe but for a subtle, must-understand reason:++**`LocalizedNumber.parse` is NOT locale-invariant.** A canonical `"1234.56"` parses correctly only under a period-decimal locale:++| Input | `en` parse | `de` / `fr` parse |+|-------|-----------|-------------------|+| `"1234.56"` | 1234.56 ✅ | **123456** ❌ (`.` treated as thousands separator) |+| `"19.99"` | 19.99 ✅ | **1999** ❌ |++The pivot is safe **in the common case**: the admin-sdk sends no `x-spree-country` and no `x-spree-locale`, so `LocaleAndCurrency` never resolves a comma-decimal market and `Spree::Current.locale` falls back to the store's `default_locale`. For the default and seeded stores that is `en` (a period-decimal locale), under which canonical input round-trips correctly — making the setters an effective no-op for the dashboard while still serving the Rails admin.++**This is a known constraint, not a guarantee.** It rests on the store's default locale being period-decimal. A store whose `default_locale` is a comma-decimal locale (e.g. `de`) would have the model setters re-parse canonical `"19.99"` as `1999`. Likewise if a dashboard request ever resolves to a comma-decimal locale (someone sends `x-spree-locale: de`, or admin requests start resolving a market from `x-spree-country`). The 6.0 fix below removes the constraint entirely by making the Admin API contract locale-invariant; until then it is guarded by the e2e money tests (which assert canonical persistence) and should be treated as a temporary assumption.++### Deprecation path (6.0)++Keep `LocalizedNumber.parse` in 5.5 for backward compatibility (the Rails admin needs it; it's harmless for the dashboard under `en`). In 6.0, make localized parsing a **presentation-layer concern only**:++- The Admin API money contract is strictly canonical (`^-?\d+(\.\d+)?$`). Admin API controllers/models assign canonical values directly (e.g. `BigDecimal(value)`), not via `LocalizedNumber.parse`.+- `LocalizedNumber.parse` survives only where HTML-form params arrive locale-formatted — i.e. the legacy Rails admin — and ideally is scoped to that layer rather than living on the model setter.+- Deprecate the locale-parsing model setters: warn when they receive a non-canonical string, then drop the parse in 6.0.++This matches the industry research (Shopify/Saleor canonical decimal; Vendure/Medusa minor-unit integers — none parse comma-vs-period server-side).++## Design Details++### The normalization utility (dashboard)++A single util in `@spree/dashboard` (or `dashboard-ui`), e.g. `normalizeMoneyInput(raw: string, locale: string): string`:++1. Derive the locale's decimal + group separators via `Intl.NumberFormat(locale, { useGrouping: true }).formatToParts(11111.1)`.+2. Strip the group separator, replace the locale decimal separator with `.`, drop any non-`[0-9.\-]`.+3. Return the canonical string (or `''`/null for blank). No `Number()` round-trip — preserve full precision as a string.++The display locale per currency is resolved from the store's markets (`useCurrencyLocale`, already built): a EUR cell formats/reads under the EUR market's `de` locale, so the merchant sees and types `1.234,56`, and the util converts to `1234.56` on the way out.++### Money form integration points (dashboard)++Each money form: keep locale-aware **display** (already done via `currencyParts` / market locale), add a normalize-on-submit step:++- **Store credit** (`customers/$customerId.tsx`, Issue + Edit dialogs): normalize `amount` before `mutateAsync`. Drop the `{ locale }` override.+- **Price-list bulk editor** (`bulk-price-editor.tsx`): normalize each cell's amount/compare-at before `bulkUpsert`. Drop the `{ locale }` override. (Display already uses the market locale.)+- **Product base prices** (`product-bulk-price-editor.tsx` → product PATCH): normalize each `variants[].prices[]` amount before the product update. **This unblocks the multi-currency product form** — every amount is canonical regardless of currency, so the single batched PATCH is fine and needs no locale.+- **Gift cards, payments, refunds, store-credit** elsewhere: same pattern where a money input exists.++### What gets reverted from the feature branch++- `packages/dashboard/src/hooks/use-customer-store-credits.ts` — `{ params, locale }` → back to `params`, no locale.+- `bulk-price-editor.tsx` / `use-prices.ts` — drop the `locale` plumbing on upsert.+- `customers/$customerId.tsx` — drop `localeForCurrency(...)` override args (keep the currency→locale resolver for *display*).+- `packages/dashboard-core/src/lib/i18n.ts` — remove the `adminClient.setLocale(i18n.language)` money-motivated wiring (or keep purely for translated-content locale, decided separately — not for money).++### What stays from the feature branch++- **`@spree/admin-sdk` is UNCHANGED.** The client-level `setLocale`/`setCurrency`/`AdminClientConfig.locale` briefly added on the branch was fully reverted — the admin-sdk needs no change for this work. Per-request `options.locale`/`options.currency` already exist on the generic `RequestOptions` path (untouched) for the rare deliberate translation-write / currency-scoped-read.+- **EUR market seed in e2e `global-setup.ts`** + the markets/price-lists spec deconfliction — needed for multi-currency tests regardless of approach.+- **`spree_i18n` added to `spree/api/Gemfile`** — the test app should match production, which bundles it (and the Rails admin needs it). Note: with the pivot, the *dashboard* money path no longer depends on it (it resolves to `en`); it's retained for production parity and the Rails admin.++### Dashboard UI language (out of scope, but adjacent)++The dashboard's own UI language (i18next `i18n.language`) is unaffected by this plan and stays a pure SPA concern — a back-office worker can run a US store with a German *interface*. It is never forwarded to the API (the `adminClient.setLocale(i18n.language)` wiring briefly added on the branch was reverted). If/when more dashboard UI locales ship, the language switcher mutates `i18n.language` only.++## Migration Path++1. Land the canonical-string contract: confirm Admin API serializers emit canonical strings (done) and document that writes expect the same (update `monetary-amounts.mdx` to state the write format explicitly; remove the "localized string accepted" framing for the Admin API / dashboard path).+2. Add `normalizeMoneyInput` util + tests in the dashboard.+3. Wire it into each money form's submit path; revert the per-form `x-spree-locale` overrides.+4. Update E2E tests: enter localized `1.234,56` / `55,55`, assert canonical persistence — the value is normalized client-side, so the assertions already written (round-trip + mangle guard) hold without the server-locale dependency.+5. Leave `Spree::LocalizedNumber` and the Rails admin untouched.++## Constraints on Current Work++- **New dashboard money inputs must normalize on submit** — never send a locale-formatted string to the Admin API; send canonical `"1234.56"`.+- **Do not add new `x-spree-locale`-for-money plumbing.** The header is not the money mechanism.+- **Do not remove or weaken `Spree::LocalizedNumber.parse`** — the Rails admin still needs it.+- **Admin API money writes are canonical decimal strings** — keep read/write symmetry on `"19.99"`.++## Open Questions++- Should the normalize util live in `dashboard-ui` (so the MoneyCell owns it end-to-end) or `dashboard` (form layer)? Leaning `dashboard-ui` since the cell already owns display formatting.+- Long-term: do we want the Admin API to *reject* non-canonical money strings (strict `^\d+(\.\d+)?$` validation) to make the contract explicit, or keep tolerating localized input server-side (via the models' `LocalizedNumber`) as a lenient fallback? Strict is more Shopify-like; lenient is backward-compatible. Recommend lenient now, revisit.++## References++- Research: [Shopify MoneyInput (Decimal!)](https://shopify.dev/docs/api/admin-graphql/latest/input-objects/MoneyInput), [Shopify REST price format](https://community.shopify.com/t/rest-api-format-of-prices-and-other-monetary-amounts/65342), [Saleor Prices](https://docs.saleor.io/docs/3.x/api-usage/prices), [Vendure Money & Currency](https://docs.vendure.io/guides/core-concepts/money/) + [CurrencyInputComponent](https://docs.vendure.io/reference/admin-ui-api/components/currency-input-component), [Medusa Pricing](https://docs.medusajs.com/resources/commerce-modules/pricing)+- `docs/api-reference/admin-api/monetary-amounts.mdx` — current money-format docs+- `docs/api-reference/store-api/monetary-amounts.mdx` — Store API (read-only) money format+- `Spree::LocalizedNumber` — `spree/core/lib/spree/localized_number.rb` (kept for Rails admin)+- Feature branch `chore/dashboard-e2e-monetary-forms` — admin-sdk locale support, EUR market seed, the `x-spree-locale` money approach this plan supersedesdiff --git a/packages/dashboard/e2e/customers.spec.ts b/packages/dashboard/e2e/customers.spec.tsindex b6929f4dcf..b320cbb0c8 100644--- a/packages/dashboard/e2e/customers.spec.ts+++ b/packages/dashboard/e2e/customers.spec.ts@@ -103,6 +103,161 @@ test.describe('customers', () => {await expect(page.getByText(/25\.00/).first()).toBeVisible({ timeout: 15_000 })})+ // Store credits are multi-currency AND localized. Selecting EUR drives both+ // the credit's currency and (via the EUR market's `de` locale) the amount's+ // display/parse format. The amount is entered comma-decimal (`1.234,56` =+ // 1234.56); the dashboard normalizes it to canonical form before sending, so+ // it persists as 1234.56 and renders €1,234.56 (en display locale) — not the+ // mangled 123456.+ test('issues store credit in EUR with a localized (comma-decimal) amount', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, CUSTOMERS_PATH(creds.store_id), CTA)++ const email = `e2e-credit-eur-${Date.now()}@example.com`+ await createCustomer(page, email)++ await page.getByRole('button', { name: /issue store credit/i }).click()+ await expect(page.getByRole('heading', { name: /issue store credit/i })).toBeVisible()++ // Switch to EUR first so the form's locale resolves before submit.+ await page.locator('#sc-currency').click()+ await page.getByRole('option', { name: /EUR/ }).click()+ // German-formatted amount: dot thousands, comma decimal.+ await page.locator('#sc-amount').fill('1.234,56')+ await page.locator('#sc-memo').fill('E2E EUR localized credit')+ await page.locator('#sc-category').click()+ await page.getByRole('option').first().click()++ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^issue store credit$/i })+ .click()++ // Persisted as 1234.56 EUR (not 123456): renders €1,234.56 in the en display+ // locale. The comma-decimal input round-tripped through client normalization.+ await expect(page.getByText(/€\s?1,234\.56/).first()).toBeVisible({ timeout: 15_000 })+ // Guard against the mangled value (comma treated as thousands → 123456).+ await expect(page.getByText(/123,456/)).toHaveCount(0)+ })++ // Regression: typing a USD-style `25.00`, THEN switching the currency to EUR+ // must not re-read the `.` as a thousands separator on submit (→ 2500). The+ // form reformats the amount to the new currency's locale on switch, so it+ // persists as €25.00.+ test('reformats the amount when the store-credit currency switches', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, CUSTOMERS_PATH(creds.store_id), CTA)++ const email = `e2e-credit-switch-${Date.now()}@example.com`+ await createCustomer(page, email)++ await page.getByRole('button', { name: /issue store credit/i }).click()+ await expect(page.getByRole('heading', { name: /issue store credit/i })).toBeVisible()++ // Type a period-decimal amount under the USD default, THEN switch to EUR.+ await page.locator('#sc-amount').fill('25.00')+ await page.locator('#sc-currency').click()+ await page.getByRole('option', { name: /EUR/ }).click()+ await page.locator('#sc-memo').fill('E2E currency switch')+ await page.locator('#sc-category').click()+ await page.getByRole('option').first().click()++ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^issue store credit$/i })+ .click()++ // €25.00, not €2,500.00.+ await expect(page.getByText(/€\s?25\.00/).first()).toBeVisible({ timeout: 15_000 })+ await expect(page.getByText(/2,500/)).toHaveCount(0)+ })++ test('edits a store credit amount', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, CUSTOMERS_PATH(creds.store_id), CTA)++ const email = `e2e-credit-edit-${Date.now()}@example.com`+ await createCustomer(page, email)++ await page.getByRole('button', { name: /issue store credit/i }).click()+ await expect(page.getByRole('heading', { name: /issue store credit/i })).toBeVisible()+ await page.locator('#sc-amount').fill('25.00')+ await page.locator('#sc-memo').fill('E2E credit to edit')+ await page.locator('#sc-category').click()+ await page.getByRole('option').first().click()+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^issue store credit$/i })+ .click()+ await expect(page.getByText(/25\.00/).first()).toBeVisible({ timeout: 15_000 })++ // Open the credit row's actions menu → Edit, change the amount, and save.+ // The trigger is an icon-only button with no accessible name, so scope to+ // the table row that shows the amount and click its button. Covers the+ // EditStoreCreditDialog raw-string submit path.+ await page+ .getByRole('row', { name: /25\.00/ })+ .getByRole('button')+ .click()+ await page.getByRole('menuitem', { name: /^edit$/i }).click()+ await expect(page.getByRole('heading', { name: /edit store credit/i })).toBeVisible()++ const amount = page.locator('#edit-sc-amount')+ await expect(amount).toBeEnabled()+ await amount.fill('40.00')+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^save$/i })+ .click()++ await expect(page.getByText(/40\.00/).first()).toBeVisible({ timeout: 15_000 })+ })++ // The Edit dialog locks currency to the credit's currency, so editing an EUR+ // credit must parse the new amount under the EUR market locale too. Issue in+ // EUR, then edit to another comma-decimal value and confirm it round-trips.+ test('edits an EUR store credit with a localized amount', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, CUSTOMERS_PATH(creds.store_id), CTA)++ const email = `e2e-credit-eur-edit-${Date.now()}@example.com`+ await createCustomer(page, email)++ // Issue an EUR credit at 50,00 (€50.00).+ await page.getByRole('button', { name: /issue store credit/i }).click()+ await expect(page.getByRole('heading', { name: /issue store credit/i })).toBeVisible()+ await page.locator('#sc-currency').click()+ await page.getByRole('option', { name: /EUR/ }).click()+ await page.locator('#sc-amount').fill('50,00')+ await page.locator('#sc-memo').fill('E2E EUR credit to edit')+ await page.locator('#sc-category').click()+ await page.getByRole('option').first().click()+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^issue store credit$/i })+ .click()+ await expect(page.getByText(/€\s?50\.00/).first()).toBeVisible({ timeout: 15_000 })++ // Edit the amount to a comma-decimal 73,45 → must persist as €73.45.+ await page+ .getByRole('row', { name: /50\.00/ })+ .getByRole('button')+ .click()+ await page.getByRole('menuitem', { name: /^edit$/i }).click()+ await expect(page.getByRole('heading', { name: /edit store credit/i })).toBeVisible()++ const amount = page.locator('#edit-sc-amount')+ await expect(amount).toBeEnabled()+ await amount.fill('73,45')+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^save$/i })+ .click()++ await expect(page.getByText(/€\s?73\.45/).first()).toBeVisible({ timeout: 15_000 })+ await expect(page.getByText(/7,345/)).toHaveCount(0)+ })+test('bulk-assigns selected customers to a group', async ({ page }) => {const creds = await login(page)await gotoIndex(page, CUSTOMERS_PATH(creds.store_id), CTA)diff --git a/packages/dashboard/e2e/global-setup.ts b/packages/dashboard/e2e/global-setup.tsindex 58115419f1..0542af53c9 100644--- a/packages/dashboard/e2e/global-setup.ts+++ b/packages/dashboard/e2e/global-setup.ts@@ -92,6 +92,19 @@ const BOOTSTRAP_RUBY = [`taxonomy.taxons.where(name: '${FIXTURE_BULK_CATEGORY}').first_or_create!(parent: taxonomy.root)`,`Spree.user_class.where(email: '${FIXTURE_PROMO_CUSTOMER_EMAIL}').first_or_create! { |u| u.password = 'customer123'; u.password_confirmation = 'customer123'; u.first_name = '${FIXTURE_PROMO_CUSTOMER_FIRST_NAME}'; u.last_name = '${FIXTURE_PROMO_CUSTOMER_LAST_NAME}' }`,`s.customer_groups.where(name: '${FIXTURE_PROMO_CUSTOMER_GROUP}').first_or_create!`,+ // Make the store multi-currency so the money-entry forms (store credit,+ // refunds, manual prices) offer EUR alongside the USD default. Markets own+ // currency + locale (the legacy Store#supported_currencies column is dead),+ // and in markets mode the supported-currency list is exactly the markets'+ // currencies. The store already has a default US/USD market via+ // Store#ensure_default_market, so we add a EUR market here, anchored to+ // Germany. `MarketCountry#country_unique_per_store` forbids reusing a+ // country across markets — the markets specs draw from other EU countries+ // (see the note atop markets.spec.ts).+ // Fail fast (find_by!) if Germany isn't seeded — a missing EUR market would+ // otherwise surface later as opaque multi-currency E2E failures.+ `germany = Spree::Country.find_by!(iso: 'DE')`,+ `s.markets.find_or_create_by!(name: 'Europe') { |m| m.currency = 'EUR'; m.default_locale = 'de'; m.countries = [germany] } unless s.markets.exists?(currency: 'EUR')`,'port = ENV.fetch("PORT", 3010)','puts JSON.generate(api_url: "http://localhost:#{port}", admin_email: admin.email, admin_password: "spree123", store_id: s.prefixed_id, store_name: s.name)',].join('; ')diff --git a/packages/dashboard/e2e/markets.spec.ts b/packages/dashboard/e2e/markets.spec.tsindex 62c77002c0..52da80bb38 100644--- a/packages/dashboard/e2e/markets.spec.ts+++ b/packages/dashboard/e2e/markets.spec.ts@@ -29,10 +29,12 @@ async function createMarket(page: Page, attrs: { name: string; countries: string// The seeded default store creates a default market for `US` via// `Store#ensure_default_market` (anchored to `default_country_iso = 'US'`),-// and `Spree::MarketCountry#country_unique_per_store` rejects re-assigning-// a country to a second market in the same store. So every test below picks-// from countries *not* already covered by the seeded US market, drawing from-// the North America + EU_VAT shipping zones seeded in `global-setup.ts`.+// plus a EUR market anchored to `Germany` (so the store is multi-currency —+// see `global-setup.ts`). `Spree::MarketCountry#country_unique_per_store`+// rejects re-assigning a country to a second market in the same store, so+// every test below picks from countries *not* already covered by the US or+// EUR markets — i.e. avoid `US`/`Germany`, drawing from the North America ++// EU_VAT shipping zones seeded in `global-setup.ts`.test.describe('markets', () => {test('lists markets', async ({ page }) => {const creds = await login(page)@@ -57,7 +59,8 @@ test.describe('markets', () => {const original = `E2E Edit Market ${suffix}`const updated = `${original} (updated)`- await createMarket(page, { name: original, countries: ['Germany'] })+ // Austria, not Germany — the seeded EUR market already owns Germany.+ await createMarket(page, { name: original, countries: ['Austria'] })await expect(rowButton(page, original)).toBeVisible({ timeout: 15_000 })await rowButton(page, original).click()diff --git a/packages/dashboard/e2e/price-lists.spec.ts b/packages/dashboard/e2e/price-lists.spec.tsindex 137aeae7bb..a157532ea7 100644--- a/packages/dashboard/e2e/price-lists.spec.ts+++ b/packages/dashboard/e2e/price-lists.spec.ts@@ -301,8 +301,11 @@ test.describe('price lists', () => {await pickProductOnPage(page, FIXTURE_PROMO_PRODUCT)await expect(page.getByText(/1 product selected/i)).toBeVisible({ timeout: 5_000 })await saveForm(page)- // Card-counter help text updates once the placeholder price exists.- await expect(page.getByText(/price configured/i)).toBeVisible({ timeout: 15_000 })+ // Card-counter help text updates once placeholder prices exist. A+ // multi-currency store creates one placeholder per currency, so the+ // count is "N prices configured" (singular when the store has one+ // currency) — match either form.+ await expect(page.getByText(/\d+ price(s)? configured/i)).toBeVisible({ timeout: 15_000 })await openBulkPriceEditor(page)@@ -342,6 +345,61 @@ test.describe('price lists', () => {).toHaveValue('33.33')})+ // Multi-currency: the bulk editor scopes its grid to one currency at a time+ // via the header currency selector. Edit + save a USD price, switch to EUR,+ // edit + save again, then confirm each currency kept its own value. The e2e+ // store seeds a EUR market alongside USD (see global-setup.ts).+ test('bulk-edits price-list overrides in two currencies', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, PRICE_LISTS_PATH(creds.store_id), CTA)++ const name = `E2E PL Multi-Cur ${Date.now()}`+ await startNewPriceList(page, creds.store_id, name)+ await submitCreate(page, name)++ await pickProductOnPage(page, FIXTURE_PROMO_PRODUCT)+ await expect(page.getByText(/1 product selected/i)).toBeVisible({ timeout: 5_000 })+ await saveForm(page)+ await expect(page.getByText(/\d+ price(s)? configured/i)).toBeVisible({ timeout: 15_000 })++ await openBulkPriceEditor(page)+ const dialog = page.getByRole('dialog')+ // The editor opens on the store default currency (USD).+ const currencyTrigger = dialog.getByRole('combobox').first()+ await expect(currencyTrigger).toContainText('USD')++ const priceCell = () => dialog.getByLabel(/^price for/i).first()+ await expect(priceCell()).toBeVisible({ timeout: 15_000 })+ await priceCell().dblclick()+ await priceCell().fill('40.00')+ await priceCell().press('Enter')+ await dialog.getByRole('button', { name: /^save prices$/i }).click()+ 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).+ await currencyTrigger.click()+ await page.getByRole('option', { name: 'EUR' }).click()+ await expect(currencyTrigger).toContainText('EUR')++ await priceCell().dblclick()+ await priceCell().fill('55,55')+ await priceCell().press('Enter')+ await dialog.getByRole('button', { name: /^save prices$/i }).click()+ await expect(dialog.getByText(/unsaved change/i)).toBeHidden({ timeout: 15_000 })+ // Round-trips as the comma-decimal `55,55`, proving locale-aware parsing.+ await expect(priceCell()).toHaveValue('55,55')++ // Switch back to USD — its value is independent of the EUR edit and shown+ // period-decimal.+ await currencyTrigger.click()+ await page.getByRole('option', { name: 'USD' }).click()+ await expect(currencyTrigger).toContainText('USD')+ // Period-decimal; the grid trims trailing zeros (40.00 → 40.0).+ await expect(priceCell()).toHaveValue(/^40[.,]0+$/)+ })+// Skip on CI: the dblclick→fill→blur pattern flakes against the fixture// product's seeded `33.33` price. The same code path (PricesCard inline// editing + product-form Save round-trip) is exercised on a fresh productdiff --git a/packages/dashboard/e2e/products-prices-inventory.spec.ts b/packages/dashboard/e2e/products-prices-inventory.spec.tsindex b63632bcd2..ddf4341bfa 100644--- a/packages/dashboard/e2e/products-prices-inventory.spec.ts+++ b/packages/dashboard/e2e/products-prices-inventory.spec.ts@@ -112,7 +112,90 @@ test.describe('product prices — single variant', () => {await page.reload()await expect(pricesCard(page).getByRole('textbox', { name: /^price for default$/i }),- ).toHaveValue(/^12[.,]5/)+ ).toHaveValue(/^12[.,]50?$/)+ })++ // Multi-currency + localized. The inline Prices card switches currency via+ // its header selector; each currency's prices ride the SAME product PATCH.+ // Enter a USD price (period) and a EUR price comma-decimal (`34,56`), save+ // once, and confirm each round-trips in its own currency/locale — proving the+ // per-currency client-side normalization in the batched product update.+ test('sets prices in two currencies (USD period + EUR comma) in one save', async ({ page }) => {+ const creds = await login(page)++ const productName = `E2E Prices Multi-Cur ${Date.now()}`+ await createProduct(page, creds.store_id, productName)++ const card = pricesCard(page)+ // USD default — period decimal.+ await fillGridCell(card.getByRole('textbox', { name: /^price for default$/i }), '12.50')++ // Switch the Prices card to EUR; the grid formats in the EUR market locale+ // (de: comma decimal). Enter `34,56` → must persist as 34.56.+ await card.getByRole('combobox').first().click()+ await page.getByRole('option', { name: 'EUR' }).click()+ await fillGridCell(card.getByRole('textbox', { name: /^price for default$/i }), '34,56')++ await page.getByRole('button', { name: /save product/i }).click()+ await expect(page.getByRole('button', { name: /save product/i })).toBeDisabled({+ timeout: 30_000,+ })++ await page.reload()+ const reloaded = pricesCard(page)+ // EUR cell is shown after reload (card defaults back to USD); switch to EUR+ // and confirm the comma-decimal value persisted as 34,56 (not 3456).+ await reloaded.getByRole('combobox').first().click()+ await page.getByRole('option', { name: 'EUR' }).click()+ await expect(reloaded.getByRole('textbox', { name: /^price for default$/i })).toHaveValue(+ /^34[.,]56$/,+ )+ // Back to USD — independent value.+ await reloaded.getByRole('combobox').first().click()+ await page.getByRole('option', { name: 'USD' }).click()+ await expect(reloaded.getByRole('textbox', { name: /^price for default$/i })).toHaveValue(+ /^12[.,]5/,+ )+ })++ // Regression: a save that includes an UNTOUCHED EUR price must not re-parse+ // it. Form state holds the canonical API value (`34.56`); under the EUR+ // market locale `.` is a thousands separator, so re-normalizing on save would+ // mangle `34.56` → `3456`. Editing a non-price field must leave the EUR price+ // intact.+ test('preserves an untouched EUR price when saving an unrelated field', async ({ page }) => {+ const creds = await login(page)++ const productName = `E2E Untouched EUR ${Date.now()}`+ await createProduct(page, creds.store_id, productName)++ // Set a EUR price comma-decimal and save.+ const card = pricesCard(page)+ await card.getByRole('combobox').first().click()+ await page.getByRole('option', { name: 'EUR' }).click()+ await fillGridCell(card.getByRole('textbox', { name: /^price for default$/i }), '34,56')+ await page.getByRole('button', { name: /save product/i }).click()+ await expect(page.getByRole('button', { name: /save product/i })).toBeDisabled({+ timeout: 30_000,+ })++ await page.reload()++ // Touch ONLY the name — do not open/edit the EUR price cell.+ await page.getByLabel(/^name$/i).fill(`${productName} (edited)`)+ await page.getByRole('button', { name: /save product/i }).click()+ await expect(page.getByRole('button', { name: /save product/i })).toBeDisabled({+ timeout: 30_000,+ })++ await page.reload()+ const reloaded = pricesCard(page)+ await reloaded.getByRole('combobox').first().click()+ await page.getByRole('option', { name: 'EUR' }).click()+ // Still 34,56 — NOT 3.456 / 3456 (which a re-normalize on save would yield).+ await expect(reloaded.getByRole('textbox', { name: /^price for default$/i })).toHaveValue(+ /^34[.,]56$/,+ )})})@@ -291,6 +374,6 @@ test.describe('product variants × prices × inventory', () => {).toHaveValue(/^15([.,]0+)?$/)await expect(pricesCard(page).getByRole('textbox', { name: /^price for .*\bblue$/i }),- ).toHaveValue(/^17[.,]5/)+ ).toHaveValue(/^17[.,]50?$/)})})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.tsxindex 2bb11d6831..3dfc3fbe8f 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@@ -5,8 +5,10 @@ import { useQuery } from '@tanstack/react-query'import { useCallback, useDeferredValue, useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'+import { useCurrencyLocale } from '@/hooks/use-currency-locale'import { useBulkUpsertPrices } from '@/hooks/use-prices'import { currencyParts } from './currency-parts'+import { normalizeMoneyInput } from './normalize-money'const PAGE_SIZE = 50@@ -100,12 +102,13 @@ export function BulkPriceEditor({filter,onStateChange,}: BulkPriceEditorProps) {- const { t, i18n } = useTranslation()+ const { t } = useTranslation()// Destructure the stable handles off `useMutation` (mutateAsync is// stable across renders; the wrapper object is not). Closing over the// wrapper would put a fresh reference in every callback's dep array// and tank the parent via the `onStateChange` effect below.const { mutateAsync: bulkUpsertAsync, isPending: isSaving } = useBulkUpsertPrices()+ const localeForCurrency = useCurrencyLocale()const [page, setPage] = useState(1)const [search, setSearch] = useState('')const deferredSearch = useDeferredValue(search)@@ -113,9 +116,15 @@ export function BulkPriceEditor({const sanitizedFilter = useMemo(() => sanitizeFilter(filter), [filter])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+ // 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'const { symbol, decimal } = useMemo(- () => currencyParts(currency, i18n.language || 'en'),- [currency, i18n.language],+ () => currencyParts(currency, marketLocale),+ [currency, marketLocale],)const { data, isLoading } = useQuery({@@ -246,14 +255,23 @@ 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.map((priceId) => {const edit = edits.get(priceId) as CellEditreturn {variant_id: edit.variantId,currency,...(priceListId ? { price_list_id: priceListId } : {}),- amount: edit.amount,- compare_at_amount: edit.compareAt,+ amount: toCanonical(edit.amount),+ compare_at_amount: toCanonical(edit.compareAt),}})try {@@ -275,7 +293,7 @@ export function BulkPriceEditor({toast.error(message)return false}- }, [edits, currency, priceListId, bulkUpsertAsync, t])+ }, [edits, currency, priceListId, bulkUpsertAsync, marketLocale, t])const discard = useCallback(() => {setEdits(new Map())diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/normalize-money.test.ts b/packages/dashboard/src/components/spree/bulk-price-editor/normalize-money.test.tsnew file mode 100644index 0000000000..d7e3a9f802--- /dev/null+++ b/packages/dashboard/src/components/spree/bulk-price-editor/normalize-money.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest'+import { normalizeMoneyInput } from './normalize-money'++describe('normalizeMoneyInput', () => {+ it('passes through canonical en input', () => {+ expect(normalizeMoneyInput('19.99', 'en')).toBe('19.99')+ expect(normalizeMoneyInput('1,234.56', 'en')).toBe('1234.56')+ expect(normalizeMoneyInput('1234.56', 'en')).toBe('1234.56')+ })++ it('converts de comma-decimal + dot grouping to canonical', () => {+ expect(normalizeMoneyInput('19,99', 'de')).toBe('19.99')+ expect(normalizeMoneyInput('1.234,56', 'de')).toBe('1234.56')+ expect(normalizeMoneyInput('1.000.000,00', 'de')).toBe('1000000.00')+ })++ 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')+ expect(normalizeMoneyInput('73,45', 'fr')).toBe('73.45')+ })++ it('returns empty string for blank input', () => {+ expect(normalizeMoneyInput('', 'de')).toBe('')+ expect(normalizeMoneyInput(' ', 'de')).toBe('')+ expect(normalizeMoneyInput(null, 'de')).toBe('')+ expect(normalizeMoneyInput(undefined, 'de')).toBe('')+ })++ it('preserves a leading minus', () => {+ expect(normalizeMoneyInput('-5,00', 'de')).toBe('-5.00')+ expect(normalizeMoneyInput('-5.00', 'en')).toBe('-5.00')+ })++ it('drops stray currency symbols and whitespace', () => {+ expect(normalizeMoneyInput(' € 1.234,56 ', 'de')).toBe('1234.56')+ expect(normalizeMoneyInput('$19.99', 'en')).toBe('19.99')+ })++ it('keeps no-decimal values intact', () => {+ expect(normalizeMoneyInput('50', 'de')).toBe('50')+ expect(normalizeMoneyInput('1.000', 'de')).toBe('1000') // de: dot is grouping+ expect(normalizeMoneyInput('1,000', 'en')).toBe('1000') // en: comma is grouping+ })++ it('collapses stray separators to a single decimal point', () => {+ // Malformed multi-dot/interior-minus input must canonicalize, not pass through.+ expect(normalizeMoneyInput('1.2.3', 'en')).toBe('1.23')+ expect(normalizeMoneyInput('12-3.4', 'en')).toBe('123.4')+ expect(normalizeMoneyInput('-12-3.4', 'en')).toBe('-123.4')+ })++ it('returns empty for inputs with no digits', () => {+ expect(normalizeMoneyInput('.', 'en')).toBe('')+ expect(normalizeMoneyInput('-', 'en')).toBe('')+ expect(normalizeMoneyInput('abc', 'en')).toBe('')+ })+})diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/normalize-money.ts b/packages/dashboard/src/components/spree/bulk-price-editor/normalize-money.tsnew file mode 100644index 0000000000..d6b291cdfd--- /dev/null+++ b/packages/dashboard/src/components/spree/bulk-price-editor/normalize-money.ts@@ -0,0 +1,73 @@+// Normalize a merchant's locale-formatted money input into the canonical+// decimal string the Admin API expects (`"1234.56"` — period decimal, no+// grouping). Industry-standard: localization is a presentation concern, so the+// dashboard converts here, in the browser, and never relies on the server to+// parse comma-vs-period. See docs/plans/5.5-client-side-money-normalization.md.+//+// The locale is the currency's display locale (its market locale, e.g. EUR →+// `de`), so the same locale drives both display formatting and this parse.++/**+ * Derives a locale's decimal and group separators via `Intl`. `fr` groups with+ * a narrow no-break space (U+202F), so we read the real characters rather than+ * assuming `,`/`.`/`" "`.+ */+function separatorsFor(locale: string): { decimal: string; group: string } {+ try {+ const parts = new Intl.NumberFormat(locale, { useGrouping: true }).formatToParts(11111.1)+ return {+ decimal: parts.find((p) => p.type === 'decimal')?.value ?? '.',+ group: parts.find((p) => p.type === 'group')?.value ?? '',+ }+ } catch {+ return { decimal: '.', group: '' }+ }+}++/**+ * Converts a locale-formatted amount string to a canonical decimal string.+ *+ * - `"1.234,56"` under `de` → `"1234.56"`+ * - `"1 234,56"` under `fr` → `"1234.56"` (narrow-space grouping)+ * - `"19.99"` under `en` → `"19.99"`+ * - `""` / whitespace → `""`+ *+ * Strips the locale's group separator and any whitespace, standardizes the+ * decimal separator to `.`, and drops stray characters. Keeps the value as a+ * string throughout — never `Number()`-coerces — to preserve precision.+ *+ * @param raw the merchant's typed value+ * @param locale the display locale the value was entered in (e.g. `de`)+ * @returns canonical `"1234.56"`-form string, or `''` for blank input+ */+export function normalizeMoneyInput(raw: string | null | undefined, locale: string): string {+ if (raw == null) return ''+ const trimmed = raw.trim()+ if (trimmed === '') return ''++ const { decimal, group } = separatorsFor(locale)++ let out = trimmed+ // 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('')+ out = out.replace(/\s/g, '')+ // Standardize the decimal separator to `.`.+ if (decimal !== '.') out = out.split(decimal).join('.')+ // Drop anything that isn't a digit, dot, or minus.+ out = out.replace(/[^0-9.-]/g, '')++ // Enforce the canonical shape: a single optional leading minus, then digits+ // with at most one decimal point. Stray separators (`1.2.3`) or interior+ // minus signs (`12-3.4`) would otherwise reach the API as malformed values.+ const negative = out.startsWith('-')+ const digitsAndDots = out.replace(/-/g, '')+ const firstDot = digitsAndDots.indexOf('.')+ const canonical =+ firstDot === -1+ ? digitsAndDots+ : `${digitsAndDots.slice(0, firstDot)}.${digitsAndDots.slice(firstDot + 1).replace(/\./g, '')}`++ if (canonical === '' || canonical === '.') return ''+ return negative ? `-${canonical}` : canonical+}diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/product-bulk-price-editor.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/product-bulk-price-editor.tsxindex 091806406f..801f7bffa7 100644--- a/packages/dashboard/src/components/spree/bulk-price-editor/product-bulk-price-editor.tsx+++ b/packages/dashboard/src/components/spree/bulk-price-editor/product-bulk-price-editor.tsx@@ -3,9 +3,11 @@ import { useCallback, useMemo } from 'react'import { type UseFormReturn, useWatch } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { composeOptionsText } from '@/components/spree/products/variants-matrix'+import { useCurrencyLocale } from '@/hooks/use-currency-locale'import { useOptionTypes } from '@/hooks/use-option-types'import type { ProductFormValues, VariantPriceFormValues } from '@/schemas/product'import { currencyParts } from './currency-parts'+import { normalizeMoneyInput } from './normalize-money'interface Props {// eslint-disable-next-line @typescript-eslint/no-explicit-any@@ -31,14 +33,25 @@ interface Props {* price entirely.*/export function ProductBulkPriceEditor({ form, currency, productName }: Props) {- const { t, i18n } = useTranslation()+ const { t } = useTranslation()const variants = useWatch({ control: form.control, name: 'variants' }) ?? []const { data: optionTypesData } = useOptionTypes({ limit: 100 })const optionTypes = useMemo(() => optionTypesData?.data ?? [], [optionTypesData])+ const localeForCurrency = useCurrencyLocale()+ // Format the grid in the currency's market locale (e.g. EUR → `de`, comma+ // decimal). The same locale normalizes the merchant's input back to canonical+ // form on commit (see `handleChange`), so form state — like the API value it+ // hydrates from — is ALWAYS canonical `"1234.56"`. Untouched prices therefore+ // never get re-normalized on save.+ //+ // Fall back to `en` (canonical period-decimal), NOT the UI language: money+ // formatting/parsing must never depend on the dashboard's language, or a USD+ // value under a German UI would be parsed as `40.00` → 4000.+ const marketLocale = localeForCurrency(currency) || 'en'const { symbol, decimal } = useMemo(- () => currencyParts(currency, i18n.language || 'en'),- [currency, i18n.language],+ () => currencyParts(currency, marketLocale),+ [currency, marketLocale],)// Project the form's variants into BulkPriceRow[] for the picked currency.@@ -74,9 +87,14 @@ export function ProductBulkPriceEditor({ form, currency, productName }: Props) {const current = form.getValues(`variants.${idx}.prices`) ?? []const existingIdx = current.findIndex((p) => p.currency === currency)- // Treat empty/whitespace string as "no value"; everything else is- // shipped verbatim to the backend's locale-aware parser.- const raw = next == null || next.trim() === '' ? null : next.trim()+ // Normalize the merchant's localized input to canonical `"1234.56"` here,+ // on commit — so form state is always canonical (matching the API values+ // it hydrates from) and the save path never re-normalizes. Empty,+ // whitespace, OR malformed input (normalizes to `''`) all mean "no value"+ // — never persist `''` as a real amount.+ const trimmed = next == null ? '' : next.trim()+ const normalized = trimmed === '' ? '' : normalizeMoneyInput(trimmed, marketLocale)+ const raw = normalized === '' ? null : normalizedconst nextPrices: VariantPriceFormValues[] = [...current]@@ -112,7 +130,7 @@ export function ProductBulkPriceEditor({ form, currency, productName }: Props) {shouldDirty: true,})},- [form, currency],+ [form, currency, marketLocale],)return (diff --git a/packages/dashboard/src/hooks/use-currency-locale.ts b/packages/dashboard/src/hooks/use-currency-locale.tsnew file mode 100644index 0000000000..03862d9afd--- /dev/null+++ b/packages/dashboard/src/hooks/use-currency-locale.ts@@ -0,0 +1,25 @@+import { useAllMarkets } from './use-markets'++/**+ * Resolves a currency code to the locale used to display and normalize amounts+ * entered in it. Money forms format the field in this locale (so a EUR amount+ * shows/accepts `1.234,56`) and normalize the merchant's input to canonical+ * `"1234.56"` under the same locale before sending — the API only ever receives+ * canonical decimal strings (client-side normalization; the server does not+ * parse locale formats). See docs/plans/5.5-client-side-money-normalization.md.+ *+ * The mapping is the store's markets: each market pairs a `currency` with a+ * `default_locale`. Returns `undefined` when no market matches (callers fall+ * back to the UI language / `en`).+ *+ * @returns a `localeForCurrency(currency)` resolver+ */+export function useCurrencyLocale(): (currency: string | undefined) => string | undefined {+ const { markets } = useAllMarkets()++ return (currency) => {+ if (!currency) return undefined+ const market = markets.find((m) => m.currency === currency)+ return market?.default_locale ?? undefined+ }+}diff --git a/packages/dashboard/src/hooks/use-customer-store-credits.ts b/packages/dashboard/src/hooks/use-customer-store-credits.tsindex d73b5c05ea..e85f04d044 100644--- a/packages/dashboard/src/hooks/use-customer-store-credits.ts+++ b/packages/dashboard/src/hooks/use-customer-store-credits.ts@@ -5,6 +5,9 @@ type StoreCreditUpdateParams = Parameters<typeof adminClient.customers.storeCredexport type { StoreCreditUpdateParams }+// The `amount` arrives already normalized to canonical `"1234.56"` form — the+// form converts the merchant's localized input client-side (see+// docs/plans/5.5-client-side-money-normalization.md), so no request locale.export function useCreateCustomerStoreCredit(customerId: string) {return useResourceMutation({mutationFn: (params: StoreCreditCreateParams) =>diff --git a/packages/dashboard/src/hooks/use-prices.ts b/packages/dashboard/src/hooks/use-prices.tsindex cb9805f8d9..c85c94ce81 100644--- a/packages/dashboard/src/hooks/use-prices.ts+++ b/packages/dashboard/src/hooks/use-prices.ts@@ -7,6 +7,10 @@ import { adminClient, useResourceMutation } from '@spree/dashboard-core'* list "N prices configured" hints, base-price grids on other surfaces)* refetch automatically. Toasts and form-error mapping live in the caller* so the spreadsheet can render its own dirty-state UI on failure.+ *+ * Amounts arrive already normalized to canonical `"1234.56"` form — the editor+ * converts the merchant's localized input client-side (see+ * docs/plans/5.5-client-side-money-normalization.md), so no request locale.*/export function useBulkUpsertPrices() {return useResourceMutation<{ price_count: number }, Error, { prices: PriceBulkUpsertRow[] }>({diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsxindex 0fc7387958..06736e874a 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx@@ -67,7 +67,10 @@ import {import { type ReactNode, useEffect, useMemo, useState } from 'react'import { Controller, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'+import { currencyParts } from '@/components/spree/bulk-price-editor/currency-parts'+import { normalizeMoneyInput } from '@/components/spree/bulk-price-editor/normalize-money'import { CustomFieldsCard } from '@/components/spree/custom-fields/custom-fields-card'+import { useCurrencyLocale } from '@/hooks/use-currency-locale'import {type StoreCreditUpdateParams,useCreateCustomerStoreCredit,@@ -1083,11 +1086,20 @@ function EditStoreCreditDialog({// as a 422 store_credit_in_use.const amountLocked = Number(credit.amount_used ?? 0) > 0+ const localeForCurrency = useCurrencyLocale()+ // Currency is locked on edit, so resolve its market locale once. The amount+ // hydrates from the canonical API value (`"50.00"`) but is displayed/edited+ // in that locale's format (`"50,00"` for EUR); on submit we normalize back to+ // canonical. Displaying in the same locale we normalize from keeps an+ // untouched amount from being mangled on save.+ const creditLocale = localeForCurrency(credit.currency) || 'en'+ const { decimal } = currencyParts(credit.currency, creditLocale)+const form = useForm<EditStoreCreditFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(editStoreCreditFormSchema) as any,defaultValues: {- amount: credit.amount ?? '',+ amount: credit.amount ? credit.amount.replace('.', decimal) : '',category_id: credit.category_id ?? '',memo: credit.memo ?? '',},@@ -1101,9 +1113,11 @@ function EditStoreCreditDialog({if (!amountLocked) {const amountValue = values.amount.toString().trim()- // Ship the raw string — the backend's LocalizedNumber.parse handles- // decoding. Number() would mangle localized input like "1.234,56" to NaN.- if (amountValue) params.amount = amountValue+ // Normalize from the credit's display locale to the canonical+ // `"1234.56"` the API expects.+ if (amountValue) {+ params.amount = normalizeMoneyInput(amountValue, creditLocale)+ }}if (values.category_id.trim()) params.category_id = values.category_id@@ -1229,6 +1243,7 @@ function IssueStoreCreditDialog({const { errors } = form.formStateconst mutation = useCreateCustomerStoreCredit(customerId)+ const localeForCurrency = useCurrencyLocale()// Clear any prior submission state when the dialog re-opens so a fresh form// is presented (otherwise stale "Issue $20" values linger across opens).@@ -1238,14 +1253,32 @@ function IssueStoreCreditDialog({}}, [open, form, defaultCurrency])+ // Switching currency re-displays the amount in the new currency's locale+ // format, so the value the merchant sees always matches the locale it will be+ // normalized under on submit. Without this, `25.00` typed under USD would be+ // re-read under EUR's `de` locale (where `.` groups thousands) and persist as+ // 2500. Canonicalize from the old locale, then swap to the new locale's+ // decimal separator.+ function handleCurrencyChange(+ next: string,+ field: { value: string; onChange: (v: string) => void },+ ) {+ const prev = field.value+ field.onChange(next)+ const raw = form.getValues('amount')?.trim()+ if (!raw) return+ const canonical = normalizeMoneyInput(raw, localeForCurrency(prev) || 'en')+ const { decimal } = currencyParts(next, localeForCurrency(next) || 'en')+ form.setValue('amount', decimal === '.' ? canonical : canonical.replace('.', decimal))+ }+async function onSubmit(values: IssueStoreCreditFormValues) {try {await mutation.mutateAsync({- // Ship the raw merchant-typed amount. The backend's- // `Spree::LocalizedNumber.parse` handles locale-aware parsing- // (comma decimals, grouped digits, etc.); coercing here would- // silently mangle inputs like "1.234,56" into NaN.- amount: values.amount,+ // Normalize the merchant's localized input (entered under the selected+ // currency's market locale) to the canonical `"1234.56"` the API+ // expects. The server never parses comma-vs-period.+ amount: normalizeMoneyInput(values.amount, localeForCurrency(values.currency) || 'en'),currency: values.currency,category_id: values.category_id,memo: values.memo || undefined,@@ -1299,7 +1332,7 @@ function IssueStoreCreditDialog({<CurrencySelectid="sc-currency"value={field.value || ''}- onChange={field.onChange}+ onChange={(next) => handleCurrencyChange(next, field)}required/>)}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsxindex bb7439c8bf..e34385f4e3 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -179,6 +179,12 @@ export function variantToWirePayload(v: VariantFormValues, index: number) {// backend's `Spree::Variant#prices=` treats an empty array as "clear all// base prices"; omitting it would otherwise leave the old amounts in// place when the merchant clears the last currency from the matrix.+ //+ // Amounts in form state are already canonical `"1234.56"` — the price editor+ // normalizes the merchant's localized input on commit (see+ // `ProductBulkPriceEditor#handleChange`), and untouched values hydrate from+ // the canonical API. So no normalization here — re-normalizing a canonical+ // value under a comma-decimal locale would mangle it (`34.56` → `3456`).if (v.prices != null) payload.prices = v.pricesif (v.stock_items?.length) {payload.stock_items = v.stock_items.map(({ stock_location_name, ...rest }) => rest)diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsxindex 2eeea5b6c2..ba05993e1f 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx@@ -115,8 +115,10 @@ function NewProductPage() {// eslint-disable-next-line @typescript-eslint/no-explicit-any;(payload as any).variants = [variantToWirePayload(v, 0)]} else if (v.prices?.length) {+ // Top-level `prices` shorthand (simple product). Amounts are already+ // canonical — the price editor normalizes on commit.// eslint-disable-next-line @typescript-eslint/no-explicit-any- ;(payload as any).prices = v.prices+ ;(payload as any).prices = v.prices.filter((p) => p.currency != null)}} else if (meaningful.length > 0) {// eslint-disable-next-line @typescript-eslint/no-explicit-anydiff --git a/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rbindex 7226dc504f..fd0d787f86 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb@@ -222,49 +222,21 @@ RSpec.describe Spree::Api::V3::Admin::PricesController, type: :controller doendend- context 'when amounts are locale-formatted strings' do- # `Spree::LocalizedNumber.parse` is locale-aware: en-US uses- # `.` for the decimal and `,` for the thousands delimiter; many- # EU locales swap them. The bulk endpoint must handle either- # without coercing to zero.-- it 'parses en-US style "1,234.56" correctly' do- I18n.with_locale(:en) do- post :bulk_upsert,- params: {- prices: [{- variant_id: variant.prefixed_id,- currency: 'USD',- price_list_id: price_list.prefixed_id,- amount: '1,234.56'- }]- },- as: :json- end-- expect(response).to have_http_status(:ok)- row = Spree::Price.find_by(- variant_id: variant.id, currency: 'USD', price_list_id: price_list.id- )- expect(row.amount).to eq(BigDecimal('1234.56'))- end-- it 'parses an alternate-locale "1.234,56" correctly' do- # Stub the i18n format directly rather than switching locales —- # not every test env loads non-English locale files, and we're- # testing the parser's locale-awareness, not Spree's translations.- allow(I18n).to receive(:t).and_call_original- allow(I18n).to receive(:t).with(- [:'number.currency.format.separator', :'number.currency.format.delimiter']- ).and_return([',', '.'])-+ context 'with canonical decimal-string amounts' do+ # The Admin API contract is canonical decimal strings (`"1234.56"` —+ # period decimal, no grouping), independent of locale. Clients (the+ # dashboard) normalize any localized input client-side before sending;+ # the API is not asked to parse comma-vs-period. See+ # docs/plans/5.5-client-side-money-normalization.md.+ it 'upserts amount and compare_at_amount as canonical strings' dopost :bulk_upsert,params: {prices: [{variant_id: variant.prefixed_id,currency: 'EUR',price_list_id: price_list.prefixed_id,- amount: '1.234,56'+ amount: '1234.56',+ compare_at_amount: '149.99'}]},as: :json@@ -274,31 +246,6 @@ RSpec.describe Spree::Api::V3::Admin::PricesController, type: :controller dovariant_id: variant.id, currency: 'EUR', price_list_id: price_list.id)expect(row.amount).to eq(BigDecimal('1234.56'))- end-- it 'parses compare_at_amount in the same locale as amount' do- allow(I18n).to receive(:t).and_call_original- allow(I18n).to receive(:t).with(- [:'number.currency.format.separator', :'number.currency.format.delimiter']- ).and_return([',', '.'])-- post :bulk_upsert,- params: {- prices: [{- variant_id: variant.prefixed_id,- currency: 'EUR',- price_list_id: price_list.prefixed_id,- amount: '99,99',- compare_at_amount: '149,99'- }]- },- as: :json-- expect(response).to have_http_status(:ok)- row = Spree::Price.find_by(- variant_id: variant.id, currency: 'EUR', price_list_id: price_list.id- )- expect(row.amount).to eq(BigDecimal('99.99'))expect(row.compare_at_amount).to eq(BigDecimal('149.99'))endenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rbindex b050451137..9f5aca800f 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb@@ -558,7 +558,14 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller doexpect(eur.compare_at_amount).to eq(13.99)end- it 'accepts amounts as strings (the documented form, symmetric with reads)' do+ # The Admin API contract is canonical decimal strings (`"29.99"`, period+ # decimal). Clients (the dashboard) normalize localized input+ # client-side before sending — the API is not asked to parse comma-vs-+ # period. See docs/plans/5.5-client-side-money-normalization.md. (The+ # models still tolerate localized input for the legacy Rails admin, but+ # that is not part of the Admin API contract and is covered by the+ # `Spree::LocalizedNumber` unit specs.)+ it 'accepts amounts as canonical decimal strings (symmetric with reads)' dopost :create, params: {name: 'String Price Product',prices: [@@ -573,34 +580,6 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller doendend- context 'with localized prices (comma-decimal under a non-English locale)' do- # A `de`-style locale formats money as `1.299,00` — comma decimal, dot- # thousands. We stub only the separator/delimiter lookup that- # `Spree::LocalizedNumber.parse` reads, rather than flipping the whole- # request locale (which would route the translated `name` attribute to a- # missing `de` Mobility translation and leave the base column NULL).- before do- allow(I18n).to receive(:t).and_call_original- allow(I18n).to receive(:t).- with([:'number.currency.format.separator', :'number.currency.format.delimiter']).- and_return([',', '.'])- end-- it 'parses comma-decimal amounts via LocalizedNumber' do- post :create, params: {- name: 'Localized Price Product',- prices: [- { currency: 'EUR', amount: '39,99', compare_at_amount: '1.299,00' }- ]- }, as: :json-- expect(response).to have_http_status(:created)- price = Spree::Product.find_by(name: 'Localized Price Product').master.prices.find_by(currency: 'EUR')- expect(price.amount).to eq(39.99)- expect(price.compare_at_amount).to eq(1299.00)- end- end-context 'with inline media' dolet(:blob) doActiveStorage::Blob.create_and_upload!(