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
Fix delivery method amounts shown in the wrong currency (#14531)
Damian Legawiecbd23287e8052
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx b/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsxindex 4edfd093a7..6ca02efaf6 100644--- a/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx+++ b/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx@@ -58,6 +58,7 @@ import {import { useIntegrations, useIntegrationTypes } from '../../../hooks/use-integrations'import { productAutocompleteProps } from '../../../hooks/use-products'import { useTaxCategories } from '../../../hooks/use-tax-categories'+import { amountForCurrency, applyCurrencyAmount } from '../../../lib/delivery-method-summary'import type { DeliveryMethodFormValues } from '../../../schemas/delivery-method'import { ConfigureIntegrationSheet } from '../integrations/configure-integration-sheet'import { StockLocationScopeField } from './stock-location-scope-field'@@ -76,8 +77,8 @@ const AMOUNT_BASED_CALCULATORS = [/*** Preference keys the per-currency editor owns on those calculators. `amount`- * and `currency` are the pre-6.0 single-currency pair, kept authoritative for- * the store's default currency so an upgraded store quotes unchanged.+ * and `currency` are the pre-6.0 single-currency pair: they belong to the+ * currency the method names, not automatically to the store default.*/const CURRENCY_AMOUNT_KEYS = ['amount', 'currency', 'amounts']@@ -901,10 +902,10 @@ function ServiceOverridesSheet({/*** The amount an amount-based calculator charges, one input per currency the- * store sells in. The default currency writes the legacy single `amount`- * preference, so an upgraded store keeps quoting from the value it already- * had; every other currency lives in the `amounts` hash. A currency left- * blank has no amount, and the method is simply not offered to those carts.+ * store sells in. Each row shows the amount for that currency — the+ * per-currency `amounts` hash, or the pre-6.0 single `amount` when its+ * `currency` preference names this row. A currency left blank has no+ * amount, and the method is simply not offered to those carts.** A single-currency store sees one plain amount field, exactly as before.*/@@ -932,24 +933,12 @@ function CurrencyAmountsField({const multiCurrency = codes.length > 1function amountFor(code: string): string {- const raw = code === defaultCurrency ? values.amount : amounts[code]- return raw === null || raw === undefined ? '' : String(raw)+ const raw = amountForCurrency(values, code, defaultCurrency)+ return raw === null ? '' : String(raw)}function setAmount(code: string, raw: string) {- if (code === defaultCurrency) {- onChange({ ...values, amount: raw === '' ? null : Number(raw) })- return- }- const nextAmounts = { ...amounts }- // An empty input is the absence of an amount, not a zero — a zero would- // offer the method free of charge in that currency.- if (raw === '') {- delete nextAmounts[code]- } else {- nextAmounts[code] = Number(raw)- }- onChange({ ...values, amounts: nextAmounts })+ onChange(applyCurrencyAmount(values, code, raw, defaultCurrency))}return (diff --git a/packages/dashboard/src/components/spree/shipping/delivery-method-list.tsx b/packages/dashboard/src/components/spree/shipping/delivery-method-list.tsxindex 5d6835933b..22f88cff60 100644--- a/packages/dashboard/src/components/spree/shipping/delivery-method-list.tsx+++ b/packages/dashboard/src/components/spree/shipping/delivery-method-list.tsx@@ -14,7 +14,7 @@ import {useDeleteDeliveryMethod,useDeliveryRateProviders,} from '../../../hooks/use-delivery-methods'-import { flatAmount, formatAmount, summarizeRules } from '../../../lib/delivery-method-summary'+import { formatListedPrice, summarizeRules } from '../../../lib/delivery-method-summary'import { useMethodSheetNavigation } from './use-method-sheet-navigation'export function DeliveryMethodList({@@ -69,12 +69,15 @@ export function DeliveryMethodList({const carrierPriced = rateProvider? rateProvider.uses_calculator === false: !!method.rate_provider && method.rate_provider !== defaultRateProvider- const amount = flatAmount(method.calculator_preferences)const price = carrierPriced? t('admin.delivery_methods.carrier_rates')- : amount === null || amount === 0- ? t('admin.delivery_methods.free')- : formatAmount(amount, defaultCurrency, i18n.language)+ : formatListedPrice(+ method.calculator_preferences,+ defaultCurrency,+ i18n.language,+ t('admin.delivery_methods.free'),+ t('admin.delivery_methods.rule_summary.separator'),+ )const ruleSummary = summarizeRules(method.rules, {t,diff --git a/packages/dashboard/src/lib/delivery-method-summary.test.ts b/packages/dashboard/src/lib/delivery-method-summary.test.tsnew file mode 100644index 0000000000..17064c611e--- /dev/null+++ b/packages/dashboard/src/lib/delivery-method-summary.test.ts@@ -0,0 +1,155 @@+import { describe, expect, it } from 'vitest'+import {+ amountForCurrency,+ applyCurrencyAmount,+ formatListedPrice,+ listedAmounts,+} from './delivery-method-summary'++describe('listedAmounts', () => {+ it('reads the legacy single amount as the store default currency', () => {+ expect(listedAmounts({ amount: 5 }, 'USD')).toEqual([{ amount: 5, currency: 'USD' }])+ })++ it('attributes the legacy amount to its own currency preference', () => {+ expect(listedAmounts({ amount: 7, currency: 'EUR' }, 'USD')).toEqual([+ { amount: 7, currency: 'EUR' },+ ])+ })++ it('reads a non-default currency from the amounts hash when the default is empty', () => {+ expect(listedAmounts({ amounts: { EUR: 7 } }, 'USD')).toEqual([{ amount: 7, currency: 'EUR' }])+ })++ it('reads the editor-written hash even when the single amount is zero', () => {+ expect(listedAmounts({ amount: 0, amounts: { EUR: 11 } }, 'USD')).toEqual([+ { amount: 0, currency: 'USD' },+ { amount: 11, currency: 'EUR' },+ ])+ })++ it('keeps each hash amount against the currency it was entered in', () => {+ expect(listedAmounts({ amounts: { GBP: 8, EUR: 7 } }, 'USD')).toEqual([+ { amount: 7, currency: 'EUR' },+ { amount: 8, currency: 'GBP' },+ ])+ })++ it('lists the default-currency amount first when both sources have a price', () => {+ expect(listedAmounts({ amount: 5, amounts: { EUR: 7 } }, 'USD')).toEqual([+ { amount: 5, currency: 'USD' },+ { amount: 7, currency: 'EUR' },+ ])+ })++ it('lets the amounts hash override the legacy amount for the same currency', () => {+ expect(listedAmounts({ amount: 5, amounts: { USD: 6, EUR: 7 } }, 'USD')).toEqual([+ { amount: 6, currency: 'USD' },+ { amount: 7, currency: 'EUR' },+ ])+ })++ it('ignores blank hash entries so an emptied currency is not offered', () => {+ expect(listedAmounts({ amounts: { EUR: '', GBP: 8 } }, 'USD')).toEqual([+ { amount: 8, currency: 'GBP' },+ ])+ })+})++describe('formatListedPrice', () => {+ const separator = ' · '++ it('formats a default-currency amount with that currency symbol', () => {+ expect(formatListedPrice({ amount: 5 }, 'USD', 'en', 'Free', separator)).toBe('$5.00')+ })++ it('formats an EUR-only method with a euro sign, not the store default symbol', () => {+ expect(formatListedPrice({ amounts: { EUR: 7 } }, 'USD', 'en', 'Free', separator)).toBe('€7.00')+ })++ it('formats a GBP-only method with a pound sign', () => {+ expect(formatListedPrice({ amounts: { GBP: 8 } }, 'USD', 'en', 'Free', separator)).toBe('£8.00')+ })++ it('joins one price per stored currency', () => {+ expect(+ formatListedPrice({ amount: 5, amounts: { EUR: 7 } }, 'USD', 'en', 'Free', separator),+ ).toBe('$5.00 · €7.00')+ })++ it('reads an empty or zero-only method as free', () => {+ expect(formatListedPrice({}, 'USD', 'en', 'Free', separator)).toBe('Free')+ expect(formatListedPrice({ amount: 0 }, 'USD', 'en', 'Free', separator)).toBe('Free')+ expect(formatListedPrice({ amounts: { EUR: 0 } }, 'USD', 'en', 'Free', separator)).toBe('Free')+ })++ it('does not read a zero single amount as free when the hash has a real price', () => {+ expect(+ formatListedPrice({ amount: 0, amounts: { EUR: 11 } }, 'USD', 'en', 'Free', separator),+ ).toBe('€11.00')+ })+})++describe('amountForCurrency', () => {+ it('puts a pre-6.0 euro amount in the euro row, not the store default', () => {+ const preferences = { amount: 7, currency: 'EUR' }+ expect(amountForCurrency(preferences, 'EUR', 'USD')).toBe(7)+ expect(amountForCurrency(preferences, 'USD', 'USD')).toBeNull()+ })++ it('reads an editor-written euro price from the amounts hash', () => {+ const preferences = { amount: 0, amounts: { EUR: 11 } }+ expect(amountForCurrency(preferences, 'EUR', 'USD')).toBe(11)+ expect(amountForCurrency(preferences, 'USD', 'USD')).toBe(0)+ })++ it('treats a blank currency preference as the store default', () => {+ expect(amountForCurrency({ amount: 5 }, 'USD', 'USD')).toBe(5)+ expect(amountForCurrency({ amount: 5 }, 'EUR', 'USD')).toBeNull()+ })++ it('trims surrounding space on the legacy currency preference', () => {+ const preferences = { amount: 7, currency: ' EUR ' }+ expect(amountForCurrency(preferences, 'EUR', 'USD')).toBe(7)+ expect(amountForCurrency(preferences, 'USD', 'USD')).toBeNull()+ })++ it('reads a lowercase amounts-hash key as that currency', () => {+ expect(amountForCurrency({ amounts: { eur: 7 } }, 'EUR', 'USD')).toBe(7)+ })+})++describe('applyCurrencyAmount', () => {+ it('keeps a pre-6.0 euro price when the dollar row is edited', () => {+ expect(applyCurrencyAmount({ amount: 7, currency: 'EUR' }, 'USD', '10', 'USD')).toEqual({+ amount: 10,+ currency: 'USD',+ amounts: { EUR: 7 },+ })+ })++ it('updates the named currency in place on a pre-6.0 method', () => {+ expect(applyCurrencyAmount({ amount: 7, currency: 'EUR' }, 'EUR', '11', 'USD')).toEqual({+ amount: 11,+ currency: 'EUR',+ amounts: { EUR: 11 },+ })+ })++ it('writes a non-default currency into the amounts hash', () => {+ expect(applyCurrencyAmount({ amount: 5, currency: 'USD' }, 'EUR', '11', 'USD')).toEqual({+ amount: 5,+ currency: 'USD',+ amounts: { EUR: 11 },+ })+ })++ it('updates and clears a lowercase stored hash key without leaving a stale entry', () => {+ expect(applyCurrencyAmount({ amounts: { eur: 7 } }, 'EUR', '11', 'USD')).toEqual({+ amounts: { EUR: 11 },+ })+ expect(applyCurrencyAmount({ amounts: { eur: 7 } }, 'EUR', '', 'USD')).toEqual({+ amounts: {},+ })+ })+})diff --git a/packages/dashboard/src/lib/delivery-method-summary.ts b/packages/dashboard/src/lib/delivery-method-summary.tsindex ce3240d44c..d370b5a92a 100644--- a/packages/dashboard/src/lib/delivery-method-summary.ts+++ b/packages/dashboard/src/lib/delivery-method-summary.ts@@ -1,19 +1,182 @@import type { DeliveryMethodRule } from '@spree/admin-sdk'import type { TFunction } from 'i18next'+function toNumber(value: unknown): number | null {+ if (value === null || value === undefined || value === '') return null+ const parsed = Number(value)+ return Number.isNaN(parsed) ? null : parsed+}++/** One stored delivery amount and the ISO currency it was entered in. */+export type ListedAmount = {+ amount: number+ currency: string+}++function amountsHash(+ preferences: Record<string, unknown> | null | undefined,+): Record<string, unknown> {+ const amounts = preferences?.amounts+ if (!amounts || typeof amounts !== 'object' || Array.isArray(amounts)) return {}+ return amounts as Record<string, unknown>+}++function hashKey(amounts: Record<string, unknown>, currency: string): string | undefined {+ const code = currency.toUpperCase()+ return Object.keys(amounts).find((key) => key.toUpperCase() === code)+}++function hashEntry(amounts: Record<string, unknown>, currency: string): unknown {+ const key = hashKey(amounts, currency)+ return key === undefined ? undefined : amounts[key]+}++function writeHashAmount(+ amounts: Record<string, unknown>,+ currency: string,+ value: number | null,+): void {+ const existing = hashKey(amounts, currency)+ if (existing !== undefined) delete amounts[existing]+ if (value !== null) amounts[currency.toUpperCase()] = value+}++/** The currency the pre-6.0 single `amount` belongs to. */+function legacyCurrency(+ preferences: Record<string, unknown> | null | undefined,+ defaultCurrency: string,+): string {+ if (typeof preferences?.currency === 'string' && preferences.currency.trim() !== '') {+ return preferences.currency.trim().toUpperCase()+ }+ return defaultCurrency.toUpperCase()+}++/**+ * The amount a calculator-priced method quotes for one currency — the same+ * order the calculator uses. The per-currency `amounts` hash wins; the+ * legacy single `amount` fills in only for its own currency (the `currency`+ * preference, or the store default when that preference is blank).+ *+ * A pre-6.0 method that names EUR therefore returns 7 for EUR and nothing+ * for USD. Reading the single amount as the store default is how a euro+ * figure appeared in the dollar row of the editor.+ */+export function amountForCurrency(+ preferences: Record<string, unknown> | null | undefined,+ currency: string,+ defaultCurrency: string,+): number | null {+ const code = currency.toUpperCase()+ const fromHash = hashEntry(amountsHash(preferences), code)+ if (fromHash !== undefined && fromHash !== null && fromHash !== '') {+ return toNumber(fromHash)+ }++ if (legacyCurrency(preferences, defaultCurrency) !== code) return null+ return toNumber(preferences?.amount)+}++/**+ * Writes one currency's amount the way the delivery-method editor does,+ * without moving a price that belongs to another currency.+ *+ * The default-currency row owns the legacy `amount` + `currency` pair. When+ * that pair still names a different currency (a pre-6.0 EUR price), the+ * existing figure is copied into the `amounts` hash first so typing in the+ * dollar row cannot overwrite the euro price.+ */+export function applyCurrencyAmount(+ preferences: Record<string, unknown>,+ currency: string,+ raw: string,+ defaultCurrency: string,+): Record<string, unknown> {+ const code = currency.toUpperCase()+ const defaultCode = defaultCurrency.toUpperCase()+ const parsed = raw === '' ? null : toNumber(raw)+ const nextAmounts = { ...amountsHash(preferences) }+ const namedCurrency = legacyCurrency(preferences, defaultCurrency)++ if (namedCurrency !== code && namedCurrency !== defaultCode) {+ const existing = amountForCurrency(preferences, namedCurrency, defaultCurrency)+ if (existing !== null && hashEntry(nextAmounts, namedCurrency) === undefined) {+ nextAmounts[namedCurrency] = existing+ }+ }++ if (code === defaultCode) {+ if (hashKey(nextAmounts, code) !== undefined) {+ writeHashAmount(nextAmounts, code, parsed)+ }+ return {+ ...preferences,+ amount: parsed,+ currency: defaultCurrency,+ amounts: nextAmounts,+ }+ }++ writeHashAmount(nextAmounts, code, parsed)++ if (namedCurrency === code) {+ return { ...preferences, amount: parsed, amounts: nextAmounts }+ }++ return { ...preferences, amounts: nextAmounts }+}++/**+ * Every amount a calculator-priced method quotes, each with the currency it+ * belongs to. The per-currency `amounts` hash is the source of truth; the+ * legacy single `amount` fills in for its own currency (the `currency`+ * preference, or the store default) when the hash has no entry there.+ *+ * A method priced only in a non-default currency therefore returns that+ * currency's row, not a number that the caller would stamp with the store+ * default's symbol.+ */+export function listedAmounts(+ preferences: Record<string, unknown> | null | undefined,+ defaultCurrency: string,+): ListedAmount[] {+ const listed: ListedAmount[] = []+ const seen = new Set<string>()+ const defaultCode = defaultCurrency.toUpperCase()++ for (const [code, value] of Object.entries(amountsHash(preferences))) {+ const parsed = toNumber(value)+ if (parsed === null) continue+ const currency = code.toUpperCase()+ listed.push({ amount: parsed, currency })+ seen.add(currency)+ }++ const legacyAmount = toNumber(preferences?.amount)+ if (legacyAmount !== null) {+ const named = legacyCurrency(preferences, defaultCurrency)+ if (!seen.has(named)) {+ listed.push({ amount: legacyAmount, currency: named })+ }+ }++ return listed.sort((left, right) => {+ if (left.currency === defaultCode) return -1+ if (right.currency === defaultCode) return 1+ return left.currency.localeCompare(right.currency)+ })+}+/*** The flat amount a calculator-priced method charges, or null when it is* priced some other way (per item, tiered, per carrier quote) and has no- * single number to show.+ * single number to show. Prefer `listedAmounts` when the currency matters.*/export function flatAmount(preferences: Record<string, unknown> | null | undefined): number | null {- const amount = preferences?.amount- if (amount === null || amount === undefined || amount === '') return null- const parsed = Number(amount)- return Number.isNaN(parsed) ? null : parsed+ return toNumber(preferences?.amount)}-/** Formats an amount in the store's currency, falling back to a bare number. */+/** Formats an amount in the given currency, falling back to a bare number. */export function formatAmount(amount: number, currency: string, locale?: string): string {try {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(amount)@@ -22,10 +185,21 @@ export function formatAmount(amount: number, currency: string, locale?: string):}}-function toNumber(value: unknown): number | null {- if (value === null || value === undefined || value === '') return null- const parsed = Number(value)- return Number.isNaN(parsed) ? null : parsed+/**+ * The glance price for a calculator-priced method on the delivery profile+ * list. Each stored amount is formatted in its own currency; zero-only or+ * empty preferences read as free.+ */+export function formatListedPrice(+ preferences: Record<string, unknown> | null | undefined,+ defaultCurrency: string,+ locale: string | undefined,+ freeLabel: string,+ separator: string,+): string {+ const priced = listedAmounts(preferences, defaultCurrency).filter((row) => row.amount !== 0)+ if (priced.length === 0) return freeLabel+ return priced.map((row) => formatAmount(row.amount, row.currency, locale)).join(separator)}interface RuleSummaryContext {