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.

Changed money preferences to be checked by their declared type (V-3738) (#14870)

Damian Legawiec526270306b9d
diff --git a/docs/api-reference/admin-api/monetary-amounts.mdx b/docs/api-reference/admin-api/monetary-amounts.mdx
index e4f62c76a7..ceea92d4b0 100644
--- a/docs/api-reference/admin-api/monetary-amounts.mdx
+++ b/docs/api-reference/admin-api/monetary-amounts.mdx
@@ -77,7 +77,7 @@ This convention applies to all monetary fields across all resources, including b
### Amounts inside `preferences`
-Calculators and some promotion rules carry their amounts inside an untyped `preferences` object (`Record<string, unknown>`) rather than as top-level fields. The same canonical-string convention applies to the money-valued keys within that hash — they read back as strings and accept canonical decimal strings on write. The keys that are money:
+Calculators and rules carry their amounts inside a `preferences` object rather than as top-level fields. Each type lists its preferences with their types in `preference_schema` (from its `…/types` endpoint), and a preference of type `money` follows the same convention as every other amount: a decimal string, read back with the decimals of the record's `currency` preference. On write, a money preference that is not a decimal string, or has more decimals than its currency, is refused with `422` and `invalid_preferences`, naming the field (`/calculator/preferences/amount`). The money preferences Spree ships:
| Resource | Money keys in `preferences` |
|----------|------------------------------|
@@ -88,7 +88,7 @@ Calculators and some promotion rules carry their amounts inside an untyped `pref
| **Calculator** `flat_rate` (shipping) | `amount`, `minimum_item_total`, `maximum_item_total` |
| **Promotion Rule** `item_total` | `amount_min`, `amount_max` |
-Percentage keys (`percent`, `flat_percent`, `base_percent`) are rates: decimal strings too (`"10"`), with no fixed number of decimals. Weights (`minimum_weight`, `maximum_weight`) and quantities (`max_items`, `min_quantity`) are not money and stay numbers. Promotion actions (`create_adjustment`, `create_item_adjustments`) hold their money inside a nested `calculator.preferences`, per the calculator rows above.
+Read an extension's money preferences from `preference_schema` rather than from this table. Percentage keys (`percent`, `flat_percent`, `base_percent`) are rates: decimal strings too (`"10"`), with no fixed number of decimals. Weights (`minimum_weight`, `maximum_weight`) and quantities (`max_items`, `min_quantity`) are not money and stay numbers. Promotion actions (`create_adjustment`, `create_item_adjustments`) hold their money inside a nested `calculator.preferences`, per the calculator rows above.
## Rates and percentages
diff --git a/docs/developer/customization/model-preferences.mdx b/docs/developer/customization/model-preferences.mdx
index 54282e7e32..48405c8f0b 100644
--- a/docs/developer/customization/model-preferences.mdx
+++ b/docs/developer/customization/model-preferences.mdx
@@ -249,6 +249,12 @@ 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.
+An amount with more decimals than its currency has (`"4.505"` dollars, `"450.50"` yen) is refused when the preferences are assigned through the API. When the currency lives somewhere other than a `currency` preference, name its source, another preference or a method of the record:
+
+```ruby server/app/models/spree/calculator/handling_fee.rb
+preference :amount, :money, default: 0, currency: :settlement_currency
+```
+
## Secret preferences
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index 2bcfcbc90f..69be6f7028 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -910,7 +910,7 @@ Other changes that come with it:
- **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.
- **The Admin and Seller APIs no longer return `display_*` money fields.** Responses carry the amount (`"29.99"`) with its currency, and the client formats it in the reader's own language. Before 6.0 the server formatted a copy in the request's language, which could disagree with the editable amount beside it. Format with `Intl.NumberFormat` or your platform's equivalent. The Store API, webhook payloads and email templates keep their `display_*` fields, and labels such as `display_name` are unchanged.
- **Email templates format money with the `money` filter.** The default templates print `{{ order.total | money }}` instead of `{{ order.display_total }}`; the output is the same. Email data gains the raw amounts the templates needed (`total_minus_store_credits`, a line item's `amount`, a parcel's `cost` and `unpriced`, a return's `refunded_total`). The `display_*` fields are still sent, so a template customized before 6.0 keeps working; merchants who customized one see the "updated by Spree" notice in the email editor.
-- **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.
+- **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. Money preferences are checked by their type on write: a value that is not a decimal string, or has more decimals than its currency, is refused with `invalid_preferences` and a pointer to the field (`/calculator/preferences/amount`), rather than `invalid_money_format`.
- **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.md
index 237a5855fb..4c185e8a05 100644
--- a/docs/plans/6.0-money-correctness.md
+++ b/docs/plans/6.0-money-correctness.md
@@ -44,6 +44,8 @@ All decided 2026-10-08; the ones marked *review* were changed or added after the
- **Email templates format money with the `money` filter** (decided 2026-10-10). The default templates print raw amounts through `money` instead of the serializers' `display_*` fields, which gives the same output and leaves one way to format money in a template. The `display_*` fields stay in email data, so a template a merchant customized before 6.0 keeps rendering; whether to remove them later is a separate decision, since customized templates live in the database.
+- **Money preferences are checked by their type** (decided 2026-10-11). Preferences assigned through the API are validated against the JSON Schema built from their declarations, which already refuses a `:money` value that is not a decimal string; `assign_preferences` now also refuses one with more decimals than its currency, read from the payload's or the record's `currency` preference or from the source a `currency:` option names. The name-based Admin and Seller check skips `preferences`, so an extension's money preference is checked whatever it is called and a text preference named like money (`rate`) is no longer refused.
+
## Design Details
### Inventory: every `.to_f` and `Float(` outside specs (58 sites at `4ca24b8`)
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/strict_money_params.rb b/spree/api/app/controllers/concerns/spree/api/v3/strict_money_params.rb
index 384fc3b454..87937fc3f6 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/strict_money_params.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/strict_money_params.rb
@@ -30,6 +30,11 @@ module Spree
# Values the merchant or a provider owns, stored as sent.
OPAQUE_KEYS = %w[metadata custom_fields external_data].freeze
+ # Preferences are checked against their declared types when assigned
+ # (Spree::Preferences::Preferable#assign_preferences), so a money
+ # preference is recognized by its type rather than its name.
+ TYPED_KEYS = %w[preferences calculator_preferences].freeze
+
included do
before_action :refuse_noncanonical_decimals, if: -> { request.post? || request.patch? || request.put? }
end
@@ -45,7 +50,7 @@ module Spree
when Hash
currency = node['currency'].presence || currency
node.each do |key, value|
- next if OPAQUE_KEYS.include?(key)
+ next if OPAQUE_KEYS.include?(key) || TYPED_KEYS.include?(key)
if scalar?(value) && MONEY_KEYS.include?(key)
check_money(key, value, currency, UNIT_PRICE_KEYS.include?(key) || (key == 'amount' && parent == 'prices'))
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 230320324e..fe6853da30 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
@@ -248,6 +248,26 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
expect(delivery_method.reload.calculator).to eq(calculator)
end
+ # The calculator's preferences are checked by their declared types, so a
+ # money amount is refused for its currency's decimals whatever it is called.
+ it 'refuses a calculator amount with more decimals than its currency has' do
+ patch :update, params: {
+ id: delivery_method.prefixed_id,
+ calculator: { preferences: { amount: '9.995', currency: 'USD' } }
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('invalid_preferences')
+ expect(json_response['error']['details']['/calculator/preferences/amount'].first).to match(/2 decimal places for USD/)
+ end
+
+ it 'refuses a calculator amount sent as a JSON number' do
+ patch :update, params: { id: delivery_method.prefixed_id, calculator: { preferences: { amount: 9.99 } } }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['details']).to have_key('/calculator/preferences/amount')
+ end
+
it 'keeps the current calculator when the rest of the update is refused' do
calculator = delivery_method.calculator
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 5522fd9215..85a53370a8 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -875,6 +875,7 @@ en:
invalid_status: Invalid status
invalid_storefront_access: is not a valid storefront access level
items_not_a_list: items must be a list of objects
+ money_preference_too_many_decimals: has more than %{count} decimal places for %{currency}
must_be_greater_than_min_amount: must be greater than or equal to the minimum
no_pickup_point_provider: this delivery method has no pickup point provider configured
not_cancellable: cannot be canceled once its goods have been dispatched
diff --git a/spree/core/lib/spree/core/preferences/masking.rb b/spree/core/lib/spree/core/preferences/masking.rb
index 4a9ad4c29f..bf8c8c9015 100644
--- a/spree/core/lib/spree/core/preferences/masking.rb
+++ b/spree/core/lib/spree/core/preferences/masking.rb
@@ -52,7 +52,7 @@ module Spree
# 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)
+ def self.wire_value(preferable, key, type, value)
case type
when :password then mask(value)
when :money
@@ -60,7 +60,7 @@ module Spree
amount = value.is_a?(String) ? BigDecimal(value, exception: false) : value
return value unless amount.is_a?(Numeric)
- currency = preferable.try(:has_preference?, :currency) ? preferable.try(:preferred_currency) : nil
+ currency = preferable.money_preference_currency(key)
currency.present? ? Spree::Money::Rounding.format(amount, currency, unit_price: true) : Spree::Money::Rounding.format_decimal(amount)
else value
end
@@ -89,7 +89,7 @@ module Spree
if definition[:of] == :id
prefixed_ids(value, definition)
elsif %i[password money].include?(field[:type])
- wire_value(preferable, field[:type], value)
+ wire_value(preferable, field[:key], field[:type], value)
elsif definition[:keys] == :currency && definition[:values] == :money
money_by_currency(preferable.wire_preference_value(value, definition))
else
diff --git a/spree/core/lib/spree/core/preferences/preferable.rb b/spree/core/lib/spree/core/preferences/preferable.rb
index a43bd44eb7..e8c31131d9 100644
--- a/spree/core/lib/spree/core/preferences/preferable.rb
+++ b/spree/core/lib/spree/core/preferences/preferable.rb
@@ -99,6 +99,24 @@ module Spree::Preferences::Preferable
choices.respond_to?(:call) ? choices.call : choices
end
+ # The currency a `:money` preference is in: its declared `currency:` source
+ # (another preference, or a method of the record), else the record's own
+ # `currency` preference. Values about to be assigned win over stored ones,
+ # so a request changing both the amount and its currency is read as one.
+ #
+ # @param name [Symbol, String]
+ # @param pending [Hash{String => Object}] values not yet assigned
+ # @return [String, nil] nil for an amount in any currency
+ def money_preference_currency(name, pending = {})
+ declared = preference_definition(name)[:currency]
+ source = declared || :currency
+ # A currency sent in the same payload wins, even a blank one clearing it.
+ return pending[source.to_s].presence if pending.key?(source.to_s)
+ return get_preference(source).presence if has_preference?(source)
+
+ public_send(source).presence if declared && respond_to?(source)
+ end
+
def has_preference!(name)
raise NoMethodError, "#{name} preference not defined" unless has_preference? name
end
@@ -174,6 +192,7 @@ module Spree::Preferences::Preferable
values = values.respond_to?(:to_unsafe_h) ? values.to_unsafe_h : values.to_h
values = values.deep_stringify_keys
failures = self.class.preference_failures(values)
+ failures += money_precision_failures(values) if failures.empty?
raise Spree::Preferences::InvalidPreferences.new(failures, prefix: pointer) if failures.any?
values.each do |key, value|
@@ -215,6 +234,24 @@ module Spree::Preferences::Preferable
private
+ # A `:money` value with more decimals than its currency has is refused, as
+ # every other amount on the API is. The schema has already checked the
+ # format; it cannot know the currency.
+ def money_precision_failures(values)
+ values.filter_map do |key, value|
+ next unless value.is_a?(String) && has_preference?(key) && preference_type(key) == :money
+
+ currency = money_preference_currency(key, values)
+ amount = BigDecimal(value, exception: false)
+ next if currency.blank? || amount.nil?
+
+ places = Spree::Money::Rounding.precision(currency)
+ next if amount.round(places) == amount
+
+ { pointer: "/#{key}", message: I18n.t('spree.errors.messages.money_preference_too_many_decimals', count: places, currency: currency) }
+ end
+ end
+
def preference_definition(name)
has_preference! name
self.class.preference_definitions[name.to_sym]
diff --git a/spree/core/lib/spree/core/preferences/preferable_class_methods.rb b/spree/core/lib/spree/core/preferences/preferable_class_methods.rb
index fe72eafdf0..ee02a6fb5e 100644
--- a/spree/core/lib/spree/core/preferences/preferable_class_methods.rb
+++ b/spree/core/lib/spree/core/preferences/preferable_class_methods.rb
@@ -70,6 +70,9 @@ module Spree::Preferences
# @option options [String, Proc] :model the record class an `of: :id` list points at
# @option options [Proc] :scope `->(owner) { relation }` the ids must be found in
# @option options [Array, Proc] :choices the fixed set a value must come from
+ # @option options [Symbol] :currency where a `:money` preference's currency comes
+ # from: another preference or a method of the record. Defaults to the
+ # record's `currency` preference; with neither, the amount is in any currency.
def preference(name, type, *args)
name = name.to_sym
secret = type == :password
@@ -80,7 +83,7 @@ module Spree::Preferences
options = args.extract_options!
options.assert_valid_keys(:default, :deprecated, :in, :choices, :internal, :nullable, :parse_on_set,
- :of, :keys, :values, :properties, :format, :model, :scope)
+ :of, :keys, :values, :properties, :format, :model, :scope, :currency)
if options.key?(:in)
Spree::Deprecation.warn("`preference :#{name}, in:` is deprecated. Use `choices:` instead.")
options[:choices] ||= options.delete(:in)
@@ -110,7 +113,8 @@ module Spree::Preferences
properties: options[:properties],
format: options[:format],
model: options[:model],
- scope: options[:scope]
+ scope: options[:scope],
+ currency: options[:currency]
}
PreferableClassMethods.declarations += 1
@@ -185,6 +189,7 @@ module Spree::Preferences
raise ArgumentError, "Unknown format `#{options[:format]}` on preference `#{name}`"
end
raise ArgumentError, "`of: :id` needs `model:` on preference `#{name}`" if options[:of] == :id && options[:model].blank?
+ raise ArgumentError, "`currency:` applies to a :money preference, not `#{name}` (#{type})" if options[:currency] && type != :money
raise ArgumentError, "`of: :object` needs `properties:` on preference `#{name}`" if options[:of] == :object && options[:properties].blank?
missing = case type
diff --git a/spree/core/spec/models/spree/preferences/preferable_spec.rb b/spree/core/spec/models/spree/preferences/preferable_spec.rb
index 147b890245..ffb37db553 100644
--- a/spree/core/spec/models/spree/preferences/preferable_spec.rb
+++ b/spree/core/spec/models/spree/preferences/preferable_spec.rb
@@ -510,6 +510,7 @@ describe Spree::Preferences::Preferable, type: :model do
expect { preferable_class.preference :wrong_of, :string, of: :integer }.to raise_error(ArgumentError, /`of:` applies to an :array/)
expect { preferable_class.preference :id_without_model, :array, of: :id }.to raise_error(ArgumentError, /needs `model:`/)
expect { preferable_class.preference :unknown_item, :array, of: :thing }.to raise_error(ArgumentError, /Unknown item type/)
+ expect { preferable_class.preference :wrong_currency, :decimal, currency: :currency }.to raise_error(ArgumentError, /`currency:` applies to a :money/)
end
describe '#assign_preferences' do
@@ -532,6 +533,42 @@ describe Spree::Preferences::Preferable, type: :model do
.to raise_error(Spree::Preferences::InvalidPreferences, %r{/preferences/channel_ids/0})
end
+ context 'with an amount of money' do
+ before do
+ preferable_class.preference :fee, :money, default: 0
+ preferable_class.preference :currency, :string, default: 'USD'
+ end
+
+ it 'refuses more decimals than the currency has, naming the value' do
+ expect { record.assign_preferences({ 'fee' => '12.505' }) }
+ .to raise_error(Spree::Preferences::InvalidPreferences, %r{/preferences/fee}) { |error| expect(error.failures.first[:message]).to match(/2 decimal places for USD/) }
+ expect { record.assign_preferences({ 'fee' => '12.50' }) }.not_to raise_error
+ end
+
+ it 'reads the currency sent with the amount before the stored one' do
+ expect { record.assign_preferences({ 'fee' => '12.50', 'currency' => 'JPY' }) }
+ .to raise_error(Spree::Preferences::InvalidPreferences, /0 decimal places for JPY/)
+ expect { record.assign_preferences({ 'fee' => '1250', 'currency' => 'JPY' }) }.not_to raise_error
+ expect(record.money_preference_currency(:fee, { 'currency' => '' })).to be_nil
+ end
+
+ it 'takes the currency from the source its declaration names' do
+ preferable_class.preference :surcharge, :money, default: 0, currency: :settlement_currency
+ preferable_class.define_method(:settlement_currency) { 'KWD' }
+
+ expect(record.money_preference_currency(:surcharge)).to eq('KWD')
+ expect { record.assign_preferences({ 'surcharge' => '1.250' }) }.not_to raise_error
+ expect { record.assign_preferences({ 'surcharge' => '1.2505' }) }.to raise_error(Spree::Preferences::InvalidPreferences)
+ end
+ end
+
+ it 'leaves an amount in any currency to the format check' do
+ preferable_class.preference :threshold, :money, default: 0
+
+ expect(record.money_preference_currency(:threshold)).to be_nil
+ expect { record.assign_preferences({ 'threshold' => '12.505' }) }.not_to raise_error
+ end
+
it 'refuses an id outside the declared scope' do
other_channel = create(:channel, store: create(:store))