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: Offered delivery methods only in the currencies their amounts name (#14947)

Łukasz Adamczykaebf8832b6f2
diff --git a/.changeset/delivery-amounts-default-currency.md b/.changeset/delivery-amounts-default-currency.md
new file mode 100644
index 0000000000..edfcc79240
--- /dev/null
+++ b/.changeset/delivery-amounts-default-currency.md
@@ -0,0 +1,7 @@
+---
+"@spree/dashboard": patch
+"@spree/dashboard-core": patch
+"@spree/seller-dashboard": patch
+---
+
+A delivery method's amount for the store's default currency is now saved with its other currencies, so leaving it blank means the method isn't offered in that currency, as the form says. Before, a blank default currency was saved as free. The admin dashboard and the seller panel share one per-currency amount editor, `CurrencyAmountsField` in `@spree/dashboard-core`, so sellers can price a method in every currency the marketplace sells in. Both forms ask for an amount in at least one currency.
diff --git a/docs/developer/core-concepts/calculators.mdx b/docs/developer/core-concepts/calculators.mdx
index d5946417fb..9d91cff18b 100644
--- a/docs/developer/core-concepts/calculators.mdx
+++ b/docs/developer/core-concepts/calculators.mdx
@@ -26,12 +26,12 @@ Each calculator takes a few settings — the amount, the percentage, the thresho
| Calculator | What it charges | Settings |
|---|---|---|
-| **Flat rate** | The same amount every time | `amount`, `currency` |
-| **Per item** | An amount for each item in the parcel | `amount`, `currency` |
+| **Flat rate** | The same amount every time | `amounts`, one per currency |
+| **Per item** | An amount for each item in the parcel | `amounts`, one per currency |
| **Percent of item total** | A percentage of what's in the parcel | `flat_percent` |
| **Price sack** | One amount above a threshold, another below — the usual "free delivery over $50" | `minimal_amount`, `discount_amount`, `normal_amount` |
| **Flexi rate** | A charge for the first item, less for each one after | `first_item`, `additional_item`, `max_items` |
-| **Digital delivery** | Nothing, for downloads | — |
+| **Digital delivery** | A charge for downloads, usually nothing | `amounts`, one per currency |
### For promotion discounts
@@ -85,7 +85,7 @@ await adminClient.deliveryMethods.create({
delivery_zone_id: 'dz_xxx',
calculator: {
type: 'flat_rate',
- preferences: { amount: '7.00', currency: 'USD' },
+ preferences: { amounts: { USD: '7.00', EUR: '6.50' } },
},
})
```
@@ -103,8 +103,10 @@ curl 'https://api.mystore.com/api/v3/admin/delivery_methods/calculators' \
Each calculator declares which settings it takes, so a form can be built for it without knowing the calculator in advance — which is how the dashboard renders these.
+An amount-based delivery charge (flat rate, flat rate per item and digital delivery) states one amount per currency in `amounts`, and Spree never converts between them: a delivery method is offered only to carts in a currency it has an amount for. A Spree 5 method priced with a single `amount` and `currency` keeps quoting that currency until `amounts` holds an amount; from then on `amounts` alone decides.
+
<Warning>
-A calculator with an `amount` also has a **currency**. If it doesn't match the order's currency, the calculator contributes nothing rather than converting. Set up one calculator per currency you sell in, or a promotion will silently do nothing for some customers.
+A promotion calculator with an `amount` also has a **currency**. If it doesn't match the order's currency, the calculator contributes nothing rather than converting. Set up one calculator per currency you sell in, or a promotion will silently do nothing for some customers.
</Warning>
## Writing your own
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 836415deff..11c7be0b14 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -2175,6 +2175,15 @@ per-currency carrier accounts). The pricing card renders one amount per
supported store currency; the default currency maps to the legacy amount
preference.
+**Amended 2026-10-21:** `amounts` decides alone once it holds an amount, and
+the dashboard writes the store's default currency into it like every other
+currency. The legacy pair still quotes its own currency, but only while
+`amounts` is empty. Mapping the default currency to the legacy `amount`
+made "left blank" impossible for it: the pair's untouched default (0 in the
+store's currency) read as a price, so a method priced only in euros, through
+the dashboard or the API, was offered free to dollar carts. Upgrades from 5.6
+need no data step: 5.x methods hold only the legacy pair.
+
## 2026-08-09: Fulfillment profiles — ShippingCategory promoted, not removed
Reverses three recorded decisions inside the 6.0 window: "fulfillment types
diff --git a/packages/admin-sdk/src/types/preferences.ts b/packages/admin-sdk/src/types/preferences.ts
index 66eb3b65d5..bff8e3d184 100644
--- a/packages/admin-sdk/src/types/preferences.ts
+++ b/packages/admin-sdk/src/types/preferences.ts
@@ -57,7 +57,7 @@ export type TypedCommissionRule = Narrowed<CommissionRule, CommissionRulePrefere
export type DeliveryCalculatorDigitalDeliveryPreferences = {
amounts: Record<string, string>
/** An amount, as an exact decimal string. */
- amount: string
+ amount: string | null
/** Format: `currency`. */
currency: string
}
@@ -71,7 +71,7 @@ export type DeliveryCalculatorFlatPercentItemTotalPreferences = {
export type DeliveryCalculatorFlatRatePreferences = {
amounts: Record<string, string>
/** An amount, as an exact decimal string. */
- amount: string
+ amount: string | null
/** Format: `currency`. */
currency: string
}
@@ -91,7 +91,7 @@ export type DeliveryCalculatorFlexiRatePreferences = {
export type DeliveryCalculatorPerItemPreferences = {
amounts: Record<string, string>
/** An amount, as an exact decimal string. */
- amount: string
+ amount: string | null
/** Format: `currency`. */
currency: string
}
diff --git a/packages/dashboard-core/src/components/currency-amounts-field.tsx b/packages/dashboard-core/src/components/currency-amounts-field.tsx
new file mode 100644
index 0000000000..ee148ef1d9
--- /dev/null
+++ b/packages/dashboard-core/src/components/currency-amounts-field.tsx
@@ -0,0 +1,93 @@
+import { currencyParts, isCurrencyCode } from '@spree/core'
+import {
+ Field,
+ FieldError,
+ FieldLabel,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ InputGroupText,
+} from '@spree/dashboard-ui'
+import { useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
+import { amountForCurrency, applyCurrencyAmount } from '../lib/currency-amounts'
+
+/**
+ * The amount an amount-based delivery calculator charges, one input per
+ * currency the store sells in, written to the per-currency `amounts`
+ * preference. A currency left blank has no amount, and the method is not
+ * offered to those carts. A single-currency store sees one plain amount
+ * field.
+ */
+export function CurrencyAmountsField({
+ values,
+ onChange,
+ currencies,
+ defaultCurrency,
+ error,
+}: {
+ values: Record<string, unknown>
+ onChange: (next: Record<string, unknown>) => void
+ /** The currencies the store sells in. */
+ currencies: readonly string[]
+ defaultCurrency: string
+ error?: { message?: string }
+}) {
+ const { t, i18n } = useTranslation()
+
+ // The store's currency list is the source of truth, but a method may already
+ // carry an amount in a currency the store has since stopped selling in —
+ // dropping that input would silently discard the amount on the next save.
+ const amounts = (values.amounts ?? {}) as Record<string, unknown>
+ const extraCodes = Object.keys(amounts).join(',')
+ const codes = useMemo(() => {
+ const supported = currencies.length > 0 ? currencies : [defaultCurrency]
+ const extra = extraCodes
+ .split(',')
+ .filter(isCurrencyCode)
+ .filter((code) => !supported.includes(code))
+ return [defaultCurrency, ...supported.filter((code) => code !== defaultCurrency), ...extra]
+ }, [currencies, defaultCurrency, extraCodes])
+
+ const multiCurrency = codes.length > 1
+
+ function amountFor(code: string): string {
+ const raw = amountForCurrency(values, code, defaultCurrency)
+ return raw === null ? '' : String(raw)
+ }
+
+ return (
+ <Field>
+ <FieldLabel htmlFor={`calculator-amount-${defaultCurrency}`}>
+ {t('admin.currency_amounts.label')}
+ </FieldLabel>
+ <div className="flex flex-col gap-2">
+ {codes.map((code) => (
+ <InputGroup key={code}>
+ <InputGroupAddon>
+ <InputGroupText>{currencyParts(code, i18n.language).symbol}</InputGroupText>
+ </InputGroupAddon>
+ <InputGroupInput
+ id={`calculator-amount-${code}`}
+ type="number"
+ step="any"
+ min="0"
+ aria-label={t('admin.currency_amounts.amount_in_currency', { currency: code })}
+ value={amountFor(code)}
+ onChange={(event) =>
+ onChange(applyCurrencyAmount(values, code, event.target.value, defaultCurrency))
+ }
+ />
+ <InputGroupAddon align="inline-end">
+ <InputGroupText>{code}</InputGroupText>
+ </InputGroupAddon>
+ </InputGroup>
+ ))}
+ </div>
+ {multiCurrency && (
+ <span className="text-muted-foreground text-xs">{t('admin.currency_amounts.help')}</span>
+ )}
+ <FieldError errors={[error]} />
+ </Field>
+ )
+}
diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.ts
index cdb4387abb..512abf1100 100644
--- a/packages/dashboard-core/src/index.ts
+++ b/packages/dashboard-core/src/index.ts
@@ -34,6 +34,7 @@ export * from './components/bulk-action-bar'
export * from './components/can'
export * from './components/country-combobox'
export * from './components/country-state-fields'
+export * from './components/currency-amounts-field'
export * from './components/currency-select'
export * from './components/export-button'
export * from './components/file-upload-field'
@@ -88,6 +89,7 @@ export * from './hooks/use-switch-admin-locale'
export * from './hooks/use-visual-viewport-offset'
export * from './lib/cancel-order-form'
export * from './lib/create-action-registry'
+export * from './lib/currency-amounts'
// ---------------------------------------------------------------------------
// Registries — pluggable extension points (nav, route, slot, table,
// settings-nav, form fields, custom field components)
diff --git a/packages/dashboard-core/src/lib/currency-amounts.test.ts b/packages/dashboard-core/src/lib/currency-amounts.test.ts
new file mode 100644
index 0000000000..3634f0eba0
--- /dev/null
+++ b/packages/dashboard-core/src/lib/currency-amounts.test.ts
@@ -0,0 +1,147 @@
+import { describe, expect, it } from 'vitest'
+import {
+ amountForCurrency,
+ applyCurrencyAmount,
+ hasCurrencyAmount,
+ listedAmounts,
+} from './currency-amounts'
+
+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('ignores the single amount once the hash holds an amount, as the server does', () => {
+ expect(listedAmounts({ amount: '0', amounts: { EUR: '11' } }, 'USD')).toEqual([
+ { 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', () => {
+ expect(listedAmounts({ amounts: { EUR: '7', USD: '5' } }, '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('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 only the amounts hash once it holds an amount, so the single amount is not a price', () => {
+ const preferences = { amount: '0', amounts: { EUR: '11' } }
+ expect(amountForCurrency(preferences, 'EUR', 'USD')).toBe('11')
+ expect(amountForCurrency(preferences, 'USD', 'USD')).toBeNull()
+ })
+
+ 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('moves a pre-6.0 euro price into the hash when the dollar row is edited', () => {
+ expect(applyCurrencyAmount({ amount: '7', currency: 'EUR' }, 'USD', '10', 'USD')).toEqual({
+ amount: null,
+ currency: 'EUR',
+ amounts: { EUR: '7', USD: '10' },
+ })
+ })
+
+ it('updates the named currency of a pre-6.0 method in the hash', () => {
+ expect(applyCurrencyAmount({ amount: '7', currency: 'EUR' }, 'EUR', '11', 'USD')).toEqual({
+ amount: null,
+ currency: 'EUR',
+ amounts: { EUR: '11' },
+ })
+ })
+
+ it('writes the store default into the hash like every other currency', () => {
+ expect(applyCurrencyAmount({ amount: '5', currency: 'USD' }, 'EUR', '11', 'USD')).toEqual({
+ amount: null,
+ currency: 'USD',
+ amounts: { USD: '5', EUR: '11' },
+ })
+ expect(applyCurrencyAmount({ amount: null }, 'USD', '9.99', 'USD')).toEqual({
+ amount: null,
+ amounts: { USD: '9.99' },
+ })
+ })
+
+ it('removes a cleared currency, the store default included, so the method is not offered in it', () => {
+ expect(applyCurrencyAmount({ amounts: { USD: '5', EUR: '7' } }, 'USD', '', 'USD')).toEqual({
+ amount: null,
+ amounts: { EUR: '7' },
+ })
+ })
+
+ it('updates and clears a lowercase stored hash key without leaving a stale entry', () => {
+ expect(applyCurrencyAmount({ amounts: { eur: '7' } }, 'EUR', '11', 'USD')).toEqual({
+ amount: null,
+ amounts: { EUR: '11' },
+ })
+ expect(applyCurrencyAmount({ amounts: { eur: '7' } }, 'EUR', '', 'USD')).toEqual({
+ amount: null,
+ amounts: {},
+ })
+ })
+})
+
+describe('hasCurrencyAmount', () => {
+ it('is true for an amount in the hash or a pre-6.0 single amount', () => {
+ expect(hasCurrencyAmount({ amounts: { EUR: '0' } })).toBe(true)
+ expect(hasCurrencyAmount({ amount: '5', amounts: {} })).toBe(true)
+ })
+
+ it('is false when no currency has an amount', () => {
+ expect(hasCurrencyAmount({ amount: null, amounts: { EUR: '' } })).toBe(false)
+ expect(hasCurrencyAmount({})).toBe(false)
+ })
+})
diff --git a/packages/dashboard-core/src/lib/currency-amounts.ts b/packages/dashboard-core/src/lib/currency-amounts.ts
new file mode 100644
index 0000000000..ee61d2f208
--- /dev/null
+++ b/packages/dashboard-core/src/lib/currency-amounts.ts
@@ -0,0 +1,172 @@
+import { isDecimalString } from '@spree/core'
+
+/**
+ * Delivery calculators whose price is a plain amount, quoted per currency
+ * through the `amounts` preference. Every other calculator (percent, tiered)
+ * is currency-neutral.
+ */
+export const AMOUNT_BASED_CALCULATORS: readonly string[] = [
+ 'flat_rate',
+ 'per_item',
+ 'digital_delivery',
+]
+
+/** The preferences the per-currency editor owns on those calculators. */
+export const CURRENCY_AMOUNT_KEYS: readonly string[] = ['amount', 'currency', 'amounts']
+
+/**
+ * A stored preference as a decimal string. The API answers with strings; a
+ * number still sitting in preferences saved before 6.0 is read as its digits.
+ */
+function toDecimal(value: unknown): string | null {
+ const text =
+ typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : ''
+ return isDecimalString(text) ? text : null
+}
+
+/** One stored delivery amount and the ISO currency it was entered in. */
+export type ListedAmount = {
+ amount: string
+ 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: string | 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()
+}
+
+/** Whether the per-currency hash holds an amount: from then on it alone decides. */
+function hasAmounts(amounts: Record<string, unknown>): boolean {
+ return Object.values(amounts).some((value) => toDecimal(value) !== null)
+}
+
+/**
+ * The amount a calculator-priced method quotes for one currency — the same
+ * rule the calculator uses. Once the per-currency `amounts` hash holds an
+ * amount it alone decides; the legacy single `amount` quotes its own
+ * currency (the `currency` preference, or the store default when that
+ * preference is blank) only while the hash is empty.
+ *
+ * A pre-6.0 method that names EUR therefore returns 7 for EUR and nothing
+ * for USD.
+ */
+export function amountForCurrency(
+ preferences: Record<string, unknown> | null | undefined,
+ currency: string,
+ defaultCurrency: string,
+): string | null {
+ const code = currency.toUpperCase()
+ const amounts = amountsHash(preferences)
+ if (hasAmounts(amounts)) return toDecimal(hashEntry(amounts, code))
+
+ if (legacyCurrency(preferences, defaultCurrency) !== code) return null
+ return toDecimal(preferences?.amount)
+}
+
+/**
+ * Writes one currency's amount the way the delivery-method editor does: into
+ * the per-currency `amounts` hash, the store default like every other
+ * currency, and a cleared currency removed so the method is not offered in
+ * it.
+ *
+ * The first edit of a method priced with the legacy single `amount` moves
+ * that figure into the hash under its own currency, since the hash alone
+ * decides once it holds an amount, and clears the single amount. Amounts are
+ * written as the exact decimal string typed, which is what the API accepts.
+ */
+export function applyCurrencyAmount(
+ preferences: Record<string, unknown>,
+ currency: string,
+ raw: string,
+ defaultCurrency: string,
+): Record<string, unknown> {
+ const current = amountsHash(preferences)
+ const nextAmounts: Record<string, unknown> = hasAmounts(current) ? { ...current } : {}
+
+ if (!hasAmounts(current)) {
+ const legacy = toDecimal(preferences.amount)
+ if (legacy !== null) nextAmounts[legacyCurrency(preferences, defaultCurrency)] = legacy
+ }
+
+ writeHashAmount(nextAmounts, currency, toDecimal(raw))
+ return { ...preferences, amount: null, amounts: nextAmounts }
+}
+
+/**
+ * Whether a calculator-priced method states an amount in any currency. One
+ * without any would never be offered.
+ */
+export function hasCurrencyAmount(
+ preferences: Record<string, unknown> | null | undefined,
+): boolean {
+ return hasAmounts(amountsHash(preferences)) || toDecimal(preferences?.amount) !== null
+}
+
+/**
+ * Every amount a calculator-priced method quotes, each with the currency it
+ * belongs to. The per-currency `amounts` hash decides once it holds an
+ * amount; the legacy single `amount` stands for its own currency (the
+ * `currency` preference, or the store default) only while the hash is empty.
+ *
+ * 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 defaultCode = defaultCurrency.toUpperCase()
+
+ for (const [code, value] of Object.entries(amountsHash(preferences))) {
+ const parsed = toDecimal(value)
+ if (parsed === null) continue
+ listed.push({ amount: parsed, currency: code.toUpperCase() })
+ }
+
+ const legacyAmount = toDecimal(preferences?.amount)
+ if (listed.length === 0 && legacyAmount !== null) {
+ listed.push({ amount: legacyAmount, currency: legacyCurrency(preferences, defaultCurrency) })
+ }
+
+ return listed.sort((left, right) => {
+ if (left.currency === defaultCode) return -1
+ if (right.currency === defaultCode) return 1
+ return left.currency.localeCompare(right.currency)
+ })
+}
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.json
index 85d7e47604..d11777a807 100644
--- a/packages/dashboard-core/src/locales/ar.json
+++ b/packages/dashboard-core/src/locales/ar.json
@@ -487,6 +487,12 @@
"discard_title": "تجاهل هذه المسودة؟"
}
},
+ "currency_amounts": {
+ "amount_in_currency": "المبلغ بعملة {{currency}}",
+ "help": "العملات المتروكة فارغة لا تُعرض لها طريقة التوصيل هذه.",
+ "label": "المبلغ",
+ "required": "أدخل مبلغًا بعملة واحدة على الأقل."
+ },
"custom_field_definitions": {
"errors": {
"failed_to_create": "فشل إنشاء تعريف الحقل المخصص",
diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.json
index 2725edb54a..a3cbd4c3a5 100644
--- a/packages/dashboard-core/src/locales/de.json
+++ b/packages/dashboard-core/src/locales/de.json
@@ -487,6 +487,12 @@
"discard_title": "Entwurf verwerfen?"
}
},
+ "currency_amounts": {
+ "amount_in_currency": "Betrag in {{currency}}",
+ "help": "Währungen ohne Betrag wird diese Versandart nicht angeboten.",
+ "label": "Betrag",
+ "required": "Gib einen Betrag in mindestens einer Währung ein."
+ },
"custom_field_definitions": {
"errors": {
"failed_to_create": "Benutzerdefiniertes Feld konnte nicht erstellt werden",
diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.json
index 2b3ee2b1ff..48ed4dc1f5 100644
--- a/packages/dashboard-core/src/locales/en.json
+++ b/packages/dashboard-core/src/locales/en.json
@@ -489,6 +489,12 @@
"discard_title": "Discard this draft?"
}
},
+ "currency_amounts": {
+ "amount_in_currency": "Amount in {{currency}}",
+ "help": "Currencies left blank are not offered this delivery method.",
+ "label": "Amount",
+ "required": "Enter an amount in at least one currency."
+ },
"custom_field_definitions": {
"errors": {
"failed_to_create": "Failed to create custom field definition",
diff --git a/packages/dashboard-core/src/locales/es.json b/packages/dashboard-core/src/locales/es.json
index 97f90f0606..1d20a1272e 100644
--- a/packages/dashboard-core/src/locales/es.json
+++ b/packages/dashboard-core/src/locales/es.json
@@ -301,6 +301,12 @@
"discard_title": "¿Descartar este borrador?"
}
},
+ "currency_amounts": {
+ "amount_in_currency": "Monto en {{currency}}",
+ "help": "A las monedas dejadas en blanco no se les ofrece este método de entrega.",
+ "label": "Monto",
+ "required": "Introduce un monto en al menos una moneda."
+ },
"pages": {
"settings": {
"stock_locations": {
diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.json
index 5576af2fff..40a63ea6fa 100644
--- a/packages/dashboard-core/src/locales/fr.json
+++ b/packages/dashboard-core/src/locales/fr.json
@@ -487,6 +487,12 @@
"discard_title": "Abandonner ce brouillon ?"
}
},
+ "currency_amounts": {
+ "amount_in_currency": "Montant en {{currency}}",
+ "help": "Les devises laissées vides ne se voient pas proposer cette méthode de livraison.",
+ "label": "Montant",
+ "required": "Saisissez un montant dans au moins une devise."
+ },
"custom_field_definitions": {
"errors": {
"failed_to_create": "Impossible de créer le champ personnalisé",
diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.json
index 40391fdcf6..54c7fcf47d 100644
--- a/packages/dashboard-core/src/locales/pl.json
+++ b/packages/dashboard-core/src/locales/pl.json
@@ -488,6 +488,12 @@
"discard_title": "Odrzucić szkic?"
}
},
+ "currency_amounts": {
+ "amount_in_currency": "Kwota w {{currency}}",
+ "help": "Waluty bez kwoty nie mają oferowanej tej metody dostawy.",
+ "label": "Kwota",
+ "required": "Podaj kwotę w co najmniej jednej walucie."
+ },
"custom_field_definitions": {
"errors": {
"failed_to_create": "Nie udało się utworzyć definicji pola niestandardowego",
diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.json
index a78fbaca85..3ebdb520cc 100644
--- a/packages/dashboard-core/src/locales/zh-CN.json
+++ b/packages/dashboard-core/src/locales/zh-CN.json
@@ -487,6 +487,12 @@
"discard_title": "放弃此草稿?"
}
},
+ "currency_amounts": {
+ "amount_in_currency": "{{currency}} 金额",
+ "help": "未填写金额的币种将不会提供该配送方式。",
+ "label": "金额",
+ "required": "请至少为一种货币输入金额。"
+ },
"custom_field_definitions": {
"errors": {
"failed_to_create": "创建自定义字段定义失败",
diff --git a/packages/dashboard/e2e/delivery-settings.spec.ts b/packages/dashboard/e2e/delivery-settings.spec.ts
index afa0477424..e17cfdc96f 100644
--- a/packages/dashboard/e2e/delivery-settings.spec.ts
+++ b/packages/dashboard/e2e/delivery-settings.spec.ts
@@ -252,6 +252,48 @@ test.describe('delivery profiles', () => {
await expect(sheet.getByText(FIXTURE_BULK_CHANNEL_NAME)).toBeVisible()
})
+ // A currency left blank is not offered, the store's default currency
+ // included, and a method with no amount in any currency is refused rather
+ // than saved as one nobody can be quoted.
+ test('leaves a blank currency out, the store default included, and asks for at least one amount', async ({
+ page,
+ }) => {
+ const creds = await login(page)
+ await gotoIndex(page, DELIVERY_PROFILES_PATH(creds.store_id), PROFILE_CTA)
+
+ const stamp = Date.now()
+ const methodName = `E2E Euro Only ${stamp}`
+ await createProfile(page, `E2E Euro Only Profile ${stamp}`)
+
+ await page
+ .getByRole('button', { name: /add method/i })
+ .first()
+ .click()
+ const sheet = page.getByRole('dialog')
+ await sheet.locator('#name').fill(methodName)
+
+ const calculator = sheet.locator('#calculator-type')
+ await expect(calculator).toBeEnabled({ timeout: 15_000 })
+ await calculator.click()
+ await page.getByRole('option', { name: /^flat rate$/i }).click()
+ await expect(sheet.locator('#calculator-amount-USD')).toHaveValue('')
+
+ await page.getByRole('button', { name: /create delivery method/i }).click()
+ await expect(sheet.getByText(/enter an amount in at least one currency/i)).toBeVisible()
+
+ await sheet.locator('#calculator-amount-EUR').fill('4.50')
+ await page.getByRole('button', { name: /create delivery method/i }).click()
+ await expect(page.getByRole('heading', { name: /new delivery method/i })).toHaveCount(0, {
+ timeout: 15_000,
+ })
+
+ await page.getByText(methodName).click()
+ await expect(sheet.locator('#calculator-amount-EUR')).toHaveValue(/^4\.50?$/, {
+ timeout: 15_000,
+ })
+ await expect(sheet.locator('#calculator-amount-USD')).toHaveValue('')
+ })
+
// Opening a method is a search-param change, so the sheet must survive a
// reload and a direct link — that is what keeps bookmarked methods working.
test('opens the method sheet straight from a URL', async ({ page }) => {
@@ -475,11 +517,18 @@ test.describe('delivery profiles', () => {
})
const sheet = page.getByRole('dialog')
await sheet.locator('#name').fill(methodName)
+ // A flat rate left without amounts must not block a method whose pricing fields the provider hides.
+ const calculator = sheet.locator('#calculator-type')
+ await expect(calculator).toBeEnabled({ timeout: 15_000 })
+ await calculator.click()
+ await page.getByRole('option', { name: /^flat rate$/i }).click()
+ await expect(sheet.locator('#calculator-amount-USD')).toHaveValue('')
const rateProvider = fieldSelect(sheet, 'Rate provider')
await expect(rateProvider).toContainText(/^internal$/i, { timeout: 15_000 })
await rateProvider.click()
await page.getByRole('option', { name: /^freight$/i }).click()
await expect(rateProvider).toContainText(/^freight$/i)
+ await expect(sheet.locator('#calculator-amount-USD')).toHaveCount(0)
// A provider-priced method carries the store's markup on top of the quote.
await sheet.locator('#markup_percent').fill('7.5')
await sheet.locator('#markup_flat').fill('2.50')
diff --git a/packages/dashboard/e2e/seller-delivery-methods.spec.ts b/packages/dashboard/e2e/seller-delivery-methods.spec.ts
index fcbd378b64..dc7e3407e2 100644
--- a/packages/dashboard/e2e/seller-delivery-methods.spec.ts
+++ b/packages/dashboard/e2e/seller-delivery-methods.spec.ts
@@ -96,10 +96,12 @@ test.describe('seller delivery methods', () => {
const calculator = sellerPage.locator('#delivery-method-calculator')
await expect(calculator).toContainText(/flat rate/i, { timeout: 20_000 })
- // The flat rate's own amount preference — blank would mean the method
- // saves as free.
- const amount = sellerPage.locator('#preference-amount')
+ // The flat rate prices per currency, the store's default first. With no
+ // amount anywhere the method would never be offered, so it is refused.
+ const amount = sellerPage.locator('[id^="calculator-amount-"]').first()
await expect(amount).toBeVisible({ timeout: 20_000 })
+ await sellerPage.getByRole('button', { name: /^save$/i }).click()
+ await expect(sellerPage.getByText(/enter an amount in at least one currency/i)).toBeVisible()
await amount.fill('9.99')
await sellerPage.getByRole('button', { name: /^save$/i }).click()
@@ -113,7 +115,7 @@ test.describe('seller delivery methods', () => {
await expect(sellerPage.locator('#delivery-method-calculator')).toContainText(/flat rate/i, {
timeout: 20_000,
})
- await expect(sellerPage.locator('#preference-amount')).toHaveValue(/9\.99/)
+ await expect(sellerPage.locator('[id^="calculator-amount-"]').first()).toHaveValue(/9\.99/)
} finally {
await context.close()
}
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx b/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx
index 21632e892b..d2b073dc5b 100644
--- a/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx
+++ b/packages/dashboard/src/components/spree/shipping/delivery-method-form.tsx
@@ -8,12 +8,14 @@ import type {
Product,
} from '@spree/admin-sdk'
import {
+ AMOUNT_BASED_CALCULATORS,
type adminClient,
Can,
+ CURRENCY_AMOUNT_KEYS,
+ CurrencyAmountsField,
currencyParts,
defaultPreferences,
filterPreferenceSchema,
- isCurrencyCode,
PreferencesForm,
ResourceMultiAutocomplete,
Subject,
@@ -73,26 +75,10 @@ import { useIntegrations, useIntegrationTypes } from '../../../hooks/use-integra
import { productAutocompleteProps } from '../../../hooks/use-products'
import { useSellers } from '../../../hooks/use-sellers'
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'
-/**
- * Calculators whose price is a plain amount, which a multi-currency store
- * quotes per currency through the `amounts` preference. Every other
- * calculator (percent, tiered) is currency-neutral and keeps the generic
- * preference rendering.
- */
-const AMOUNT_BASED_CALCULATORS = ['flat_rate', 'per_item', 'digital_delivery']
-
-/**
- * Preference keys the per-currency editor owns on those calculators. `amount`
- * 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']
-
/** One entry from the delivery-method-rule discovery endpoint. */
type DeliveryMethodRuleType = Awaited<
ReturnType<typeof adminClient.deliveryMethods.ruleTypes>
@@ -942,90 +928,9 @@ function ServiceOverridesSheet({
// carrier-quoted ones
// ---------------------------------------------------------------------------
-/**
- * The amount an amount-based calculator charges, one input per currency the
- * 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.
- */
-function CurrencyAmountsField({
- values,
- onChange,
-}: {
- values: Record<string, unknown>
- onChange: (next: Record<string, unknown>) => void
-}) {
- const { t } = useTranslation()
- const { currencies, defaultCurrency } = useStore()
-
- // The store's currency list is the source of truth, but a method may already
- // carry an amount in a currency the store has since stopped selling in —
- // dropping that input would silently discard the amount on the next save.
- const amounts = (values.amounts ?? {}) as Record<string, unknown>
- const extraCodes = Object.keys(amounts).join(',')
- const codes = useMemo(() => {
- const supported = currencies.length > 0 ? currencies : [defaultCurrency]
- const extra = extraCodes
- .split(',')
- .filter(isCurrencyCode)
- .filter((code) => !supported.includes(code))
- return [defaultCurrency, ...supported.filter((code) => code !== defaultCurrency), ...extra]
- }, [currencies, defaultCurrency, extraCodes])
-
- const multiCurrency = codes.length > 1
-
- function amountFor(code: string): string {
- const raw = amountForCurrency(values, code, defaultCurrency)
- return raw === null ? '' : String(raw)
- }
-
- function setAmount(code: string, raw: string) {
- onChange(applyCurrencyAmount(values, code, raw, defaultCurrency))
- }
-
- return (
- <Field>
- <FieldLabel htmlFor={`calculator-amount-${defaultCurrency}`}>
- {t('admin.preferences.amount')}
- </FieldLabel>
- <div className="flex flex-col gap-2">
- {codes.map((code) => (
- <InputGroup key={code}>
- <InputGroupAddon>
- <InputGroupText>{currencyParts(code, i18n.language).symbol}</InputGroupText>
- </InputGroupAddon>
- <InputGroupInput
- id={`calculator-amount-${code}`}
- type="number"
- step="any"
- min="0"
- aria-label={t('admin.delivery_methods.pricing.amount_in_currency', {
- currency: code,
- })}
- value={amountFor(code)}
- onChange={(event) => setAmount(code, event.target.value)}
- />
- <InputGroupAddon align="inline-end">
- <InputGroupText>{code}</InputGroupText>
- </InputGroupAddon>
- </InputGroup>
- ))}
- </div>
- {multiCurrency && (
- <span className="text-muted-foreground text-xs">
- {t('admin.delivery_methods.pricing.currency_amounts_help')}
- </span>
- )}
- </Field>
- )
-}
-
function PricingCard({ form }: { form: UseFormReturn<DeliveryMethodFormValues> }) {
const { t } = useTranslation()
- const { defaultCurrency } = useStore()
+ const { currencies, defaultCurrency } = useStore()
const { symbol: currencySymbol } = currencyParts(defaultCurrency, i18n.language)
const { data: calculators } = useDeliveryCalculators()
const { data: taxCategories } = useTaxCategories()
@@ -1083,9 +988,17 @@ function PricingCard({ form }: { form: UseFormReturn<DeliveryMethodFormValues> }
// refuses any it does not, so a switch starts from the new
// calculator's defaults rather than the old one's values.
const schema = (calculators?.data ?? []).find((c) => c.type === next)?.schema
+ const defaults = schema
+ ? defaultPreferences(schema, { currency: defaultCurrency })
+ : {}
+ // The single amount's default is 0, which would read as a
+ // price someone set; a new amount-based method starts with
+ // no amount in any currency.
form.setValue(
'calculator.preferences',
- schema ? defaultPreferences(schema, { currency: defaultCurrency }) : {},
+ AMOUNT_BASED_CALCULATORS.includes(next)
+ ? { ...defaults, amount: null }
+ : defaults,
{ shouldDirty: true },
)
}}
@@ -1108,12 +1021,15 @@ function PricingCard({ form }: { form: UseFormReturn<DeliveryMethodFormValues> }
<Controller
name="calculator.preferences"
control={form.control}
- render={({ field }) => (
+ render={({ field, fieldState }) => (
<>
{amountBased && (
<CurrencyAmountsField
values={(field.value ?? {}) as Record<string, unknown>}
onChange={field.onChange}
+ currencies={currencies}
+ defaultCurrency={defaultCurrency}
+ error={fieldState.error}
/>
)}
<PreferencesForm
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx b/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx
index ea1aaa4936..4247a94c76 100644
--- a/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx
+++ b/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx
@@ -16,13 +16,14 @@ import {
SheetHeader,
SheetTitle,
} from '@spree/dashboard-ui'
-import { useEffect } from 'react'
+import { useEffect, useMemo } from 'react'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import {
useCreateDeliveryMethod,
useDeliveryMethod,
useDeliveryMethodRuleTypes,
+ useDeliveryRateProviders,
useFulfillmentProviders,
useUpdateDeliveryMethod,
} from '../../../hooks/use-delivery-methods'
@@ -91,6 +92,7 @@ export function DeliveryMethodSheet({
const { data: method, isLoading: methodLoading } = useDeliveryMethod(methodId)
const { data: ruleTypes, isLoading: ruleTypesLoading } = useDeliveryMethodRuleTypes()
const { data: fulfillmentProviders } = useFulfillmentProviders()
+ const { data: rateProviders, isLoading: rateProvidersLoading } = useDeliveryRateProviders()
const createMutation = useCreateDeliveryMethod()
const updateMutation = useUpdateDeliveryMethod(methodId ?? '')
// Edit only: a method being created has no id to hang values on yet.
@@ -99,12 +101,24 @@ export function DeliveryMethodSheet({
// Saving sends the full rule set for reconciliation, so the form must not be
// reachable until the existing rules have loaded — otherwise a quick save
// would submit an empty set and delete them all. Rule types are needed too,
- // since they decide which rules carry a product list.
- const loading = editing ? methodLoading || ruleTypesLoading : ruleTypesLoading
+ // since they decide which rules carry a product list, and so are the rate
+ // providers, which decide whether the method is asked for an amount.
+ const loading = (editing && methodLoading) || ruleTypesLoading || rateProvidersLoading
+
+ const carrierPricedProviders = useMemo(() => {
+ const types = (rateProviders?.data ?? [])
+ .filter((rateProvider) => rateProvider.uses_calculator === false)
+ .map((rateProvider) => rateProvider.type)
+ return types.includes(rateProviders?.default ?? '') ? [...types, ''] : types
+ }, [rateProviders])
+ const schema = useMemo(
+ () => deliveryMethodFormSchema(carrierPricedProviders),
+ [carrierPricedProviders],
+ )
const form = useForm<DeliveryMethodFormValues>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(deliveryMethodFormSchema) as any,
+ resolver: zodResolver(schema) as any,
defaultValues: {
...DELIVERY_METHOD_DEFAULTS,
delivery_zone_id: zoneId ?? '',
diff --git a/packages/dashboard/src/lib/delivery-method-summary.test.ts b/packages/dashboard/src/lib/delivery-method-summary.test.ts
index 8092e4e1c0..2b34220e32 100644
--- a/packages/dashboard/src/lib/delivery-method-summary.test.ts
+++ b/packages/dashboard/src/lib/delivery-method-summary.test.ts
@@ -1,62 +1,5 @@
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' },
- ])
- })
-})
+import { formatListedPrice } from './delivery-method-summary'
describe('formatListedPrice', () => {
const separator = ' · '
@@ -79,7 +22,7 @@ describe('formatListedPrice', () => {
it('joins one price per stored currency', () => {
expect(
- formatListedPrice({ amount: '5', amounts: { EUR: '7' } }, 'USD', 'en', 'Free', separator),
+ formatListedPrice({ amounts: { USD: '5', EUR: '7' } }, 'USD', 'en', 'Free', separator),
).toBe('$5.00 · €7.00')
})
@@ -97,74 +40,3 @@ describe('formatListedPrice', () => {
).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: {},
- })
- })
-
- it('sends the amount as the exact string typed, and a cleared default amount as zero', () => {
- expect(applyCurrencyAmount({ amount: '5.0' }, 'USD', '9.99', 'USD')).toMatchObject({
- amount: '9.99',
- })
- expect(applyCurrencyAmount({ amount: '5.0' }, 'USD', '', 'USD')).toMatchObject({ amount: '0' })
- })
-})
diff --git a/packages/dashboard/src/lib/delivery-method-summary.ts b/packages/dashboard/src/lib/delivery-method-summary.ts
index e266007b62..07f5078145 100644
--- a/packages/dashboard/src/lib/delivery-method-summary.ts
+++ b/packages/dashboard/src/lib/delivery-method-summary.ts
@@ -1,6 +1,6 @@
import type { DeliveryMethodRule } from '@spree/admin-sdk'
import { isDecimalString, isZeroMoney } from '@spree/core'
-import { formatAmount } from '@spree/dashboard-core'
+import { formatAmount, listedAmounts } from '@spree/dashboard-core'
import type { TFunction } from 'i18next'
/**
@@ -13,170 +13,6 @@ function toDecimal(value: unknown): string | null {
return isDecimalString(text) ? text : null
}
-/** One stored delivery amount and the ISO currency it was entered in. */
-export type ListedAmount = {
- amount: string
- 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: string | 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,
-): string | null {
- const code = currency.toUpperCase()
- const fromHash = hashEntry(amountsHash(preferences), code)
- if (fromHash !== undefined && fromHash !== null && fromHash !== '') {
- return toDecimal(fromHash)
- }
-
- if (legacyCurrency(preferences, defaultCurrency) !== code) return null
- return toDecimal(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.
- *
- * Amounts are written as the exact decimal string typed, which is what the
- * API accepts; a cleared default-currency amount is zero, as the server
- * stores it.
- */
-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 = toDecimal(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] = String(existing)
- }
- }
-
- if (code === defaultCode) {
- if (hashKey(nextAmounts, code) !== undefined) {
- writeHashAmount(nextAmounts, code, parsed)
- }
- return {
- ...preferences,
- amount: parsed ?? '0',
- currency: defaultCurrency,
- amounts: nextAmounts,
- }
- }
-
- writeHashAmount(nextAmounts, code, parsed)
-
- if (namedCurrency === code) {
- return { ...preferences, amount: parsed ?? '0', 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 = toDecimal(value)
- if (parsed === null) continue
- const currency = code.toUpperCase()
- listed.push({ amount: parsed, currency })
- seen.add(currency)
- }
-
- const legacyAmount = toDecimal(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
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 96ac9ccb2e..f7651a4f8e 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -806,10 +806,6 @@
"updated": "تم تحديث طريقة التوصيل"
},
"no_zone_restriction": "بدون تقييد",
- "pricing": {
- "amount_in_currency": "المبلغ بعملة {{currency}}",
- "currency_amounts_help": "العملات المتروكة فارغة لا تُعرض لها طريقة التوصيل هذه."
- },
"provider_needs_connection": "اربط {{name}} لاستخدامه",
"provider_unavailable": "{{name}} (غير متاح)",
"rule_summary": {
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 527568bb83..c51238cfbf 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -799,10 +799,6 @@
"updated": "Versandart aktualisiert"
},
"no_zone_restriction": "Keine Beschränkung",
- "pricing": {
- "amount_in_currency": "Betrag in {{currency}}",
- "currency_amounts_help": "Währungen ohne Betrag wird diese Versandart nicht angeboten."
- },
"provider_needs_connection": "{{name}} verbinden, um es zu nutzen",
"provider_unavailable": "{{name}} (nicht verfügbar)",
"rule_summary": {
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 0904615475..6c52165784 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -799,10 +799,6 @@
"updated": "Delivery method updated"
},
"no_zone_restriction": "No restriction",
- "pricing": {
- "amount_in_currency": "Amount in {{currency}}",
- "currency_amounts_help": "Currencies left blank are not offered this delivery method."
- },
"provider_needs_connection": "Connect {{name}} to use it",
"provider_unavailable": "{{name}} (unavailable)",
"rule_summary": {
diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.json
index e5e9d98591..ea2296fefa 100644
--- a/packages/dashboard/src/locales/es.json
+++ b/packages/dashboard/src/locales/es.json
@@ -4805,10 +4805,6 @@
"updated": "Método de entrega actualizado"
},
"no_zone_restriction": "Sin restricción",
- "pricing": {
- "amount_in_currency": "Monto en {{currency}}",
- "currency_amounts_help": "A las monedas dejadas en blanco no se les ofrece este método de entrega."
- },
"provider_needs_connection": "Conectá {{name}} para usarlo",
"provider_unavailable": "{{name}} (no disponible)",
"rule_summary": {
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index a60137bedd..e96d0b8df1 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -799,10 +799,6 @@
"updated": "Méthode de livraison mise à jour"
},
"no_zone_restriction": "Aucune restriction",
- "pricing": {
- "amount_in_currency": "Montant en {{currency}}",
- "currency_amounts_help": "Les devises laissées vides ne se voient pas proposer cette méthode de livraison."
- },
"provider_needs_connection": "Connectez {{name}} pour l’utiliser",
"provider_unavailable": "{{name}} (indisponible)",
"rule_summary": {
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index f7ff4d89dc..0b5c7e818e 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -811,10 +811,6 @@
"updated": "Zaktualizowano metodę dostawy"
},
"no_zone_restriction": "Bez ograniczeń",
- "pricing": {
- "amount_in_currency": "Kwota w {{currency}}",
- "currency_amounts_help": "Waluty bez kwoty nie mają oferowanej tej metody dostawy."
- },
"provider_needs_connection": "Połącz {{name}}, aby użyć",
"provider_unavailable": "{{name}} (niedostępny)",
"rule_summary": {
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 1aca2d985f..b3d18dbbf1 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -797,10 +797,6 @@
"updated": "配送方式已更新"
},
"no_zone_restriction": "不限制",
- "pricing": {
- "amount_in_currency": "{{currency}} 金额",
- "currency_amounts_help": "未填写金额的币种将不会提供该配送方式。"
- },
"provider_needs_connection": "连接 {{name}} 后即可使用",
"provider_unavailable": "{{name}}(不可用)",
"rule_summary": {
diff --git a/packages/dashboard/src/schemas/delivery-method.test.ts b/packages/dashboard/src/schemas/delivery-method.test.ts
new file mode 100644
index 0000000000..b4c44c06ec
--- /dev/null
+++ b/packages/dashboard/src/schemas/delivery-method.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest'
+import { DELIVERY_METHOD_DEFAULTS, deliveryMethodFormSchema } from './delivery-method'
+
+const flatRate = (amounts: Record<string, string>) => ({
+ ...DELIVERY_METHOD_DEFAULTS,
+ name: 'Standard',
+ calculator: { type: 'flat_rate', preferences: { amounts } },
+})
+
+function amountErrors(values: ReturnType<typeof flatRate>, carrierPricedProviders?: string[]) {
+ const result = deliveryMethodFormSchema(carrierPricedProviders).safeParse(values)
+ return result.success ? [] : result.error.issues.filter((issue) => issue.path[0] === 'calculator')
+}
+
+describe('deliveryMethodFormSchema calculator amounts', () => {
+ it('asks a calculator-priced method for an amount in at least one currency', () => {
+ expect(amountErrors(flatRate({}))).toHaveLength(1)
+ expect(amountErrors(flatRate({ EUR: '' }))).toHaveLength(1)
+ expect(amountErrors(flatRate({ EUR: '4.90' }))).toEqual([])
+ })
+
+ // The calculator stays on the record but its fields are hidden, so an empty amount must not block saving.
+ it('asks nothing of a method priced by a carrier', () => {
+ expect(amountErrors({ ...flatRate({}), rate_provider: 'easy_post' }, ['easy_post'])).toEqual([])
+ })
+
+ it('asks nothing when the default provider quotes the rates', () => {
+ expect(amountErrors(flatRate({}), ['easy_post', ''])).toEqual([])
+ })
+})
diff --git a/packages/dashboard/src/schemas/delivery-method.ts b/packages/dashboard/src/schemas/delivery-method.ts
index 35aa79bed3..2b052293af 100644
--- a/packages/dashboard/src/schemas/delivery-method.ts
+++ b/packages/dashboard/src/schemas/delivery-method.ts
@@ -1,3 +1,4 @@
+import { AMOUNT_BASED_CALCULATORS, hasCurrencyAmount, i18n } from '@spree/dashboard-core'
import { z } from 'zod/v4'
/**
@@ -32,7 +33,7 @@ export const deliveryMethodServiceSchema = z.object({
export type DeliveryMethodServiceDraft = z.infer<typeof deliveryMethodServiceSchema>
-export const deliveryMethodFormSchema = z.object({
+const deliveryMethodFormObject = z.object({
name: z.string().min(1),
admin_name: z.string().optional(),
code: z.string().optional(),
@@ -63,7 +64,29 @@ export const deliveryMethodFormSchema = z.object({
services: z.array(deliveryMethodServiceSchema),
})
-export type DeliveryMethodFormValues = z.infer<typeof deliveryMethodFormSchema>
+export type DeliveryMethodFormValues = z.infer<typeof deliveryMethodFormObject>
+
+/**
+ * The delivery method form's schema. `carrierPricedProviders` names the rate
+ * providers that quote their own rates (`''` when the default one does): their
+ * methods hide the calculator, so its amounts are not asked for.
+ */
+export function deliveryMethodFormSchema(carrierPricedProviders: readonly string[] = []) {
+ return deliveryMethodFormObject.superRefine((values, ctx) => {
+ if (carrierPricedProviders.includes(values.rate_provider)) return
+
+ // A calculator-priced method with no amount in any currency would never be offered.
+ const { type, preferences } = values.calculator
+ if (!AMOUNT_BASED_CALCULATORS.includes(type ?? '')) return
+ if (hasCurrencyAmount(preferences)) return
+
+ ctx.addIssue({
+ code: 'custom',
+ path: ['calculator', 'preferences'],
+ message: i18n.t('admin.currency_amounts.required'),
+ })
+ })
+}
export const DELIVERY_METHOD_DEFAULTS: DeliveryMethodFormValues = {
name: '',
diff --git a/packages/seller-dashboard/src/pages/delivery-methods.tsx b/packages/seller-dashboard/src/pages/delivery-methods.tsx
index 7ab569dd34..64a1ce617e 100644
--- a/packages/seller-dashboard/src/pages/delivery-methods.tsx
+++ b/packages/seller-dashboard/src/pages/delivery-methods.tsx
@@ -1,6 +1,10 @@
import {
+ AMOUNT_BASED_CALCULATORS,
+ CURRENCY_AMOUNT_KEYS,
+ CurrencyAmountsField,
defaultPreferences,
filterPreferenceSchema,
+ hasCurrencyAmount,
PageHeader,
PreferencesForm,
type ResourceSearch,
@@ -281,13 +285,15 @@ function DeliveryMethodSheet({
form.setValue('calculator', {
type: flatRate.type,
- preferences: defaultPreferences(renderableSchema(flatRate.schema)),
+ preferences: calculatorDefaults(flatRate.type, flatRate.schema),
})
}, [calculators, methodId, form])
- const calculatorSchema = renderableSchema(
+ const calculatorSchema = calculatorFormSchema(
+ calculatorType,
calculators?.data.find((calculator) => calculator.type === calculatorType)?.schema,
)
+ const amountBased = AMOUNT_BASED_CALCULATORS.includes(calculatorType)
const save = useMutation({
mutationFn: (values: DeliveryMethodFormValues) => {
@@ -354,7 +360,17 @@ function DeliveryMethodSheet({
<SheetDescription>{t('delivery_methods.sheet.description')}</SheetDescription>
</SheetHeader>
<form
- onSubmit={form.handleSubmit((values) => save.mutateAsync(values).catch(() => undefined))}
+ onSubmit={form.handleSubmit((values) => {
+ // An amount-based calculator with no amount in any currency would never be offered.
+ const { type, preferences } = values.calculator
+ if (AMOUNT_BASED_CALCULATORS.includes(type) && !hasCurrencyAmount(preferences)) {
+ form.setError('calculator.preferences', {
+ message: t('admin.currency_amounts.required'),
+ })
+ return
+ }
+ return save.mutateAsync(values).catch(() => undefined)
+ })}
className="flex min-h-0 flex-1 flex-col"
>
<div className="flex flex-1 flex-col gap-6 overflow-y-auto p-4">
@@ -488,11 +504,10 @@ function DeliveryMethodSheet({
value={field.value}
onValueChange={(next) => {
field.onChange(next)
- const schema = renderableSchema(
- calculators?.data.find((calculator) => calculator.type === next)
- ?.schema,
- )
- form.setValue('calculator.preferences', defaultPreferences(schema))
+ const schema = calculators?.data.find(
+ (calculator) => calculator.type === next,
+ )?.schema
+ form.setValue('calculator.preferences', calculatorDefaults(next, schema))
}}
>
<SelectTrigger id="delivery-method-calculator">
@@ -522,13 +537,24 @@ function DeliveryMethodSheet({
<Controller
control={form.control}
name="calculator.preferences"
- render={({ field }) => (
- <PreferencesForm
- schema={calculatorSchema}
- values={field.value}
- onChange={field.onChange}
- currencyOptions={currencyOptions}
- />
+ render={({ field, fieldState }) => (
+ <>
+ {amountBased && sellerProfile && (
+ <CurrencyAmountsField
+ values={field.value}
+ onChange={field.onChange}
+ currencies={currencyOptions}
+ defaultCurrency={sellerProfile.default_currency}
+ error={fieldState.error}
+ />
+ )}
+ <PreferencesForm
+ schema={calculatorSchema}
+ values={field.value}
+ onChange={field.onChange}
+ currencyOptions={currencyOptions}
+ />
+ </>
)}
/>
</CardContent>
@@ -634,12 +660,33 @@ function DeliveryMethodSheet({
/**
* The part of a preference schema the shared form can render.
*
- * Drops keyed maps — today the flat-rate calculator's
- * per-currency `amounts` map, which the operator edits through a dedicated
- * multi-currency control and the generic form would show as the hash itself
- * in a text box. A seller quotes in the store's currency, so `amount` and
- * `currency` are the whole question.
+ * Drops keyed maps, which the generic form would show as the hash itself in a
+ * text box.
+ */
+/**
+ * A calculator's settings for the generic form: an amount-based calculator's
+ * amounts are edited per currency by the amount editor instead.
*/
+function calculatorFormSchema(
+ type: string,
+ schema: PreferenceSchema | undefined,
+): PreferenceSchema | undefined {
+ const renderable = renderableSchema(schema)
+ if (!renderable || !AMOUNT_BASED_CALCULATORS.includes(type)) return renderable
+
+ return filterPreferenceSchema(renderable, (key) => !CURRENCY_AMOUNT_KEYS.includes(key))
+}
+
+/**
+ * A calculator's starting settings. The single amount's default is 0, which
+ * would read as a price someone set, so an amount-based calculator starts with
+ * no amount in any currency.
+ */
+function calculatorDefaults(type: string, schema: PreferenceSchema | undefined) {
+ const defaults = defaultPreferences(calculatorFormSchema(type, schema))
+ return AMOUNT_BASED_CALCULATORS.includes(type) ? { ...defaults, amount: null } : defaults
+}
+
function renderableSchema(schema: PreferenceSchema | undefined): PreferenceSchema | undefined {
if (!schema) return undefined
diff --git a/packages/seller-sdk/src/types/preferences.ts b/packages/seller-sdk/src/types/preferences.ts
index ecb6b59a44..5cce3a1173 100644
--- a/packages/seller-sdk/src/types/preferences.ts
+++ b/packages/seller-sdk/src/types/preferences.ts
@@ -13,7 +13,7 @@ type Narrowed<Resource, Map> = {
export type DeliveryCalculatorDigitalDeliveryPreferences = {
amounts: Record<string, string>
/** An amount, as an exact decimal string. */
- amount: string
+ amount: string | null
/** Format: `currency`. */
currency: string
}
@@ -27,7 +27,7 @@ export type DeliveryCalculatorFlatPercentItemTotalPreferences = {
export type DeliveryCalculatorFlatRatePreferences = {
amounts: Record<string, string>
/** An amount, as an exact decimal string. */
- amount: string
+ amount: string | null
/** Format: `currency`. */
currency: string
}
@@ -47,7 +47,7 @@ export type DeliveryCalculatorFlexiRatePreferences = {
export type DeliveryCalculatorPerItemPreferences = {
amounts: Record<string, string>
/** An amount, as an exact decimal string. */
- amount: string
+ amount: string | null
/** Format: `currency`. */
currency: string
}
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
index fe6853da30..dded6b3b42 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
@@ -281,7 +281,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
expect(delivery_method.reload.calculator).to eq(calculator)
end
- it 'stores per-currency amounts' do
+ it 'stores per-currency amounts, which alone decide where the method is offered' do
patch :update, params: {
id: delivery_method.prefixed_id,
calculator: { type: 'flat_rate', preferences: { amount: '20', currency: 'USD', amounts: { 'EUR' => '15.0' } } }
@@ -293,7 +293,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
calculator = delivery_method.reload.calculator
expect(calculator.preferred_amounts).to eq('EUR' => '15.0')
expect(calculator.amount_for('EUR')).to eq(15.0)
- expect(calculator.amount_for('USD')).to eq(20)
+ expect(calculator.amount_for('USD')).to be_nil
end
# The dashboard sheet saves basics and conditions together.
diff --git a/spree/core/app/models/concerns/spree/calculator/currency_amounts.rb b/spree/core/app/models/concerns/spree/calculator/currency_amounts.rb
index 2245dce852..70bbfd4ab7 100644
--- a/spree/core/app/models/concerns/spree/calculator/currency_amounts.rb
+++ b/spree/core/app/models/concerns/spree/calculator/currency_amounts.rb
@@ -6,9 +6,12 @@ module Spree
# currency directly, so one method serves every currency it has an
# amount for — no more method-per-currency duplication.
#
- # The 5.x single `amount` + `currency` preferences keep working as the
- # fallback for their own currency, so upgraded stores quote unchanged
- # until they fill in the hash.
+ # Once the hash holds an amount it alone decides, and a currency it leaves
+ # out is not offered. The 5.x single `amount` + `currency` pair quotes its
+ # own currency only while the hash is empty, so upgraded stores quote
+ # unchanged until they fill it in. The pair's untouched default (0 in the
+ # store's currency) can never be read as a price someone set beside the
+ # hash.
module CurrencyAmounts
extend ActiveSupport::Concern
@@ -17,14 +20,15 @@ module Spree
end
# The amount this calculator quotes for a currency: the per-currency
- # hash first, then the legacy single amount when its currency matches.
+ # hash when it holds any amount, otherwise the legacy single amount for
+ # its own currency.
#
# @param currency [String]
# @return [BigDecimal, nil] nil when the currency has no amount — the
# method is not offered for that cart
def amount_for(currency)
- explicit = preferred_amounts&.transform_keys { |key| key.to_s.upcase }&.dig(currency.to_s.upcase)
- return BigDecimal(explicit.to_s) if explicit.present?
+ amounts = currency_amounts
+ return amounts[currency.to_s.upcase] if amounts.any?
legacy_currency = respond_to?(:preferred_currency) ? preferred_currency : nil
return preferred_amount if legacy_currency.blank? || legacy_currency.casecmp(currency.to_s).zero?
@@ -38,6 +42,15 @@ module Spree
def supports_currency?(currency)
amount_for(currency).present?
end
+
+ private
+
+ # The hash's amounts by upper-case currency, without blank entries.
+ def currency_amounts
+ (preferred_amounts || {}).each_with_object({}) do |(key, value), amounts|
+ amounts[key.to_s.upcase] = BigDecimal(value.to_s) if value.present?
+ end
+ end
end
end
end
diff --git a/spree/core/app/models/spree/calculator/shipping/digital_delivery.rb b/spree/core/app/models/spree/calculator/shipping/digital_delivery.rb
index cb9b40bf50..9616481aad 100644
--- a/spree/core/app/models/spree/calculator/shipping/digital_delivery.rb
+++ b/spree/core/app/models/spree/calculator/shipping/digital_delivery.rb
@@ -3,7 +3,9 @@ module Spree
class DigitalDelivery < ShippingCalculator
include Spree::Calculator::CurrencyAmounts
- preference :amount, :money, default: 0
+ # Blank once its figure has moved into `amounts`, so the method quotes
+ # nothing outside the hash.
+ preference :amount, :money, default: 0, nullable: true
preference :currency, :string, format: :currency, default: -> { Spree::Store.default.default_currency }
def self.description
diff --git a/spree/core/app/models/spree/calculator/shipping/flat_rate.rb b/spree/core/app/models/spree/calculator/shipping/flat_rate.rb
index cf358bf17d..d9fa2c0fc7 100644
--- a/spree/core/app/models/spree/calculator/shipping/flat_rate.rb
+++ b/spree/core/app/models/spree/calculator/shipping/flat_rate.rb
@@ -3,7 +3,9 @@ module Spree
class FlatRate < ShippingCalculator
include Spree::Calculator::CurrencyAmounts
- preference :amount, :money, default: 0
+ # Blank once its figure has moved into `amounts`, so the method quotes
+ # nothing outside the hash.
+ preference :amount, :money, default: 0, nullable: true
# @deprecated Together with the single `amount`, superseded by the
# per-currency `amounts` hash; kept as the fallback for its own
# currency so upgraded stores quote unchanged.
diff --git a/spree/core/app/models/spree/calculator/shipping/per_item.rb b/spree/core/app/models/spree/calculator/shipping/per_item.rb
index 347e2a0bf4..db881162be 100644
--- a/spree/core/app/models/spree/calculator/shipping/per_item.rb
+++ b/spree/core/app/models/spree/calculator/shipping/per_item.rb
@@ -3,7 +3,9 @@ module Spree
class PerItem < ShippingCalculator
include Spree::Calculator::CurrencyAmounts
- preference :amount, :money, default: 0
+ # Blank once its figure has moved into `amounts`, so the method quotes
+ # nothing outside the hash.
+ preference :amount, :money, default: 0, nullable: true
preference :currency, :string, format: :currency, default: -> { Spree::Store.default.default_currency }
def self.description
diff --git a/spree/core/app/models/spree/delivery_method.rb b/spree/core/app/models/spree/delivery_method.rb
index c23f675fd4..db3ec82b9e 100644
--- a/spree/core/app/models/spree/delivery_method.rb
+++ b/spree/core/app/models/spree/delivery_method.rb
@@ -451,10 +451,13 @@ module Spree
calculator.description + ': ' +
if calculator.is_a?(Spree::Calculator::Shipping::FlatRate)
- if calculator.preferred_amount == 0
+ amount = calculator.amount_for(calculator.preferred_currency)
+ if amount.nil?
+ ''
+ elsif amount.zero?
I18n.t('spree.free')
else
- Spree::Money.new(calculator.preferred_amount, { currency: calculator.preferred_currency }).to_s
+ Spree::Money.new(amount, { currency: calculator.preferred_currency }).to_s
end
elsif calculator.is_a?(Spree::Calculator::Shipping::FlexiRate)
Spree::Money.new(calculator.preferred_first_item, { currency: calculator.preferred_currency }).to_s
diff --git a/spree/core/spec/models/spree/calculator/shipping/flat_rate_spec.rb b/spree/core/spec/models/spree/calculator/shipping/flat_rate_spec.rb
index 58ce8bf9e9..900102f85a 100644
--- a/spree/core/spec/models/spree/calculator/shipping/flat_rate_spec.rb
+++ b/spree/core/spec/models/spree/calculator/shipping/flat_rate_spec.rb
@@ -7,16 +7,27 @@ RSpec.describe Spree::Calculator::Shipping::FlatRate, type: :model do
let(:usd_package) { double(currency: 'USD', weight: 1, item_total: 50) }
let(:eur_package) { double(currency: 'EUR', weight: 1, item_total: 50) }
- it 'quotes each currency its own amount and hides currencies without one' do
+ it 'quotes from the per-currency amounts alone once they hold one, hiding every other currency' do
subject.preferred_amounts = { 'EUR' => 4 }
- expect(subject.compute_package(usd_package)).to eq(5)
expect(subject.compute_package(eur_package)).to eq(4)
- expect(subject.supports_currency?('USD')).to be true
- expect(subject.supports_currency?('EUR')).to be true
+ expect(subject.compute_package(usd_package)).to be_nil
+ expect(subject.supports_currency?('USD')).to be false
expect(subject.supports_currency?('GBP')).to be false
end
+ it 'never reads the untouched single amount as a price beside the per-currency amounts' do
+ calculator = described_class.new(preferred_amounts: { 'EUR' => 4 })
+
+ expect(calculator.supports_currency?(calculator.preferred_currency)).to be false
+ end
+
+ it 'quotes nothing for a blank single amount' do
+ subject.preferred_amount = nil
+
+ expect(subject.supports_currency?('USD')).to be false
+ end
+
it 'keeps the legacy single amount+currency pair working unchanged' do
expect(subject.compute_package(usd_package)).to eq(5)
expect(subject.supports_currency?('EUR')).to be false