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
Added a money type for preferences
Damian Legawiecf508a389f7f0
diff --git a/.changeset/money-preference-type.md b/.changeset/money-preference-type.mdnew file mode 100644index 0000000000..53881e0d9e--- /dev/null+++ b/.changeset/money-preference-type.md@@ -0,0 +1,8 @@+---+"@spree/dashboard": patch+"@spree/dashboard-core": patch+"@spree/dashboard-ui": patch+"@spree/admin-sdk": patch+---++Preferences of the new `money` type are shown with their currency's symbol in settings forms and as money in calculator summaries, instead of being guessed from the preference's name. `PreferenceField.type` documents the `money` type.diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex 3f3c1ddc8a..708dd16e95 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -23780,13 +23780,13 @@ paths:description: Order total meets these criteriapreference_schema:- key: amount_min- type: decimal+ type: moneydefault: '100'- key: operator_mintype: stringdefault: ">"- key: amount_max- type: decimal+ type: moneydefault:- key: operator_maxtype: string@@ -33328,10 +33328,10 @@ paths:description: Charges this rate only on sales within a value rangepreference_schema:- key: min_amount- type: decimal+ type: moneydefault:- key: max_amount- type: decimal+ type: moneydefault:association_fields: []schema:@@ -35135,7 +35135,7 @@ paths:calculator_type: flat_ratecalculator_preferences:amounts: {}- amount: '10.0'+ amount: '10.00'currency: USDmeta:page: 1@@ -35227,7 +35227,7 @@ paths:calculator_type: flat_ratecalculator_preferences:amounts: {}- amount: '12.5'+ amount: '12.50'currency: USDrequestBody:content:@@ -35337,7 +35337,7 @@ paths:type: hashdefault: {}- key: amount- type: decimal+ type: moneydefault: '0'- key: currencytype: string@@ -35346,10 +35346,10 @@ paths:name: Flexible Rate per package itempreference_schema:- key: first_item- type: decimal+ type: moneydefault: '0'- key: additional_item- type: decimal+ type: moneydefault: '0'- key: max_itemstype: integer@@ -35364,7 +35364,7 @@ paths:type: hashdefault: {}- key: amount- type: decimal+ type: moneydefault: '0'- key: currencytype: string@@ -35373,13 +35373,13 @@ paths:name: Price sackpreference_schema:- key: minimal_amount- type: decimal+ type: moneydefault: '0'- key: normal_amount- type: decimal+ type: moneydefault: '0'- key: discount_amount- type: decimal+ type: moneydefault: '0'- key: currencytype: string@@ -35391,7 +35391,7 @@ paths:type: hashdefault: {}- key: amount- type: decimal+ type: moneydefault: '0'- key: currencytype: stringdiff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yamlindex 013649bcce..18cb95729c 100644--- a/docs/api-reference/seller.yaml+++ b/docs/api-reference/seller.yaml@@ -12444,7 +12444,7 @@ paths:calculator_type: flat_ratecalculator_preferences:amounts: {}- amount: '10.0'+ amount: '10.00'currency: USD- id: dm_gbHJdmfrXBname: Marketplace post@@ -12466,7 +12466,7 @@ paths:calculator_type: flat_ratecalculator_preferences:amounts: {}- amount: '10.0'+ amount: '10.00'currency: USDmeta:page: 1@@ -12645,7 +12645,7 @@ paths:calculator_type: flat_ratecalculator_preferences:amounts: {}- amount: '10.0'+ amount: '10.00'currency: USDschema:"$ref": "#/components/schemas/DeliveryMethod"@@ -12684,7 +12684,7 @@ paths:calculator_type: flat_ratecalculator_preferences:amounts: {}- amount: '10.0'+ amount: '10.00'currency: USDschema:"$ref": "#/components/schemas/DeliveryMethod"@@ -12774,10 +12774,10 @@ paths:total rangepreference_schema:- key: minimum_amount- type: decimal+ type: moneydefault:- key: maximum_amount- type: decimal+ type: moneydefault:- type: weight_rulename: Weight@@ -12862,7 +12862,7 @@ paths:type: hashdefault: {}- key: amount- type: decimal+ type: moneydefault: '0'- key: currencytype: string@@ -12871,10 +12871,10 @@ paths:name: Flexible Rate per package itempreference_schema:- key: first_item- type: decimal+ type: moneydefault: '0'- key: additional_item- type: decimal+ type: moneydefault: '0'- key: max_itemstype: integer@@ -12889,7 +12889,7 @@ paths:type: hashdefault: {}- key: amount- type: decimal+ type: moneydefault: '0'- key: currencytype: string@@ -12898,13 +12898,13 @@ paths:name: Price sackpreference_schema:- key: minimal_amount- type: decimal+ type: moneydefault: '0'- key: normal_amount- type: decimal+ type: moneydefault: '0'- key: discount_amount- type: decimal+ type: moneydefault: '0'- key: currencytype: string@@ -12916,7 +12916,7 @@ paths:type: hashdefault: {}- key: amount- type: decimal+ type: moneydefault: '0'- key: currencytype: stringdiff --git a/docs/developer/customization/model-preferences.mdx b/docs/developer/customization/model-preferences.mdxindex 67f1612d79..81f210887f 100644--- a/docs/developer/customization/model-preferences.mdx+++ b/docs/developer/customization/model-preferences.mdx@@ -98,7 +98,22 @@ This hash will contain the value for every preference that has been defined for`preferences` never holds secrets — see [Secret preferences](#secret-preferences).-## Secret preferences+## Money preferences++Declare an amount of money with the `:money` type, and a rate or a measure (a percentage, a weight) with `:decimal`:++```ruby server/app/models/spree/calculator/handling_fee.rb+module Spree+ class Calculator::HandlingFee < Spree::Calculator+ preference :amount, :money, default: 0+ preference :currency, :string, default: -> { Spree::Store.default.default_currency }+ preference :surcharge_percent, :decimal, default: 0+ end+end+```++Both are read back as a `BigDecimal` and take a number or a decimal string (`"4.50"`); text such as `"4,50"` is refused rather than misread. The difference is on the [API](/api-reference/admin-api/monetary-amounts): a `:money` preference is written with the decimals of the record's `currency` preference (`"4.50"`, or `"450"` in yen), and the dashboard shows it with that currency's symbol. A money preference on a record with no currency, such as a rule matching an order total in any currency, keeps its exact decimal.+Declare API keys, signing secrets and other credentials with the `:password` type:diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex 33ff827e7e..217035711d 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -825,6 +825,7 @@ Other changes that come with it:- **Money on the API is written to each currency's decimals.** Every amount in the Store, Admin and Seller APIs, and so in webhook payloads and email variables, is a decimal string with exactly its currency's decimal places: `"10.00"` (was `"10.0"`), `"1000"` in yen (was `"1000.0"`), `"1.500"` in dinar. Unit prices keep up to four decimals. Fields that were JSON numbers are now strings: `cart.order_minimum` and `order_minimum_shortfall`, the product filter price range `min`/`max`, report money metrics and percentages, and the store's `preferred_default_minimum_payout_amount` and `preferred_default_commission_tax_rate`. Clients comparing these strings, or parsing them as numbers, should switch to exact decimal arithmetic; the SDKs export `sumMoney`, `subtractMoney`, `multiplyMoney`, `compareMoney` and `isZeroMoney`.- **Admin and Seller writes refuse JSON numbers for money.** Amounts and rates, including those inside `preferences`, must be canonical decimal strings (`"19.99"`). A number, a localized or grouped string, or more decimals than the field holds is answered with `422` and `invalid_money_format`, naming the field.- **Amounts may not carry more decimals than they can keep.** Now that the columns hold four decimals, the database no longer rounds away a fraction of a cent, so a payment, refund, store credit, gift card, fee or discount with more decimals than its currency has (`10.0049` dollars) fails validation with `too_many_decimals`. Unit prices and cost prices allow four, tax rates five decimals of the fraction (`rate_percent` `"7.125"`, not `"7.1255"`), and price list percentages three. Round in your own code before saving. A manual order discount's `value` and a commission rate's `value` are read as strictly as other money fields.+- **Money preferences have their own type.** Calculator, rule and store preferences holding an amount (`amount`, `first_item`, `minimal_amount`, `amount_min`, `min_amount`, `default_minimum_payout_amount` and the like) are declared `:money` instead of `:decimal`, report `money` in `preference_schema`, and are written with the decimals of the calculator's currency (`"12.50"` rather than `"12.5"`). Declare your own extensions' amounts with `:money` so the dashboard shows their currency. A `:decimal` or `:money` preference now refuses text such as `"1,599.99"` instead of reading it as 1.- **Rates are decimal strings, and tax rates are renamed.** Rates and percentages read and write as strings without trailing zeros. A tax rate's `amount` (a fraction) is now `rate`, and `amount_percentage` is `rate_percent`; `Spree::TaxRate#amount_percentage` keeps working with a warning until 6.1.- **`amount_in_cents` and `compare_at_amount_in_cents` are removed** from prices and price history. Read `amount`, and each currency's `decimal_places` (new on `GET /api/v3/store/currencies`) if you need minor units.- **Money columns widen to `decimal(19,4)`.** They now hold a Kuwaiti dinar's third decimal, unit prices below a cent (`0.0125`), and very large amounts in currencies like the Vietnamese dong. No stored value changes. Totals, payments and refunds are still rounded to the currency's decimals; only unit prices (`price`, `compare_at_amount`, `cost_price`, `unit_cost`) keep up to four. The migration rewrites each money table while it runs, which locks `spree_orders`, `spree_line_items` and `spree_adjustments` for as long as that takes. If you cannot take that lock, widen those columns online first (add a `decimal(19,4)` shadow column, backfill it in batches, swap it in), and the migration skips any column already at `(19,4)`. Extensions with their own money tables, such as `spree_stripe_payment_intents` from the standalone Stripe gem, should widen theirs the same way.diff --git a/docs/plans/6.0-money-correctness.md b/docs/plans/6.0-money-correctness.mdindex 5fbf2332de..275c45a737 100644--- a/docs/plans/6.0-money-correctness.md+++ b/docs/plans/6.0-money-correctness.md@@ -1,6 +1,6 @@# Money Correctness-**Status:** In Progress — A, A2, B and C built on spree/spree#14852, awaiting review and merge+**Status:** In Progress — A, A2, B and C merged in spree/spree#14852; D (money preferences) and E (Admin API without `display_*`) in progress**Target:** Spree 6.0**Depends on:** `5.5-client-side-money-normalization.md` (canonical decimal-string contract), `6.0-6.1-split-adjustments.md` (typed `spree_tax_lines` / `spree_discounts` / `spree_fees` — landed, so they are in scope), `6.0-json-preferences.md` (decimal preferences are exact strings), `6.0-payment-gateways-monorepo.md` (Stripe lives in the monorepo; Adyen and PayPal Checkout are separate gems patched in the same release)**Author:** Damian + Claude@@ -39,6 +39,9 @@ All decided 2026-10-08; the ones marked *review* were changed or added after the- **`spree_adyen` and `spree_paypal_checkout` are not patched in their Spree 5 repositories** (decided 2026-10-09; amends "patch the gems you own in the same release"). Their `main` branches still target Spree 5 (`spree_admin`), where this API does not exist. Adyen takes money amounts when it is ported into `spree/providers` (constraint added to `6.0-payment-gateways-monorepo.md`); PayPal and third-party gateways keep working through the hundredths bridge until 6.1.- **PR A applies the ISO table to Spree's own rounding only; registering it over the Money gem moves to A2** (decided 2026-10-09). Registering changes `Money#cents` for HUF, which Stripe payment sessions read, and A2 is the only PR that may change what a gateway receives.+- **Money preferences have their own type** (decided 2026-10-09, after spree/spree#14852). A preference is declared `:money` for an amount and `:decimal` for a rate or a measure. `:money` is stored like a decimal, reports `money` in `preference_schema`, and is written on the API with at least the decimals of the record's `currency` preference and up to four, like a unit price; with no currency it keeps its exact decimal. Why: with one `:decimal` type the server and the dashboard could only guess money from a preference's name, so calculator amounts went out as `"12.5"` while every other amount was `"12.50"`. Both types refuse text such as `"1,599.99"`, which the old lenient cast read as 1. Ships in PR D.+- **The Admin API drops `display_*` fields** (decided 2026-10-09). Every amount is an exact decimal string with its currency, so the dashboard and seller panel format money themselves, in the admin's own language (`useMoneyLocale`); the server's strings were formatted in the request's language and could disagree with the editable fields beside them. The Store API keeps them for storefronts, webhooks and email templates. Ships in PR E, after the dashboards stop reading them.+## Design Details### Inventory: every `.to_f` and `Float(` outside specs (58 sites at `4ca24b8`)@@ -203,6 +206,17 @@ None changes a stored value of an existing two-decimal order.3. Specs that only pass after widening: KWD three-decimal order, VND order above 100,000,000, a `"0.0125"` USD unit price.4. Upgrade guide: the migration window, the online path, extension tables to widen (`spree_paypal_checkout_orders`).+**PR D — money preferences.**+1. The `:money` preference type, strict reading for `:decimal` and `:money`, and currency-aware serialization of preferences.+2. Every amount among the built-in calculator, rule and store preferences declared `:money`; rates, weights and volumes stay `:decimal`.+3. The settings form shows a money preference with its currency's symbol, and calculator summaries format it as money instead of guessing from the key.+4. Model preferences docs, upgrade guide, changeset; regenerate `docs/api-reference/*.yaml`.++**PR E — Admin API without `display_*`.**+1. Move every `display_*` read in the dashboard, the shared packages and the seller panel onto `formatMoney(amount, currency, useMoneyLocale())`.+2. Remove the admin-only `display_*` attributes and drop the ones Admin and Seller serializers inherit from the Store serializers.+3. Regenerate types, Zod schemas and the API reference; upgrade guide entry.+**Rounding conformance specs** (each states the exact expected `BigDecimal`): tax-inclusive VAT pricing; split payments summing exactly to the order total; partial refunds leaving the exact residual; largest-remainder promotion distribution summing to the promotion amount; captures of `"0.29"`, `"1.15"`, `"1234567.89"`; a KWD three-decimal order end to end; a JPY zero-decimal order end to end; a VND order above 100,000,000; a sub-cent unit price whose line total rounds to the exponent.Verification per PR: the changed specs locally, then `pnpm test:rspec core` and `pnpm test:rspec api` one at a time; for A2 also `pnpm test:rspec stripe`; for B `pnpm typecheck` and `pnpm test` in `packages/sdk-core`, `sdk`, `admin-sdk`, `seller-sdk`, and `pnpm exec tsc -b` in the dashboard.diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex 8707a3293f..1b9a142ebb 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -2148,8 +2148,10 @@ export type CommissionRateUpdateParams = Partial<CommissionRateCreateParams>* a STI subclass (payment provider, promotion action, promotion rule).** The `type` mirrors Spree's preference type system — `string`, `text`,- * `integer`, `decimal`, `boolean`, `array`, `password` — so admin UIs- * can switch on it to render the right input widget.+ * `integer`, `decimal`, `money`, `boolean`, `array`, `password` — so admin UIs+ * can switch on it to render the right input widget. A `money` value is a+ * decimal string in the currency of the record's `currency` preference, when+ * it has one; a `decimal` is a rate or measure, such as a percentage or a weight.*/export interface PreferenceField {key: stringdiff --git a/packages/dashboard-core/src/components/preferences-form.tsx b/packages/dashboard-core/src/components/preferences-form.tsxindex cc5de7c283..58e987718e 100644--- a/packages/dashboard-core/src/components/preferences-form.tsx+++ b/packages/dashboard-core/src/components/preferences-form.tsx@@ -10,6 +10,10 @@ import {FieldGroup,FieldLabel,Input,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ InputGroupText,SecretInput,Select,SelectContent,@@ -22,6 +26,8 @@ import {import { PlusIcon, TrashIcon } from '@spree/dashboard-ui/icons'import { useId, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'+import { currencyParts } from '../products/currency-parts'+import { useMoneyLocale } from '../products/use-money-locale'import { CurrencySelect } from './currency-select'import { StoreDatePicker } from './store-date-picker'@@ -47,7 +53,7 @@ export function defaultPreferences(// A decimal default declared as a Ruby integer arrives as a JSON number,// and the API refuses money sent back that way.out[field.key] =- field.type === 'decimal' && typeof field.default === 'number'+ (field.type === 'decimal' || field.type === 'money') && typeof field.default === 'number'? String(field.default): field.defaultcontinue@@ -122,6 +128,7 @@ export function PreferencesForm({redactPasswords={redactPasswords}currencyOptions={currencyOptions}inlineDatePickers={inlineDatePickers}+ currency={typeof values.currency === 'string' ? values.currency : undefined}/>))}</FieldGroup>@@ -136,6 +143,8 @@ interface PreferenceFieldProps {redactPasswords?: booleancurrencyOptions?: string[]inlineDatePickers?: boolean+ /** The currency a money preference is in, when the record names one. */+ currency?: string}export function PreferenceField({@@ -146,8 +155,10 @@ export function PreferenceField({redactPasswords,currencyOptions,inlineDatePickers,+ currency,}: PreferenceFieldProps) {const { t, i18n } = useTranslation()+ const moneyLocale = useMoneyLocale()const id = `preference-${field.key}`// Localize the field label from the preference key when no explicit// override is given, falling back to a humanized key for custom/extension@@ -232,6 +243,36 @@ export function PreferenceField({</Field>)+ case 'money':+ return (+ <Field>+ <FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>+ <InputGroup>+ {currency && (+ <InputGroupAddon>+ <InputGroupText>{currencyParts(currency, moneyLocale).symbol}</InputGroupText>+ </InputGroupAddon>+ )}+ <InputGroupInput+ id={id}+ type="number"+ step="any"+ placeholder={+ isMaxKey(field.key) ? t('admin.components.preferences_form.unlimited') : undefined+ }+ value={value === null || value === undefined ? '' : String(value)}+ onChange={(e) => {+ const raw = e.target.value+ if (raw === '') return onChange(null)+ // The API refuses money sent as a JSON number.+ onChange(isDecimalString(raw) ? raw : null)+ }}+ />+ </InputGroup>+ {description && <FieldDescription>{description}</FieldDescription>}+ </Field>+ )+case 'integer':case 'decimal':return (diff --git a/packages/dashboard-ui/src/spree/calculator-summary.tsx b/packages/dashboard-ui/src/spree/calculator-summary.tsxindex 632306370c..30de118c9e 100644--- a/packages/dashboard-ui/src/spree/calculator-summary.tsx+++ b/packages/dashboard-ui/src/spree/calculator-summary.tsx@@ -96,11 +96,9 @@ function formatField(if (value === null || value === undefined || value === '') return nullif (field.key === 'currency') return null+ if (field.type === 'money') return formatMoney(value, currency)if (field.type === 'decimal') {if (/(?:^|_)percent$/.test(field.key)) return `${value}%`- if (field.key === 'amount' || field.key.endsWith('_amount')) {- return formatMoney(value, currency)- }return `${humanize(field.key)}: ${value}`}if (field.type === 'boolean') {diff --git a/packages/dashboard/e2e/promotions.spec.ts b/packages/dashboard/e2e/promotions.spec.tsindex a293c29eb1..d883a8fbcc 100644--- a/packages/dashboard/e2e/promotions.spec.ts+++ b/packages/dashboard/e2e/promotions.spec.ts@@ -438,9 +438,9 @@ test.describe('promotions', () => {await expect(page.getByRole('heading', { name })).toBeVisible({ timeout: 15_000 })await openAdjustmentAction(page, /flat rate/i)- // Preferences carry no currency of their own, so the value reads back- // without trailing zeros.- await expect(page.getByRole('dialog').locator('#preference-amount')).toHaveValue(/^12\.50?$/)+ // A money preference is written to its calculator's currency, so the+ // amount keeps its cents.+ await expect(page.getByRole('dialog').locator('#preference-amount')).toHaveValue('12.50')await cancelEditor(page)await pagediff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rbindex 21d3ec6c4c..ddb8eaaf66 100644--- a/spree/core/app/models/concerns/spree/preference_schema.rb+++ b/spree/core/app/models/concerns/spree/preference_schema.rb@@ -78,7 +78,9 @@ module Spreewire[:choices] = field[:choices] if field[:choices].present?wire[:default] = nil if field[:type] == :password# A decimal default goes out as the decimal string the API takes back.- wire[:default] = Spree::Money::Rounding.format_decimal(field[:default]) if field[:type] == :decimal && field[:default].is_a?(Numeric)+ if %i[decimal money].include?(field[:type]) && field[:default].is_a?(Numeric)+ wire[:default] = Spree::Money::Rounding.format_decimal(field[:default])+ endwire.freezeend.freezeenddiff --git a/spree/core/app/models/spree/calculator/flat_rate.rb b/spree/core/app/models/spree/calculator/flat_rate.rbindex c0145fb44f..7e3cc812d3 100644--- a/spree/core/app/models/spree/calculator/flat_rate.rb+++ b/spree/core/app/models/spree/calculator/flat_rate.rb@@ -1,6 +1,6 @@module Spreeclass Calculator::FlatRate < Calculator- preference :amount, :decimal, default: 0+ preference :amount, :money, default: 0preference :currency, :string, default: -> { Spree::Store.default.default_currency }preference :apply_only_on_full_priced_items, :boolean, default: falsediff --git a/spree/core/app/models/spree/calculator/flexi_rate.rb b/spree/core/app/models/spree/calculator/flexi_rate.rbindex 4f97ff8d49..19107d7f39 100644--- a/spree/core/app/models/spree/calculator/flexi_rate.rb+++ b/spree/core/app/models/spree/calculator/flexi_rate.rb@@ -1,7 +1,7 @@module Spreeclass Calculator::FlexiRate < Calculator- preference :first_item, :decimal, default: 0.0- preference :additional_item, :decimal, default: 0.0+ preference :first_item, :money, default: 0.0+ preference :additional_item, :money, default: 0.0preference :max_items, :integer, default: 0preference :currency, :string, default: -> { Spree::Store.default.default_currency }preference :apply_only_on_full_priced_items, :boolean, default: falsediff --git a/spree/core/app/models/spree/calculator/price_sack.rb b/spree/core/app/models/spree/calculator/price_sack.rbindex 65375946ae..06a12cdd3f 100644--- a/spree/core/app/models/spree/calculator/price_sack.rb+++ b/spree/core/app/models/spree/calculator/price_sack.rb@@ -1,8 +1,8 @@module Spreeclass Calculator::PriceSack < Calculator- preference :minimal_amount, :decimal, default: 0- preference :normal_amount, :decimal, default: 0- preference :discount_amount, :decimal, default: 0+ preference :minimal_amount, :money, default: 0+ preference :normal_amount, :money, default: 0+ preference :discount_amount, :money, default: 0preference :currency, :string, default: -> { Spree::Store.default.default_currency }def self.descriptiondiff --git a/spree/core/app/models/spree/calculator/shipping/digital_delivery.rb b/spree/core/app/models/spree/calculator/shipping/digital_delivery.rbindex 3389bd5fe4..7d8799f5ce 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,7 @@ module Spreeclass DigitalDelivery < ShippingCalculatorinclude Spree::Calculator::CurrencyAmounts- preference :amount, :decimal, default: 0+ preference :amount, :money, default: 0preference :currency, :string, default: -> { Spree::Store.default.default_currency }def self.descriptiondiff --git a/spree/core/app/models/spree/calculator/shipping/flat_rate.rb b/spree/core/app/models/spree/calculator/shipping/flat_rate.rbindex bc8abff74c..61fb68741e 100644--- a/spree/core/app/models/spree/calculator/shipping/flat_rate.rb+++ b/spree/core/app/models/spree/calculator/shipping/flat_rate.rb@@ -3,14 +3,14 @@ module Spreeclass FlatRate < ShippingCalculatorinclude Spree::Calculator::CurrencyAmounts- preference :amount, :decimal, default: 0+ preference :amount, :money, default: 0# @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.preference :currency, :string, default: -> { Spree::Store.default.default_currency }- preference :minimum_item_total, :decimal, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'- preference :maximum_item_total, :decimal, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'+ preference :minimum_item_total, :money, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'+ preference :maximum_item_total, :money, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'preference :minimum_weight, :decimal, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'preference :maximum_weight, :decimal, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'diff --git a/spree/core/app/models/spree/calculator/shipping/flexi_rate.rb b/spree/core/app/models/spree/calculator/shipping/flexi_rate.rbindex 7333a20795..eb92a59fab 100644--- a/spree/core/app/models/spree/calculator/shipping/flexi_rate.rb+++ b/spree/core/app/models/spree/calculator/shipping/flexi_rate.rb@@ -1,8 +1,8 @@module Spreemodule Calculator::Shippingclass FlexiRate < ShippingCalculator- preference :first_item, :decimal, default: 0.0- preference :additional_item, :decimal, default: 0.0+ preference :first_item, :money, default: 0.0+ preference :additional_item, :money, default: 0.0preference :max_items, :integer, default: 0preference :currency, :string, default: -> { Spree::Store.default.default_currency }diff --git a/spree/core/app/models/spree/calculator/shipping/per_item.rb b/spree/core/app/models/spree/calculator/shipping/per_item.rbindex 5a850a6b94..dfa1a9d4a5 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,7 @@ module Spreeclass PerItem < ShippingCalculatorinclude Spree::Calculator::CurrencyAmounts- preference :amount, :decimal, default: 0+ preference :amount, :money, default: 0preference :currency, :string, default: -> { Spree::Store.default.default_currency }def self.descriptiondiff --git a/spree/core/app/models/spree/calculator/shipping/price_sack.rb b/spree/core/app/models/spree/calculator/shipping/price_sack.rbindex a66e46cf6f..2ebb4402a7 100644--- a/spree/core/app/models/spree/calculator/shipping/price_sack.rb+++ b/spree/core/app/models/spree/calculator/shipping/price_sack.rb@@ -1,9 +1,9 @@module Spreemodule Calculator::Shippingclass PriceSack < ShippingCalculator- preference :minimal_amount, :decimal, default: 0- preference :normal_amount, :decimal, default: 0- preference :discount_amount, :decimal, default: 0+ preference :minimal_amount, :money, default: 0+ preference :normal_amount, :money, default: 0+ preference :discount_amount, :money, default: 0preference :currency, :string, default: -> { Spree::Store.default.default_currency }# Single-currency amounts: quoting another currency would mislabeldiff --git a/spree/core/app/models/spree/calculator/tiered_flat_rate.rb b/spree/core/app/models/spree/calculator/tiered_flat_rate.rbindex ac1f16fc55..9042a4b281 100644--- a/spree/core/app/models/spree/calculator/tiered_flat_rate.rb+++ b/spree/core/app/models/spree/calculator/tiered_flat_rate.rb@@ -2,7 +2,7 @@ module Spreeclass Calculator::TieredFlatRate < Calculatorinclude Spree::Calculator::Tiers- preference :base_amount, :decimal, default: 0+ preference :base_amount, :money, default: 0preference :currency, :string, default: -> { Spree::Store.default.default_currency }def self.descriptiondiff --git a/spree/core/app/models/spree/commission_rules/item_total_rule.rb b/spree/core/app/models/spree/commission_rules/item_total_rule.rbindex be75f49aa2..c1df0f696b 100644--- a/spree/core/app/models/spree/commission_rules/item_total_rule.rb+++ b/spree/core/app/models/spree/commission_rules/item_total_rule.rb@@ -14,8 +14,8 @@ module Spree# This rule is the reason commission rules became classes. It could not# exist while a rule was only able to name a record.class ItemTotalRule < Spree::CommissionRule- preference :min_amount, :decimal, nullable: true- preference :max_amount, :decimal, nullable: true+ preference :min_amount, :money, nullable: true+ preference :max_amount, :money, nullable: truedef applicable?(context)# Weighed exactly as the fee will weigh it, per this rate's own base.diff --git a/spree/core/app/models/spree/delivery_method_rules/item_total_rule.rb b/spree/core/app/models/spree/delivery_method_rules/item_total_rule.rbindex 94a76a5822..9331b136ba 100644--- a/spree/core/app/models/spree/delivery_method_rules/item_total_rule.rb+++ b/spree/core/app/models/spree/delivery_method_rules/item_total_rule.rb@@ -4,8 +4,8 @@ module Spree# owner's currency). Empty preferences pass — half-configured rules fail# open per-rule, matching the PromotionRule/PriceRule convention.class ItemTotalRule < Spree::DeliveryMethodRule- preference :minimum_amount, :decimal, default: nil, nullable: true- preference :maximum_amount, :decimal, default: nil, nullable: true+ preference :minimum_amount, :money, default: nil, nullable: true+ preference :maximum_amount, :money, default: nil, nullable: truedef eligible?(package)total = package.item_totaldiff --git a/spree/core/app/models/spree/promotion/rules/item_total.rb b/spree/core/app/models/spree/promotion/rules/item_total.rbindex 41c233d286..e338c2c5ab 100644--- a/spree/core/app/models/spree/promotion/rules/item_total.rb+++ b/spree/core/app/models/spree/promotion/rules/item_total.rb@@ -4,9 +4,9 @@ module Spreeclass Promotionmodule Rulesclass ItemTotal < Spree::PromotionRule- preference :amount_min, :decimal, default: 100.00+ preference :amount_min, :money, default: 100.00preference :operator_min, :string, default: '>'- preference :amount_max, :decimal, default: nil, nullable: true+ preference :amount_max, :money, default: nil, nullable: truepreference :operator_max, :string, default: '<'OPERATORS_MIN = ['gt', 'gte']diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 51ab95c5b7..4df952501f 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -89,7 +89,7 @@ module Spree# What a seller's balance must reach before a settlement is worth sending;# below it the balance carries to the next period. Zero pays whatever is# owed, which is right for a provider that moves money for free.- preference :default_minimum_payout_amount, :decimal, default: 0+ preference :default_minimum_payout_amount, :money, default: 0# Checkout preferences# Store-level fallback for the channel-owned `guest_checkout` preference# (see Spree::Channel::Gating). Retained so existing accessors keep working.diff --git a/spree/core/lib/spree/core/preferences/masking.rb b/spree/core/lib/spree/core/preferences/masking.rbindex 0c48d14dc6..3e4515aaf8 100644--- a/spree/core/lib/spree/core/preferences/masking.rb+++ b/spree/core/lib/spree/core/preferences/masking.rb@@ -56,6 +56,25 @@ module Spree# @param preferable [#preferences, #preference_schema, nil] any object# that includes `Spree::Preferences::Preferable` and `Spree::PreferenceSchema`# @return [Hash{String => Object}]+ # Money is written to at least the decimals of the currency the record+ # names (a calculator's `currency` preference), keeping up to four like+ # a unit price, so a per-item amount below a cent survives a round trip.+ # A money preference with no currency of its own, such as an order-total+ # rule that applies to any currency, keeps its exact decimal.+ def self.wire_value(preferable, type, value)+ case type+ when :password then mask(value)+ when :money+ # Stored as the JSON text of a decimal.+ amount = value.is_a?(String) ? BigDecimal(value, exception: false) : value+ return value unless amount.is_a?(Numeric)++ currency = preferable.try(:preferred_currency) if preferable.try(:has_preference?, :currency)+ currency.present? ? Spree::Money::Rounding.format(amount, currency, unit_price: true) : Spree::Money::Rounding.format_decimal(amount)+ else value+ end+ end+def self.serialize(preferable)return {} if preferable.nil?@@ -64,7 +83,7 @@ module Spree# reveal what it would fall back to — read through the record,# because a secret lives in its own column.value = preferable.stored_preference(field[:key]) { nil }- hash[field[:key_string] || field[:key].to_s] = field[:type] == :password ? mask(value) : value+ hash[field[:key_string] || field[:key].to_s] = wire_value(preferable, field[:type], value)endendenddiff --git a/spree/core/lib/spree/core/preferences/preferable.rb b/spree/core/lib/spree/core/preferences/preferable.rbindex e7870a77fd..06d20cd955 100644--- a/spree/core/lib/spree/core/preferences/preferable.rb+++ b/spree/core/lib/spree/core/preferences/preferable.rb@@ -34,7 +34,7 @@ module Spree::Preferences::Preferablereturn value unless value.is_a?(String)case type- when :decimal then BigDecimal(value, exception: false) || value+ when :decimal, :money then BigDecimal(value, exception: false) || valuewhen :datetime then Time.zone.iso8601(value)else valueend@@ -218,10 +218,12 @@ module Spree::Preferences::Preferableendwhen :passwordvalue.to_s- when :decimal- decimal_value = value.presence+ when :decimal, :money+ # A number or canonical decimal text only: "1,599.99" raises rather+ # than being read as 1.+ decimal_value = value.is_a?(String) ? value.presence : valuedecimal_value ||= 0 unless nullable- decimal_value.present? ? decimal_value.to_s.to_d : decimal_value+ decimal_value.nil? ? nil : Spree::Money::Rounding.parse_decimal(decimal_value)when :integerint_value = value.presenceint_value ||= 0 unless nullablediff --git a/spree/core/spec/models/spree/preferences/masking_spec.rb b/spree/core/spec/models/spree/preferences/masking_spec.rbindex 09680c4a66..0a87515d49 100644--- a/spree/core/spec/models/spree/preferences/masking_spec.rb+++ b/spree/core/spec/models/spree/preferences/masking_spec.rb@@ -96,6 +96,38 @@ RSpec.describe Spree::Preferences::Masking doexpect(described_class.serialize(preferable)['api_secret']).to eq("#{'•' * 16}alue")end+ context 'with money preferences' do+ let(:preferable_class) do+ Class.new(Spree::Calculator) do+ preference :amount, :money, default: 0+ preference :currency, :string, default: 'USD'++ def self.name+ 'TestMoneyCalculator'+ end+ end+ end++ it "writes money to the record's currency's decimals" do+ preferable.set_preference(:amount, '12.5')++ expect(described_class.serialize(preferable)['amount']).to eq('12.50')+ end++ it 'keeps an amount below a cent, as a unit price does' do+ preferable.set_preference(:amount, '0.0125')++ expect(described_class.serialize(preferable)['amount']).to eq('0.0125')+ end++ it 'writes whole yen' do+ preferable.set_preference(:currency, 'JPY')+ preferable.set_preference(:amount, '1500')++ expect(described_class.serialize(preferable)['amount']).to eq('1500')+ end+ end+it 'returns nil for unset password preferences (no default leakage)' dopreferable.preferences.delete(:api_secret)diff --git a/spree/core/spec/models/spree/preferences/preferable_spec.rb b/spree/core/spec/models/spree/preferences/preferable_spec.rbindex 424a74f988..db19adb81e 100644--- a/spree/core/spec/models/spree/preferences/preferable_spec.rb+++ b/spree/core/spec/models/spree/preferences/preferable_spec.rb@@ -163,6 +163,10 @@ describe Spree::Preferences::Preferable, type: :model doexpect(@a.get_preference(:if_decimal)).to eq(0.0)end+ it 'refuses text it would otherwise misread' do+ expect { @a.set_preference(:if_decimal, '1,599.99') }.to raise_error(Spree::Money::InvalidFormat)+ end+it 'stores and returns a decimal default as a BigDecimal, so setting the same amount is not a change' doA.preference :decimal_with_default, :decimal, default: 0.0record = A.create!