Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fixed review findings in the money changes
Damian Legawiecb39dfde3e45f
diff --git a/docs/changelog.mdx b/docs/changelog.mdxindex 8ff443af63..159a616044 100644--- a/docs/changelog.mdx+++ b/docs/changelog.mdx@@ -18,7 +18,7 @@ Keep up with the latest features and improvements in Spree Commerce!<Update label="Prices save correctly in every language" description="October 9, 2026" tags={["Pricing", "Dashboard"]}>Stores whose language writes a comma as the decimal separator, such as Dutch, German or French, could save the wrong price. A price entered as €49,50 was stored as €4950,00, and saving an unchanged €99 again turned it into €990 and then €9900. Prices, costs, weights and dimensions are now saved exactly as entered, whatever the store's language.- Taxes and discounts in yen are now rounded to whole yen, and partial captures in yen are recorded at their real amount.+ Taxes and discounts in yen are now rounded to whole yen.The dashboard now shows and reads amounts in your own number format, whatever the currency: if your dashboard is in German you type `1.234,56` for dollars and euros alike.diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex 56fbdd7342..83e2d8804e 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -822,7 +822,7 @@ Other changes that come with it:- **Numbers are no longer parsed by locale.** Price, variant, payment, refund, store credit, gift card, discount and fee amounts are stored as sent. Before 6.0 they were re-read under the request's language, so a store whose language writes a comma decimal (Dutch, German, French) saved the dashboard's `49.50` as 4950, and an unchanged price grew tenfold on each save. Send canonical decimal strings (`"1234.56"`) and convert localized input in the client. `Spree::LocalizedNumber` still works with a warning until 6.1. If your prices were saved in a comma-decimal store before upgrading, check them.- **Rounding follows the currency.** Taxes, percentage discounts, promotion splits and shipping markups round to the currency's own decimal places from the ISO 4217 table: whole yen, three decimals for dinar. Two-decimal currencies are unchanged. Open carts in other currencies may change by less than one minor unit the next time they are recalculated. Placed orders do not change. Spree now gives the Hungarian forint two decimal places, as ISO 4217 does.-- **Capture records in yen and dinar were wrong.** A partial or manual capture in a currency without two decimals was recorded in the wrong unit: 100 times too much in yen, a tenth in dinar. New captures are recorded correctly. To list the old records, writing nothing, run:+- **Capture records in yen and dinar may be wrong.** A capture in a currency without two decimals could be recorded in the wrong unit: 100 times too much in yen, a tenth in dinar. To list those records, writing nothing, run:<CodeGroup>diff --git a/docs/plans/6.0-money-correctness.md b/docs/plans/6.0-money-correctness.mdindex 56c5f2b3cf..48ff0ed2a9 100644--- a/docs/plans/6.0-money-correctness.md+++ b/docs/plans/6.0-money-correctness.md@@ -9,7 +9,7 @@## Summary-Spree stores money in decimal columns, but four things still make amounts wrong or ambiguous before 6.0. Some money paths pass through floats (`.to_f` in Ruby, `parseFloat` in the dashboard), so a captured `"1.15"` can become `114` cents. The API does not agree with itself on what a money field looks like: most fields are strings, a few are JSON numbers, and the strings are not normalized (`"10.0"`, never `"10.00"`). Payment gateways receive a bare integer in hundredths of the currency, which is the right unit only for two-decimal currencies, while Stripe sessions use ISO minor units — and Stripe's own units are neither (ISK, HUF, TWD carry special rules). And the columns are `decimal(10, 2)`, which cannot hold a Kuwaiti dinar's third decimal, a sub-cent B2B unit price, or a large Vietnamese dong order. This plan removes floats from money paths in Ruby and TypeScript and writes the rule into `CLAUDE.md`, hands gateways an amount with its currency and lets each adapter convert to its provider's unit, makes every money field on the wire a decimal string written to a published per-currency exponent, and widens the money columns to `decimal(19, 4)`. It ships as four pull requests: A (floats out), A2 (gateway amounts), B (wire contract), C (precision).+Spree stores money in decimal columns, but four things still make amounts wrong or ambiguous before 6.0. Some money paths pass through floats (`.to_f` in Ruby, `parseFloat` in the dashboard), which cannot hold most decimal amounts exactly and are only rescued by a rounding step that happens to follow. The API does not agree with itself on what a money field looks like: most fields are strings, a few are JSON numbers, and the strings are not normalized (`"10.0"`, never `"10.00"`). Payment gateways receive a bare integer in hundredths of the currency, which is the right unit only for two-decimal currencies, while Stripe sessions use ISO minor units — and Stripe's own units are neither (ISK, HUF, TWD carry special rules). And the columns are `decimal(10, 2)`, which cannot hold a Kuwaiti dinar's third decimal, a sub-cent B2B unit price, or a large Vietnamese dong order. This plan removes floats from money paths in Ruby and TypeScript and writes the rule into `CLAUDE.md`, hands gateways an amount with its currency and lets each adapter convert to its provider's unit, makes every money field on the wire a decimal string written to a published per-currency exponent, and widens the money columns to `decimal(19, 4)`. It ships as four pull requests: A (floats out), A2 (gateway amounts), B (wire contract), C (precision).## Key Decisions (do not deviate without discussion)@@ -99,7 +99,7 @@ About 50–65 `Number(...)` / `parseFloat(...)` calls in `packages/dashboard`, `Today `payment_method.authorize/purchase/capture/credit` receive `Spree::Money#amount_in_cents`, the amount in hundredths for every currency (1000 JPY → `100000`; 1.505 KWD → `151`), while Stripe sessions use `Money#cents`, the ISO minor unit (1000 JPY → `1000`). The capture event then reads the hundredths value back as minor units: a 1000 JPY capture records 100,000 JPY, a 1.500 KWD capture records 0.150 KWD. `Payment#captured_amount` sums those events and the capture flow resizes the payment from that sum, so the error can reach the payment's own amount.-PR A fixes the recording without touching what any gateway receives: the capture event is the hundredths integer divided by 100, in BigDecimal, which is correct for every currency the hundredths unit can express. PR A2 then changes the interface:+The two capture callers do not even agree with each other: an admin capture passes hundredths, a capture on dispatch passes the currency's minor unit, and the workflow records both the same way. No fix to the recording alone is right for both, so PR A only removes the float and keeps every unit as it was; PR A2 fixes the recording with the interface, when the workflow receives a `Spree::Money`:```rubyclass Spree::Gateway@@ -158,7 +158,7 @@ Cost: a scale change rewrites the table under an exclusive lock on PostgreSQL, aNone changes a stored value of an existing two-decimal order.-1. **New capture events in zero- and three-decimal currencies** are recorded correctly (PR A). Old rows are reported by `spree:money:audit_capture_events`, never rewritten.+1. **Capture events in zero- and three-decimal currencies** are recorded correctly from PR A2. Old rows are reported by `spree:money:audit_capture_events`, never rewritten.2. **What opted-in gateways receive** changes for every currency's representation (a `Spree::Money` instead of an integer); the amount charged changes only where it was wrong (JPY captures at Stripe). Un-opted gateways see no change until 6.1.3. **Open carts in zero- and three-decimal currencies** recalculate with exponent rounding (`123.40` JPY → `123`). Accepted.4. **Promotion and manual discount distribution in JPY/KWD** splits in whole yen / thousandths of a dinar on new orders.@@ -170,7 +170,7 @@ None changes a stored value of an existing two-decimal order.**PR A — floats out.** No wire, schema or gateway-interface change.1. Add `currency_exponents.json` and read it in `Spree::Money::Rounding`; add `parse_canonical`, `parse_canonical_decimal`, `format`, `format_decimal`, and a `mode:` parameter on `to_currency`.-2. Fix every **money** row of the Ruby inventory and the hard-coded hundredths. Capture events record `hundredths / 100` in BigDecimal.+2. Fix every **money** row of the Ruby inventory and the hard-coded hundredths. Capture events and dispatch captures keep their units (fixed in A2), without the float.3. Remove the locale-parsing model setters and deprecate `Spree::LocalizedNumber`; the dashboard formats money in the admin's own language (`useMoneyLocale`), with end-to-end tests for English and German admins and for a store whose market writes a comma decimal.4. Add `spree:money:audit_capture_events` (report only).5. Add the "Money" rule to `CLAUDE.md`.@@ -179,9 +179,10 @@ None changes a stored value of an existing two-decimal order.**PR A2 — gateway amounts.** Revertible on its own.1. Register `currency_exponents.json` over the Money gem; `Spree::Gateway.accepts_money_amounts`, the hundredths bridge with its deprecation warning, `Spree::Payment#gateway_amount`.-2. Stripe adapter opts in with `stripe_units` (zero-decimal list, ISK, HUF, TWD rules), used by sessions and by capture/refund; store credit gateway opts in.-3. Patch and release `spree_adyen` and `spree_paypal_checkout` alongside 6.0.-4. Upgrade guide and changelog: the extension API change and the 6.1 removal of the bridge.+2. The capture workflow takes a `Spree::Money` from every caller and records it as is, which fixes yen and dinar capture records.+3. Stripe adapter opts in with `stripe_units` (zero-decimal list, ISK, HUF, TWD rules), used by sessions and by capture/refund; store credit gateway opts in.+4. Patch and release `spree_adyen` and `spree_paypal_checkout` alongside 6.0.+5. Upgrade guide and changelog: the extension API change and the 6.1 removal of the bridge.**PR B — wire contract (breaking).**1. `money_attributes` (exponent and unit-price formats) and `rate_attributes`; convert the non-conforming fields; rename the tax rate fields with model aliases; remove the `*_in_cents` fields; `decimal_places` on currencies.diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rbindex 4a04a51829..46f27ba399 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/payments_controller.rb@@ -53,7 +53,10 @@ module Spree# already-captured or already-void payment returns success.def captureamount = money_param(:amount, @resource.currency)- amount = Spree::Money.new(amount, currency: @resource.currency).amount_in_cents if amount+ unless amount.nil? || amount.positive?+ raise Spree::Money::InvalidFormat.new('must be greater than 0', field: :amount)+ end+ amount = Spree::Money::Rounding.to_hundredths(amount) if amountresult = Spree.payment_capture_workflow.call(payment: @resource, amount: amount)diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rbindex 3c7d611a37..559e85a34f 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb@@ -186,7 +186,7 @@ RSpec.describe Spree::Api::V3::Admin::Orders::PaymentsController, type: :control}, as: :jsonend- [1.15, '1,15', '1.155'].each do |amount|+ [1.15, '1,15', '1.155', '-5.00', '0'].each do |amount|it "refuses #{amount.inspect} with invalid_money_format" doexpect(Spree.payment_capture_workflow).not_to receive(:call)diff --git a/spree/core/app/models/spree/calculator/shipping/flat_percent_item_total.rb b/spree/core/app/models/spree/calculator/shipping/flat_percent_item_total.rbindex a95a9ea2d3..2de28a1c4a 100644--- a/spree/core/app/models/spree/calculator/shipping/flat_percent_item_total.rb+++ b/spree/core/app/models/spree/calculator/shipping/flat_percent_item_total.rb@@ -8,7 +8,7 @@ module Spreeenddef compute_package(package)- compute_from_price(total(package.contents), package.order&.currency)+ compute_from_price(total(package.contents), package.owner&.currency)end# @param price [BigDecimal]diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rbindex 7d3ffe7354..bb5bcef20b 100644--- a/spree/core/app/models/spree/fulfillment.rb+++ b/spree/core/app/models/spree/fulfillment.rb@@ -895,7 +895,7 @@ module Spreedef capture_at_gateway(payment, amount)return 0 if amount <= 0- units = Spree::Money::Rounding.to_minor_units(amount, payment.currency)+ units = ::Money.from_amount(amount, payment.currency).centsresult = Spree.payment_capture_workflow.call(payment: payment, amount: units)raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 875cb598a3..5f6b040e92 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -1274,7 +1274,7 @@ module Spreeenddef credit_card_nil_payment?(attributes)- payments.store_credits.present? && (BigDecimal(attributes[:amount].to_s, exception: false) || 0).zero?+ payments.store_credits.present? && Spree::Money::Rounding.blank_or_zero?(attributes[:amount])endendenddiff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rbindex fadf0c310c..939fbd2c15 100644--- a/spree/core/app/models/spree/price_list.rb+++ b/spree/core/app/models/spree/price_list.rb@@ -389,8 +389,8 @@ module Spreecurrent = current_values[price_id]- amount = attrs[:amount].presence&.to_d- compare_at_amount = attrs[:compare_at_amount].presence&.to_d+ amount = Spree::Money::Rounding.parse_decimal(attrs[:amount])+ compare_at_amount = Spree::Money::Rounding.parse_decimal(attrs[:compare_at_amount])# Clear compare_at_amount if it equals amountcompare_at_amount = nil if compare_at_amount == amountdiff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rbindex 11d585bff0..bbcb9c0e6c 100644--- a/spree/core/app/services/spree/imports/row_processors/product_variant.rb+++ b/spree/core/app/services/spree/imports/row_processors/product_variant.rb@@ -4,9 +4,13 @@ module Spreeclass ProductVariant < BaseOPTION_TYPES_COUNT = 3CATEGORY_FIELDS = %w[category1 category2 category3].freeze+ # Written as plain decimals ("16.50"): the models store text as sent,+ # and "1,599.99" or "16,50" would otherwise be saved as 1 or 16.+ DECIMAL_FIELDS = %w[price compare_at_price cost_price weight height width depth carton_weight].freezedef initialize(row, **)super+ ensure_decimals!@store = row.store@seller = import.seller# Before the product is saved: rows are not wrapped in a transaction,@@ -83,6 +87,15 @@ module Spreeprivate+ def ensure_decimals!+ DECIMAL_FIELDS.each do |column|+ text = attributes[column].to_s.strip+ next if text.empty? || text.match?(Spree::Money::Rounding::CANONICAL_DECIMAL)++ raise ArgumentError, I18n.t('spree.import_invalid_number', column: column, value: text)+ end+ end+# A product-header (options-empty) row creates an option-less default# variant to hold product-level attributes. Once an option-bearing# variant exists, that placeholder is a leftover — remove it anddiff --git a/spree/core/app/services/spree/prices/bulk_upsert.rb b/spree/core/app/services/spree/prices/bulk_upsert.rbindex a40b84d416..d1b101bbcb 100644--- a/spree/core/app/services/spree/prices/bulk_upsert.rb+++ b/spree/core/app/services/spree/prices/bulk_upsert.rb@@ -46,7 +46,7 @@ module Spreerows = Array(rows).map { |r| r.with_indifferent_access }# Amounts are parsed once, here; everything below reads numbers.keyed = rows.select { |r| r[:variant_id].present? && r[:currency].present? }- .map { |r| r.merge(amount: parse_amount(r[:amount]), compare_at_amount: parse_amount(r[:compare_at_amount])) }+ .map { |r| r.merge(amount: Spree::Money::Rounding.parse_decimal(r[:amount]), compare_at_amount: Spree::Money::Rounding.parse_decimal(r[:compare_at_amount])) }# Checked before anything is deduped: `row_key` coerces the quantity,# so two malformed rows would collapse into one and the batch would be# judged on a shape the caller never sent.@@ -371,11 +371,6 @@ module Spree[row[:variant_id].to_s, row[:currency], row[:price_list_id].to_s]end- # Blank values become nil.- def parse_amount(value)- value.presence&.to_d- end-def sweep(affected_keys, clear_rows)cleared_keys = clear_rows.map { |r| row_key(r) }.to_setaffected_set = affected_keys.to_setdiff --git a/spree/core/app/services/spree/stores/provision_defaults.rb b/spree/core/app/services/spree/stores/provision_defaults.rbindex 3bfa4f9fdb..14a0fe2775 100644--- a/spree/core/app/services/spree/stores/provision_defaults.rb+++ b/spree/core/app/services/spree/stores/provision_defaults.rb@@ -260,7 +260,7 @@ module Spreecalculator = delivery_method.calculatornext unless calculator.respond_to?(:preferred_currency)next if calculator.preferred_currency == currency- next unless (BigDecimal(calculator.preferences[:amount].to_s, exception: false) || 0).zero?+ next unless Spree::Money::Rounding.blank_or_zero?(calculator.preferences[:amount])calculator.update!(preferences: calculator.preferences.merge(currency: currency))enddiff --git a/spree/core/app/workflows/spree/payments/capture.rb b/spree/core/app/workflows/spree/payments/capture.rbindex 0a7ee29c8a..acda45f727 100644--- a/spree/core/app/workflows/spree/payments/capture.rb+++ b/spree/core/app/workflows/spree/payments/capture.rb@@ -86,10 +86,7 @@ module Spreeif Spree::Payment.where(id: payment.id, status: 'completed').exists?already_captured = trueelse- # Gateways are called in hundredths of the currency (see- # Spree::Money#amount_in_cents), not in its minor unit — reading- # them as minor units recorded a yen capture a hundred times over.- payment.capture_events.create!(amount: BigDecimal(@amount) / 100)+ payment.capture_events.create!(amount: ::Money.new(@amount, payment.currency).to_d)# Split before completing, so payment.completed publishes with# the captured amount and the order recomputes from correct rows.@remainder = payment.split_uncaptured_amountdiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex f78c3783c4..99f678e11f 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -956,6 +956,7 @@ en:image: Imageimport: Importimport_has_no_failed_rows: This import has no failed rows to retry.+ import_invalid_number: "%{column} must be a number like 16.50, got %{value}."import_mailer:greeting: Hi %{user_name},import_done:diff --git a/spree/core/lib/spree/money.rb b/spree/core/lib/spree/money.rbindex 97b01985de..d499b081bb 100644--- a/spree/core/lib/spree/money.rb+++ b/spree/core/lib/spree/money.rb@@ -116,6 +116,20 @@ module SpreeBigDecimal(value)end+ # Reads a decimal from a caller that may send a number or text: a blank+ # is nil, a number passes, and text must be a plain decimal ("16.50"),+ # never read as a wrong number the way `"1,599.99".to_d` reads 1.+ #+ # @param value [Numeric, String, nil]+ # @return [BigDecimal, Numeric, nil]+ # @raise [Spree::Money::InvalidFormat]+ def parse_decimal(value)+ return if value.blank?+ return value if value.is_a?(Numeric)++ parse_canonical_decimal(value.to_s.strip)+ end+# Writes an amount the way the API and exports carry it: exactly the# currency's decimal places ("10.00", "1.500", "100"). A unit price keeps# up to {UNIT_PRICE_DECIMALS}, with zeros beyond the currency's own@@ -129,16 +143,10 @@ module Spreereturn if amount.nil?places = precision(currency)- unless unit_price- return Kernel.format("%.#{places}f", to_currency(amount, currency))- end-- decimal = quantize(amount, [places, UNIT_PRICE_DECIMALS].max)- text = Kernel.format("%.#{[places, UNIT_PRICE_DECIMALS].max}f", decimal)- whole, fraction = text.split('.')- return whole if fraction.nil?-- fraction = fraction.sub(/0+\z/, '').ljust(places, '0')+ kept = unit_price ? [places, UNIT_PRICE_DECIMALS].max : places+ rounded = quantize(amount, kept)+ whole, fraction = (rounded.zero? ? BigDecimal(0) : rounded).to_s('F').split('.')+ fraction = fraction.to_s.sub(/0+\z/, '').ljust(places, '0')fraction.empty? ? whole : "#{whole}.#{fraction}"end@@ -174,6 +182,27 @@ module Spree(BigDecimal(amount.to_s) * (10**precision(currency))).round.to_iend+ # An amount in hundredths of the currency, whatever its own minor unit:+ # the unit payment gateways are called with until they take amounts with+ # their currency.+ #+ # @param amount [Numeric, String]+ # @return [Integer]+ def to_hundredths(amount)+ quantize(BigDecimal(amount.to_s) * 100, 0).to_i+ end++ # Whether an amount is missing or zero. Text that is not a number is+ # neither, so a malformed value is never mistaken for "nothing to pay".+ #+ # @param value [Numeric, String, nil]+ # @return [Boolean]+ def blank_or_zero?(value)+ return true if value.blank?++ BigDecimal(value.to_s, exception: false)&.zero? || false+ end+# @param units [Integer] whole minor units, as {#to_minor_units} returns# @param currency [String, ::Money::Currency, nil]# @return [BigDecimal]@@ -214,7 +243,7 @@ module Spree## @return [Integer]def amount_in_cents- Rounding.quantize(to_d * 100, 0).to_i+ Rounding.to_hundredths(to_d)enddef absdiff --git a/spree/core/lib/tasks/money.rake b/spree/core/lib/tasks/money.rakeindex da361b5197..a75e0c1017 100644--- a/spree/core/lib/tasks/money.rake+++ b/spree/core/lib/tasks/money.rake@@ -19,7 +19,9 @@ namespace :spree dopayment = event.paymentnext if payment.nil?- exponent = Spree::Money::Rounding.precision(payment.currency)+ # The wrong records were written with the Money gem's exponent, which+ # differs from ISO 4217 for a few currencies (forint, ariary).+ exponent = (::Money::Currency.find(payment.currency) || ::Money::Currency.find('USD')).exponentnext if exponent == 2corrected = event.amount * (10**exponent) / 100diff --git a/spree/core/spec/lib/spree/money_spec.rb b/spree/core/spec/lib/spree/money_spec.rbindex a37f8e34f1..3a38cba12f 100644--- a/spree/core/spec/lib/spree/money_spec.rb+++ b/spree/core/spec/lib/spree/money_spec.rb@@ -279,6 +279,43 @@ describe Spree::Money doit 'passes nil through' doexpect(described_class.format(nil, 'USD')).to be_nilend++ it 'keeps every digit of a large amount' do+ expect(described_class.format(BigDecimal('12345678901234.5678'), 'USD', unit_price: true)).to eq('12345678901234.5678')+ end++ it 'never writes a negative zero' do+ expect(described_class.format(BigDecimal('-0.001'), 'USD')).to eq('0.00')+ end+ end++ describe '.to_hundredths' do+ it 'counts hundredths of any currency exactly' do+ expect(described_class.to_hundredths(BigDecimal('1.15'))).to eq(115)+ expect(described_class.to_hundredths('1500.50')).to eq(150_050)+ end+ end++ describe '.blank_or_zero?' do+ it 'is true for nothing and for zero' do+ expect([nil, '', '0', '0.00', 0].map { |value| described_class.blank_or_zero?(value) }).to all(be(true))+ end++ it 'is false for an amount, and for text that is not a number' do+ expect(['10', '10,00', 'abc'].map { |value| described_class.blank_or_zero?(value) }).to all(be(false))+ end+ end++ describe '.parse_decimal' do+ it 'reads a plain decimal, passes a number and leaves a blank empty' do+ expect(described_class.parse_decimal(' 16.50 ')).to eq(BigDecimal('16.50'))+ expect(described_class.parse_decimal(16.5)).to eq(16.5)+ expect(described_class.parse_decimal('')).to be_nil+ end++ it 'refuses text it would otherwise misread' do+ expect { described_class.parse_decimal('1,599.99') }.to raise_error(Spree::Money::InvalidFormat)+ endenddescribe '.format_decimal' dodiff --git a/spree/core/spec/lib/tasks/money_spec.rb b/spree/core/spec/lib/tasks/money_spec.rbindex f268f9bba2..e901bd0f0f 100644--- a/spree/core/spec/lib/tasks/money_spec.rb+++ b/spree/core/spec/lib/tasks/money_spec.rb@@ -17,13 +17,24 @@ describe 'spree:money:audit_capture_events' dolet(:dollar_payment) { create(:payment, amount: 10) }let!(:yen_event) { yen_payment.capture_events.create!(amount: 100_000) }+ let(:forint_payment) do+ create(:payment, amount: 1000).tap { |payment| payment.order.update_columns(currency: 'HUF') }+ end+ let!(:forint_event) { forint_payment.capture_events.create!(amount: 100_000) }+before { dollar_payment.capture_events.create!(amount: 10) }it 'lists events in currencies without two decimals with both readings, and changes nothing' doexpect { subject.invoke }.to output(- /#{yen_event.prefixed_id}\t#{yen_payment.number}\tJPY\trecorded=100000\tif_from_capture=1000\tpayment_amount=1000\n.*1 capture event/m+ /#{yen_event.prefixed_id}\t#{yen_payment.number}\tJPY\trecorded=100000\tif_from_capture=1000\tpayment_amount=1000\n.*2 capture event/m).to_stdoutexpect(yen_event.reload.amount).to eq(100_000)end++ # The wrong records were written with the Money gem's exponent, which gives+ # the forint no decimals although ISO 4217 gives it two.+ it 'lists forint events, which ISO 4217 writes with two decimals' do+ expect { subject.invoke }.to output(/#{forint_event.prefixed_id}\t.*HUF\trecorded=100000\.00\tif_from_capture=1000\.00/).to_stdout+ endenddiff --git a/spree/core/spec/models/spree/calculator/shipping/flat_percent_item_total_spec.rb b/spree/core/spec/models/spree/calculator/shipping/flat_percent_item_total_spec.rbindex dc6537465b..4e4a4fd0c5 100644--- a/spree/core/spec/models/spree/calculator/shipping/flat_percent_item_total_spec.rb+++ b/spree/core/spec/models/spree/calculator/shipping/flat_percent_item_total_spec.rb@@ -22,6 +22,13 @@ module Spreeit 'rounds result correctly' doexpect(subject.compute(package)).to eq(4.04)end++ # A cart's package has no order; the currency comes from its owner.+ it "rounds to the owner's currency" do+ allow(package).to receive(:owner).and_return(build(:cart, currency: 'JPY'))++ expect(subject.compute(package)).to eq(BigDecimal('4'))+ endendendenddiff --git a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rbindex 013e395ff9..98cc6f6b76 100644--- a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb+++ b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb@@ -50,6 +50,15 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do# fallback they would answer the store's own unit either way, so an import# that dropped them looked correct everywhere except the editor, which# shows the raw column so a save cannot stamp one store's unit on a row.+ context 'with a number written with a thousands separator' do+ let(:row_data) { csv_row_hash('slug' => 'grouped-kettle', 'name' => 'Grouped Kettle', 'price' => '1,599.99') }++ it 'fails the row naming the column instead of saving 1' do+ expect { described_class.new(row) }.to raise_error(ArgumentError, 'price must be a number like 16.50, got 1,599.99.')+ expect(Spree::Product.find_by(slug: 'grouped-kettle')).to be_nil+ end+ end+it 'stores the units the file declared alongside the measurements' dodefault_variant = product.default_variantdiff --git a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rbindex cf58f11934..a317a11a89 100644--- a/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb+++ b/spree/core/spec/services/spree/prices/bulk_upsert_spec.rb@@ -129,6 +129,13 @@ RSpec.describe Spree::Prices::BulkUpsert doexpect(base.amount).to eq(BigDecimal('7.77'))end+ it 'refuses an amount it would otherwise misread' do+ expect {+ described_class.call(rows: [{ variant_id: variant.id, currency: 'USD', amount: '1,599.99' }])+ }.to raise_error(Spree::Money::InvalidFormat)+ expect(variant.prices.find_by(currency: 'USD', price_list_id: nil)&.amount).not_to eq(BigDecimal('1'))+ end+it 'drops rows missing variant_id or currency' doresult = described_class.call(rows: [{ amount: '9.99' }])diff --git a/spree/core/spec/workflows/spree/payments/capture_spec.rb b/spree/core/spec/workflows/spree/payments/capture_spec.rbindex bbd3fddba3..12735fd4a7 100644--- a/spree/core/spec/workflows/spree/payments/capture_spec.rb+++ b/spree/core/spec/workflows/spree/payments/capture_spec.rb@@ -61,19 +61,6 @@ RSpec.describe Spree::Payments::Capture doexpect(payment.reload.captured_amount).to eq(BigDecimal(amount))endend-- it 'records a yen capture in yen, not a hundred times over' do- payment.update_columns(amount: BigDecimal('1000'))- order.update_columns(currency: 'JPY', total: BigDecimal('1000'))- expect(gateway).to receive(:capture).with(100_000, '123', anything).and_return(success_response)-- result = described_class.call(payment: payment)-- expect(result).to be_success, result.error.to_s-- expect(payment.reload.captured_amount).to eq(BigDecimal('1000'))- expect(payment.amount).to eq(BigDecimal('1000'))- endendit 'is a no-op for an already-captured payment' dodiff --git a/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb b/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rbindex 7b938ff94f..b0cdfd5190 100644--- a/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb+++ b/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb@@ -440,11 +440,13 @@ module SpreeMeilisearchendend- # The bound as a plain decimal, or nil for anything that is not a finite- # number, so a malformed price never reaches the filter expression.+ # The bound as a plain decimal, or nil for anything else, so a malformed+ # or enormous price never reaches the filter expression.def price_filter_value(value)- bound = BigDecimal(value.to_s, exception: false)- Spree::Money::Rounding.format_decimal(bound) if bound&.finite?+ text = value.to_s.strip+ return unless text.length <= 32 && text.match?(Spree::Money::Rounding::CANONICAL_DECIMAL)++ Spree::Money::Rounding.format_decimal(text)enddef format_custom_field_filter_value(value, numeric)diff --git a/spree/providers/meilisearch/spec/models/spree_meilisearch/search_provider_spec.rb b/spree/providers/meilisearch/spec/models/spree_meilisearch/search_provider_spec.rbindex 9cf42309ec..939c4d0fd9 100644--- a/spree/providers/meilisearch/spec/models/spree_meilisearch/search_provider_spec.rb+++ b/spree/providers/meilisearch/spec/models/spree_meilisearch/search_provider_spec.rb@@ -107,7 +107,7 @@ RSpec.describe SpreeMeilisearch::SearchProvider doms_responseend- provider.search_and_filter(scope: store.products, filters: { 'price_gte' => 'Infinity', 'price_lte' => '19.99' })+ provider.search_and_filter(scope: store.products, filters: { 'price_gte' => '1e1000000000000000000', 'price_lte' => '19.99' })endend