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
Removed float arithmetic from money paths
Damian Legawiecc4261730f205
diff --git a/CLAUDE.md b/CLAUDE.mdindex 4f5eaa112a..8a7624d9a0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -502,6 +502,16 @@ Spree::Dependencies.cart_add_item_service = 'Spree::Cart::AddItem'- Before removing a translation key `i18n-tasks unused` reports, check it is not passed around as a string or built from a value (`"spree.#{name}"`) — the checker cannot see either- Keep translations in `config/locales/en.yml` — no duplication across files+### Money++Money is never a float — not in Ruby, not in TypeScript (see `docs/plans/6.0-money-correctness.md`).++- No `.to_f`, `Float()` or float literal (`100.0`) on an amount, price, total, cost, fee, discount, tax or payout. Compute in `BigDecimal`; in the dashboard never `parseFloat`/`Number()` a money string.+- Round with `Spree::Money::Rounding.to_currency(amount, currency)` (the currency's ISO 4217 exponent from `spree/core/config/currency_exponents.json`), never `.round(2)`; split in minor units with `to_minor_units` / `from_minor_units`, never `* 100` / `/ 100`. Round only when persisting, calling a gateway, or serializing — not in intermediate math.+- Read an amount from an API request with `Spree::Money::Rounding.parse_canonical(value, currency)`: canonical decimal strings only (`"1234.56"`), no locale parsing on the server. `Spree::LocalizedNumber` is deprecated; never add a model setter that re-parses numbers.+- Write amounts out with `Spree::Money::Rounding.format(amount, currency)`.+- A third party that needs a JSON number gets `.to_f` once, on the line that hands it over, with a comment saying why.+### Time zones- Parsing or formatting a date **for a store** uses that store's zone, neverdiff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdxindex de9dc244c5..56fbdd7342 100644--- a/docs/developer/upgrades/5.6-to-6.0.mdx+++ b/docs/developer/upgrades/5.6-to-6.0.mdx@@ -818,6 +818,24 @@ Other changes that come with it:- **Alba moved into `spree_core`**, with its configuration, so core's staff emails render in installations without `spree_api`.- **Your own mailers keep working.** A mailer that inherits `Spree::BaseMailer` and calls `mail` with its own ERB views is wrapped in the new email layout, and the `spree/shared/mailer_hero` and `mailer_button` partials remain for its views. See [Your own mailers](/developer/customization/emails#your-own-mailers).+## Money++- **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:++<CodeGroup>++```bash Spree CLI (Docker)+spree rake spree:money:audit_capture_events+```++```bash Without Spree CLI+bundle exec rake spree:money:audit_capture_events+```++</CodeGroup>+## Translations ship with SpreeSpree's translations for emails, API messages and validation messages are now part of Spree itself, in 43 languages besides English. Regional English (`en-GB` and the like) now falls back to `en`. A key a language does not translate yet falls back to English, unless your app configured its own `config.i18n.fallbacks`. See [Translations](/developer/core-concepts/translations#translating-the-interface).@@ -877,6 +895,7 @@ Before 6.0 a cart was an incomplete order, so extensions written for 5.x (paymen| `.with_metafield_key`, `.with_metafield_key_value` | `.with_custom_field_key`, `.with_custom_field_key_value` || `Spree.metafields` | `Spree.custom_fields` || `Spree.t`, `Spree.translate` | `I18n.t` with the full key, e.g. `I18n.t('spree.free')` |+| `Spree::LocalizedNumber.parse` | `BigDecimal(value)` on a canonical decimal string; Spree no longer parses numbers by locale || `CustomFieldDefinition#name`, `#metafield_type`, `#display_on` | `#label`, `#field_type`, `#storefront_visible` (columns renamed) || `Spree::SearchProvider::Meilisearch` | `SpreeMeilisearch::SearchProvider` (moved to the `spree_meilisearch` gem) || `Spree::SearchProvider::ProductPresenter` | `SpreeMeilisearch::ProductPresenter` (moved to the `spree_meilisearch` gem) |diff --git a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rbindex a7aa5dc093..d956a9b54c 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb@@ -48,6 +48,7 @@ module Spreeinsufficient_stock: 'insufficient_stock',invalid_quantity: 'invalid_quantity',invalid_price: 'invalid_price',+ invalid_money_format: 'invalid_money_format',price_override_not_allowed: 'price_override_not_allowed',# Validation errorsdiff --git a/spree/api/app/controllers/concerns/spree/api/v3/money_params.rb b/spree/api/app/controllers/concerns/spree/api/v3/money_params.rbnew file mode 100644index 0000000000..2aecb3887c--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/money_params.rb@@ -0,0 +1,40 @@+module Spree+ module Api+ module V3+ # Money read from a request. The contract is a canonical decimal string+ # ("19.99"); a JSON number, a localized string or more decimals than the+ # currency has is answered with `invalid_money_format`, naming the field.+ module MoneyParams+ extend ActiveSupport::Concern++ included do+ rescue_from Spree::Money::InvalidFormat, with: :render_invalid_money_format+ end++ protected++ # @param name [Symbol] the request parameter+ # @param currency [String] the currency the amount is in+ # @param unit_price [Boolean] allows up to four decimals+ # @return [BigDecimal, nil] nil when the parameter is absent+ # @raise [Spree::Money::InvalidFormat]+ def money_param(name, currency, unit_price: false)+ Spree::Money::Rounding.parse_canonical(params[name], currency, unit_price: unit_price)+ rescue Spree::Money::InvalidFormat => error+ raise Spree::Money::InvalidFormat.new(error.message, field: name)+ end++ private++ def render_invalid_money_format(error)+ render_error(+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:invalid_money_format],+ message: [error.field, error.message].compact.join(' '),+ status: :unprocessable_content,+ details: error.field ? { error.field => [error.message] } : nil+ )+ end+ end+ end+ end+enddiff --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 40d7432bbf..4a04a51829 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@@ -52,7 +52,8 @@ module Spree# to prevent. Both flows are idempotent on replay — an# already-captured or already-void payment returns success.def capture- amount = params[:amount] ? (params[:amount].to_f * 100).round : nil+ amount = money_param(:amount, @resource.currency)+ amount = Spree::Money.new(amount, currency: @resource.currency).amount_in_cents if amountresult = Spree.payment_capture_workflow.call(payment: @resource, amount: amount)diff --git a/spree/api/app/controllers/spree/api/v3/base_controller.rb b/spree/api/app/controllers/spree/api/v3/base_controller.rbindex 430ded9ca8..6d09952e92 100644--- a/spree/api/app/controllers/spree/api/v3/base_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/base_controller.rb@@ -12,6 +12,7 @@ module Spreeinclude Spree::Api::V3::JwtAuthenticationinclude Spree::Api::V3::ApiKeyAuthenticationinclude Spree::Api::V3::ErrorHandler+ include Spree::Api::V3::MoneyParamsinclude Spree::Api::V3::SecurityHeadersinclude Spree::Api::V3::ResourceSerializerinclude Spree::Api::V3::RateLimitHeadersdiff --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 84df106d9f..3c7d611a37 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@@ -175,6 +175,34 @@ RSpec.describe Spree::Api::V3::Admin::Orders::PaymentsController, type: :controlexpect(payment.reload.status).to eq('completed')end+ context 'with a partial amount' do+ it 'hands the gateway exact hundredths' do+ expect(Spree.payment_capture_workflow).to receive(:call).with(payment: payment, amount: 115).and_call_original++ patch :capture, params: {+ order_id: order_with_payment.prefixed_id,+ id: payment.prefixed_id,+ amount: '1.15'+ }, as: :json+ end++ [1.15, '1,15', '1.155'].each do |amount|+ it "refuses #{amount.inspect} with invalid_money_format" do+ expect(Spree.payment_capture_workflow).not_to receive(:call)++ patch :capture, params: {+ order_id: order_with_payment.prefixed_id,+ id: payment.prefixed_id,+ amount: amount+ }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('invalid_money_format')+ expect(json_response['error']['details']).to have_key('amount')+ end+ end+ end+context 'when payment is already completed' dobefore { payment.update_column(:status, 'completed') }diff --git a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb b/spree/core/app/models/concerns/spree/purchase/payment_processing.rbindex 23bb0fc060..d2d098ca84 100644--- a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb+++ b/spree/core/app/models/concerns/spree/purchase/payment_processing.rb@@ -46,7 +46,7 @@ module Spree## @return [Boolean]def payment_required?- total.to_f > 0.0+ total.to_d.positive?end# Whether a confirm/review pass is expected before completion —diff --git a/spree/core/app/models/concerns/spree/vat_price_calculation.rb b/spree/core/app/models/concerns/spree/vat_price_calculation.rbindex 7431ca0802..ece2224b3f 100644--- a/spree/core/app/models/concerns/spree/vat_price_calculation.rb+++ b/spree/core/app/models/concerns/spree/vat_price_calculation.rb@@ -1,6 +1,9 @@module Spree# Restates a VAT-inclusive price for a customer in another country: the# home-country VAT comes out, the destination's goes on.+ #+ # The including class answers +currency+, which the restated amount is+ # rounded to.module VatPriceCalculation# Cheapest test first: a domestic sale needs no restatement whatever the# provider is, so the provider lookup (a constantize and an instantiation) is@@ -11,7 +14,7 @@ module Spreereturn amount if amount.nil? || !outside_default_vat_zone?(price_options)return amount unless restatement_available?(price_options)- round_to_two_places(add_foreign_vat_for(amount, price_options))+ Spree::Money::Rounding.to_currency(add_foreign_vat_for(amount, price_options), currency)endprivate@@ -66,7 +69,7 @@ module Spreelookup[:country] = country_from(price_options)end- Spree::TaxRate.included_tax_amount_for(lookup).to_f+ Spree::TaxRate.included_tax_amount_for(lookup).to_dend# +current_price_options+ is documented as an override point, so an app may@@ -92,9 +95,5 @@ module Spree@default_tax_country = Spree::Current.store&.default_countryend-- def round_to_two_places(amount)- Spree::Money::Rounding.quantize(amount, 2)- endendenddiff --git a/spree/core/app/models/spree/adjusters/largest_remainder.rb b/spree/core/app/models/spree/adjusters/largest_remainder.rbindex 84d6cf777d..14195b7b23 100644--- a/spree/core/app/models/spree/adjusters/largest_remainder.rb+++ b/spree/core/app/models/spree/adjusters/largest_remainder.rb@@ -1,6 +1,7 @@module Spreemodule Adjusters- # Largest-remainder apportionment of an integer cent total across weights.+ # Largest-remainder apportionment of an integer total, in the currency's+ # minor units, across weights.# Shared by promotion order-level distribution and manual admin discounts# so both split identically (sum of shares always equals the total).module LargestRemainderdiff --git a/spree/core/app/models/spree/adjusters/promotion.rb b/spree/core/app/models/spree/adjusters/promotion.rbindex 8f9089f147..0fedc3810f 100644--- a/spree/core/app/models/spree/adjusters/promotion.rb+++ b/spree/core/app/models/spree/adjusters/promotion.rb@@ -140,7 +140,7 @@ module Spreeendend- # Largest-remainder distribution (in cents) of the order-wide winner over+ # Largest-remainder distribution (in minor units) of the order-wide winner over# each line's remaining discounted base, so shares always sum exactly to# the promotion amount and no line goes below zero.def distribute_over_line_items(chosen)@@ -149,11 +149,12 @@ module Spreebases_sum = bases.sumreturn if bases_sum <= 0- total_cents = [chosen[:amount].abs, bases_sum].min * 100- shares = Spree::Adjusters::LargestRemainder.largest_remainder_shares(total_cents.round, bases)+ currency = order.currency+ total_units = Spree::Money::Rounding.to_minor_units([chosen[:amount].abs, bases_sum].min, currency)+ shares = Spree::Adjusters::LargestRemainder.largest_remainder_shares(total_units, bases)line_items.each_with_index do |line_item, index|- amount = -BigDecimal(shares[index]) / 100+ amount = -Spree::Money::Rounding.from_minor_units(shares[index], currency)next if amount.zero?persist_discount(line_item, chosen, amount)diff --git a/spree/core/app/models/spree/calculator/flat_percent_item_total.rb b/spree/core/app/models/spree/calculator/flat_percent_item_total.rbindex 12025d4985..356fe309f7 100644--- a/spree/core/app/models/spree/calculator/flat_percent_item_total.rb+++ b/spree/core/app/models/spree/calculator/flat_percent_item_total.rb@@ -7,7 +7,7 @@ module Spreeenddef compute(object)- computed_amount = (object.amount * preferred_flat_percent / 100).round(2)+ computed_amount = Spree::Money::Rounding.to_currency(object.amount * preferred_flat_percent / 100, object.try(:currency))# We don't want to cause the promotion adjustments to push the order into a negative total.if computed_amount > object.amountdiff --git a/spree/core/app/models/spree/calculator/percent_on_line_item.rb b/spree/core/app/models/spree/calculator/percent_on_line_item.rbindex e25b1fe0e8..d8b643ee49 100644--- a/spree/core/app/models/spree/calculator/percent_on_line_item.rb+++ b/spree/core/app/models/spree/calculator/percent_on_line_item.rb@@ -11,7 +11,7 @@ module Spreedef compute(object)return 0 if preferred_apply_only_on_full_priced_items && object.variant.compare_at_amount_in(object.currency).present?- computed_amount = (object.amount * preferred_percent / 100).round(2)+ computed_amount = Spree::Money::Rounding.to_currency(object.amount * preferred_percent / 100, object.currency)# We don't want to cause the promotion adjustments to push the order into a negative total.if computed_amount > object.amountdiff --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 f1e5451005..a95a9ea2d3 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,12 +8,14 @@ module Spreeenddef compute_package(package)- compute_from_price(total(package.contents))+ compute_from_price(total(package.contents), package.order&.currency)end- def compute_from_price(price)- value = price * BigDecimal(preferred_flat_percent.to_s) / 100.0- (value * 100).round.to_f / 100+ # @param price [BigDecimal]+ # @param currency [String, nil] the amount is rounded to its minor unit+ # @return [BigDecimal]+ def compute_from_price(price, currency = nil)+ Spree::Money::Rounding.to_currency(price * BigDecimal(preferred_flat_percent.to_s) / 100, currency)endendenddiff --git a/spree/core/app/models/spree/calculator/tiered_percent.rb b/spree/core/app/models/spree/calculator/tiered_percent.rbindex e8a5dc09d5..e2bce2c228 100644--- a/spree/core/app/models/spree/calculator/tiered_percent.rb+++ b/spree/core/app/models/spree/calculator/tiered_percent.rb@@ -15,7 +15,7 @@ module Spreedef compute(object)percent = tier_value_for(object.amount) || preferred_base_percent- (object.amount * percent / 100).round(2)+ Spree::Money::Rounding.to_currency(object.amount * percent / 100, object.try(:currency))endprivatediff --git a/spree/core/app/models/spree/delivery_rate.rb b/spree/core/app/models/spree/delivery_rate.rbindex e28d688805..fcab2a7490 100644--- a/spree/core/app/models/spree/delivery_rate.rb+++ b/spree/core/app/models/spree/delivery_rate.rb@@ -80,9 +80,9 @@ module Spree@tax_amount ||= if tax_rate.nil?BigDecimal(0)elsif tax_rate.included_in_price?- (cost / (1 + tax_rate.amount) * tax_rate.amount).round(2)+ Spree::Money::Rounding.to_currency(cost / (1 + tax_rate.amount) * tax_rate.amount, currency)else- (cost * tax_rate.amount).round(2)+ Spree::Money::Rounding.to_currency(cost * tax_rate.amount, currency)endenddiff --git a/spree/core/app/models/spree/gateway.rb b/spree/core/app/models/spree/gateway.rbindex d49227521a..ddcd705b89 100644--- a/spree/core/app/models/spree/gateway.rb+++ b/spree/core/app/models/spree/gateway.rb@@ -1,6 +1,6 @@module Spreeclass Gateway < PaymentMethod- FROM_DOLLAR_TO_CENT_RATE = 100.0+ FROM_DOLLAR_TO_CENT_RATE = 100delegate :authorize, :purchase, :capture, :void, :credit, to: :providerdiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 2d8783ec8e..875cb598a3 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -415,9 +415,9 @@ module Spree# Returns the subtotal used for analytics integrations# It's a sum of the item total and the promo total- # @return [Float]+ # @return [BigDecimal]def analytics_subtotal- (item_total + line_items.sum(:discount_total)).to_f+ item_total + line_items.sum(:discount_total)end@@ -1274,7 +1274,7 @@ module Spreeenddef credit_card_nil_payment?(attributes)- payments.store_credits.present? && attributes[:amount].to_f.zero?+ payments.store_credits.present? && (BigDecimal(attributes[:amount].to_s, exception: false) || 0).zero?endendenddiff --git a/spree/core/app/models/spree/payment/gateway_options.rb b/spree/core/app/models/spree/payment/gateway_options.rbindex 38fba84c49..f5758368db 100644--- a/spree/core/app/models/spree/payment/gateway_options.rb+++ b/spree/core/app/models/spree/payment/gateway_options.rb@@ -67,7 +67,7 @@ module Spreeprivatedef exchange_multiplier- payment.payment_method.try(:exchange_multiplier) || 1.0+ payment.payment_method.try(:exchange_multiplier) || 1endendenddiff --git a/spree/core/app/models/spree/payment_method/store_credit.rb b/spree/core/app/models/spree/payment_method/store_credit.rbindex 1945a4aee1..f0034e3025 100644--- a/spree/core/app/models/spree/payment_method/store_credit.rb+++ b/spree/core/app/models/spree/payment_method/store_credit.rb@@ -26,7 +26,7 @@ module Spreeelseaction = lambda do |store_credit|store_credit.authorize(- amount_in_cents / 100.0.to_d,+ BigDecimal(amount_in_cents) / 100,gateway_options[:currency],action_originator: gateway_options[:originator])@@ -38,7 +38,7 @@ module Spreedef capture(amount_in_cents, auth_code, gateway_options = {})action = lambda do |store_credit|store_credit.capture(- amount_in_cents / 100.0.to_d,+ BigDecimal(amount_in_cents) / 100,auth_code,gateway_options[:currency],action_originator: gateway_options[:originator]@@ -49,7 +49,7 @@ module Spreedef purchase(amount_in_cents, store_credit, gateway_options = {})eligible_events = store_credit.store_credit_events.where(- amount: amount_in_cents / 100.0.to_d,+ amount: BigDecimal(amount_in_cents) / 100,action: Spree::StoreCredit::ELIGIBLE_ACTION)event = eligible_events.detect do |eligible_event|@@ -76,7 +76,7 @@ module Spreecurrency = gateway_options[:currency] || store_credit.currencyoriginator = gateway_options[:originator]- store_credit.credit(amount_in_cents / 100.0.to_d, auth_code, currency, action_originator: originator)+ store_credit.credit(BigDecimal(amount_in_cents) / 100, auth_code, currency, action_originator: originator)endhandle_action(action, :credit, auth_code)diff --git a/spree/core/app/models/spree/refund.rb b/spree/core/app/models/spree/refund.rbindex 1d215a7026..9c72e57edc 100644--- a/spree/core/app/models/spree/refund.rb+++ b/spree/core/app/models/spree/refund.rb@@ -56,10 +56,6 @@ module Spree# back through a payment that may belong to several orders.before_validation :assign_order_from_payment, on: :create- def amount=(amount)- self[:amount] = Spree::LocalizedNumber.parse(amount)- end-def moneySpree::Money.new(amount, currency: currency)end@@ -121,7 +117,7 @@ module Spreedef perform!return true if transaction_id.present?- credit_cents = Spree::Money.new(amount.to_f, currency: currency).amount_in_cents+ credit_cents = Spree::Money.new(amount, currency: currency).amount_in_cents@response = process!(credit_cents)diff --git a/spree/core/app/models/spree/stock/estimator.rb b/spree/core/app/models/spree/stock/estimator.rbindex 0204d82750..5fc3013d56 100644--- a/spree/core/app/models/spree/stock/estimator.rb+++ b/spree/core/app/models/spree/stock/estimator.rb@@ -121,7 +121,7 @@ module Spreepercent = service_row&.markup_percent || delivery_method.markup_percent || 0flat = service_row&.markup_flat || delivery_method.markup_flat || 0- (cost * (1 + (percent / 100)) + flat).round(2)+ Spree::Money::Rounding.to_currency(cost * (1 + (percent / 100)) + flat, currency)end# Display name for provider-priced rates: the merchant's label override,diff --git a/spree/core/app/models/spree/tax_provider/internal.rb b/spree/core/app/models/spree/tax_provider/internal.rbindex 064049d5d1..7f30e35da5 100644--- a/spree/core/app/models/spree/tax_provider/internal.rb+++ b/spree/core/app/models/spree/tax_provider/internal.rb@@ -136,7 +136,7 @@ module Spreewrite_tax_line(owner, item, rate, 0, 'customer_exempt', jurisdiction,data: exemption_data(exemption, exemption_subject))else- write_tax_line(owner, item, rate, compute_tax(rate, item, relevant_rates),+ write_tax_line(owner, item, rate, compute_tax(rate, item, relevant_rates, owner.currency),reason_for(rate), jurisdiction)endend@@ -169,16 +169,19 @@ module Spreeitem.respond_to?(:taxable_basis) ? item.taxable_basis : item.amountend- def compute_tax(rate, item, relevant_rates)+ # Rounded per line, half up, to the order's currency — the internal+ # provider's choice; other providers round as their jurisdictions require.+ def compute_tax(rate, item, relevant_rates, currency)basis = taxable_basis(item)- if rate.included_in_price- included_sum = relevant_rates.select(&:included_in_price).sum(&:amount)- included_sum = rate.amount if included_sum.zero?- (basis / (1 + included_sum) * rate.amount).round(2)- else- (basis * rate.amount).round(2)- end+ tax = if rate.included_in_price+ included_sum = relevant_rates.select(&:included_in_price).sum(&:amount)+ included_sum = rate.amount if included_sum.zero?+ basis / (1 + included_sum) * rate.amount+ else+ basis * rate.amount+ end+ Spree::Money::Rounding.to_currency(tax, currency)end# Pre-tax amounts are stored so refund and reporting code can weighdiff --git a/spree/core/app/models/spree/tax_rate.rb b/spree/core/app/models/spree/tax_rate.rbindex b8b36716fa..a8154e50d1 100644--- a/spree/core/app/models/spree/tax_rate.rb+++ b/spree/core/app/models/spree/tax_rate.rb@@ -66,7 +66,7 @@ module Spreeenddef amount_percentage=(value)- self.amount = value.present? ? (value.to_f / 100) : nil+ self.amount = value.present? ? BigDecimal(value.to_s) / 100 : nilend# The included-in-price rate to back out of a gross price.diff --git a/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb b/spree/core/app/presenters/spree/csv/order_line_item_presenter.rbindex 2f43f6e196..2efb33ae33 100644--- a/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb+++ b/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb@@ -96,16 +96,16 @@ module Spreeindex.zero? ? order.email : nil,index.zero? ? order.status : nil,index.zero? ? order.currency : nil,- index.zero? ? order.item_total.to_f : nil,- index.zero? ? order.delivery_total.to_f : nil,- index.zero? ? order.tax_total.to_f : nil,+ index.zero? ? money(order.item_total) : nil,+ index.zero? ? money(order.delivery_total) : nil,+ index.zero? ? money(order.tax_total) : nil,index.zero? ? order.included_tax_total.positive? : nil,index.zero? ? (order.discount_total.negative? || line_item.discount_total.negative?) : nil,index.zero? ? order.has_free_shipping? : nil,- index.zero? ? order.discount_total.abs : nil,+ index.zero? ? money(order.discount_total.abs) : nil,index.zero? ? order.promo_code : nil,- index.zero? ? order.payments.store_credits.sum(:amount).abs : nil,- index.zero? ? order.total.to_f : nil,+ index.zero? ? money(order.payments.store_credits.sum(:amount).abs) : nil,+ index.zero? ? money(order.total) : nil,index.zero? ? order.delivery_method&.name : nil,index.zero? ? order.total_weight.to_f : nil,index.zero? ? order.payments.valid&.first&.display_source_name : nil,@@ -160,6 +160,10 @@ module Spreeprivate+ def money(amount)+ Spree::Money::Rounding.format(amount, order.currency)+ end+# Drops the cells whose headers were omitted, matching each value to its# header by position so the row and the header list stay aligned.def reject_omitted(csv)diff --git a/spree/core/app/presenters/spree/csv/price_list_price_presenter.rb b/spree/core/app/presenters/spree/csv/price_list_price_presenter.rbindex 58f6b68fd2..bc8825ab2c 100644--- a/spree/core/app/presenters/spree/csv/price_list_price_presenter.rb+++ b/spree/core/app/presenters/spree/csv/price_list_price_presenter.rb@@ -32,9 +32,7 @@ module Spree# store's locale, not the exporting admin's, and a comma written here# would re-import as a hundred times the price.def amount_string(amount)- return nil if amount.nil?-- format("%.#{Spree::Money::Rounding.precision(price.currency)}f", amount)+ Spree::Money::Rounding.format(amount, price.currency, unit_price: true)endendenddiff --git a/spree/core/app/presenters/spree/csv/product_variant_presenter.rb b/spree/core/app/presenters/spree/csv/product_variant_presenter.rbindex fdb839c739..3586a97f9e 100644--- a/spree/core/app/presenters/spree/csv/product_variant_presenter.rb+++ b/spree/core/app/presenters/spree/csv/product_variant_presenter.rb@@ -98,8 +98,8 @@ module Spreeindex.zero? ? product.meta_keywords : nil,index.zero? ? product.tag_list.to_s : nil,index.zero? ? product.label_list.to_s : nil,- variant.amount_in(currency).to_f,- variant.compare_at_amount_in(currency).to_f,+ unit_price(variant.amount_in(currency) || 0),+ unit_price(variant.compare_at_amount_in(currency) || 0),currency,variant.width,variant.height,@@ -151,6 +151,10 @@ module Spreeprivate+ def unit_price(amount)+ Spree::Money::Rounding.format(amount, currency, unit_price: true)+ end+# Default-channel publication for the export's store. 5.5 transitional:# fall back to the legacy Product columns when the publication dates are# NULL (pre-backfill). 6.0 drops the Product-column fallback.@@ -175,8 +179,8 @@ module Spreecsv = Array.new(CSV_HEADERS.size)csv[CSV_HEADERS.index('sku')] = variant.skucsv[CSV_HEADERS.index('slug')] = product.slug- csv[CSV_HEADERS.index('price')] = variant.amount_in(currency)&.to_f- csv[CSV_HEADERS.index('compare_at_price')] = variant.compare_at_amount_in(currency)&.to_f+ csv[CSV_HEADERS.index('price')] = unit_price(variant.amount_in(currency))+ csv[CSV_HEADERS.index('compare_at_price')] = unit_price(variant.compare_at_amount_in(currency))csv[CSV_HEADERS.index('currency')] = currencycsvenddiff --git a/spree/core/app/presenters/spree/csv/purchase_order_item_presenter.rb b/spree/core/app/presenters/spree/csv/purchase_order_item_presenter.rbindex d017dd6bcf..342e6a6546 100644--- a/spree/core/app/presenters/spree/csv/purchase_order_item_presenter.rb+++ b/spree/core/app/presenters/spree/csv/purchase_order_item_presenter.rb@@ -41,9 +41,7 @@ module Spreeprivatedef amount_string(amount, currency)- return nil if amount.nil?-- format("%.#{Spree::Money::Rounding.precision(currency)}f", amount)+ Spree::Money::Rounding.format(amount, currency, unit_price: true)endendenddiff --git a/spree/core/app/services/spree/orders/discounts/create.rb b/spree/core/app/services/spree/orders/discounts/create.rbindex fbc44818a9..90fd2aac90 100644--- a/spree/core/app/services/spree/orders/discounts/create.rb+++ b/spree/core/app/services/spree/orders/discounts/create.rb@@ -39,7 +39,7 @@ module Spreedef line_item_row(order, line_item, label, value, value_type)base = discountable_base(line_item)- amount = -[amount_for(base, value, value_type), base].min+ amount = -[amount_for(base, value, value_type, order.currency), base].minreturn if amount.zero?create_row(order, line_item, label, amount, value, value_type)@@ -51,19 +51,20 @@ module Spreebases_sum = bases.sumreturn [] if bases_sum <= 0- total = [amount_for(bases_sum, value, value_type), bases_sum].min- shares = Spree::Adjusters::LargestRemainder.largest_remainder_shares((total * 100).round, bases)+ total = [amount_for(bases_sum, value, value_type, order.currency), bases_sum].min+ total_units = Spree::Money::Rounding.to_minor_units(total, order.currency)+ shares = Spree::Adjusters::LargestRemainder.largest_remainder_shares(total_units, bases)line_items.each_with_index.filter_map do |line_item, index|- amount = -BigDecimal(shares[index]) / 100+ amount = -Spree::Money::Rounding.from_minor_units(shares[index], order.currency)next if amount.zero?create_row(order, line_item, label, amount, value, value_type)endend- def amount_for(base, value, value_type)- value_type == 'percent' ? (base * value / 100).round(2) : value+ def amount_for(base, value, value_type, currency)+ value_type == 'percent' ? Spree::Money::Rounding.to_currency(base * value / 100, currency) : valueend# Remaining discountable base: amount net of already-applied discounts.diff --git a/spree/core/app/services/spree/stores/provision_defaults.rb b/spree/core/app/services/spree/stores/provision_defaults.rbindex 774a200377..3bfa4f9fdb 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 calculator.preferences[:amount].to_f.zero?+ next unless (BigDecimal(calculator.preferences[:amount].to_s, exception: false) || 0).zero?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 8f0622c0ec..0a7ee29c8a 100644--- a/spree/core/app/workflows/spree/payments/capture.rb+++ b/spree/core/app/workflows/spree/payments/capture.rb@@ -86,7 +86,10 @@ module Spreeif Spree::Payment.where(id: payment.id, status: 'completed').exists?already_captured = trueelse- payment.capture_events.create!(amount: ::Money.new(@amount, payment.currency).to_f)+ # 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)# 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/currency_exponents.json b/spree/core/config/currency_exponents.jsonnew file mode 100644index 0000000000..763a120c06--- /dev/null+++ b/spree/core/config/currency_exponents.json@@ -0,0 +1,180 @@+{+ "AED": 2,+ "AFN": 2,+ "ALL": 2,+ "AMD": 2,+ "ANG": 2,+ "AOA": 2,+ "ARS": 2,+ "AUD": 2,+ "AWG": 2,+ "AZN": 2,+ "BAM": 2,+ "BBD": 2,+ "BDT": 2,+ "BGN": 2,+ "BHD": 3,+ "BIF": 0,+ "BMD": 2,+ "BND": 2,+ "BOB": 2,+ "BRL": 2,+ "BSD": 2,+ "BTN": 2,+ "BWP": 2,+ "BYN": 2,+ "BYR": 0,+ "BZD": 2,+ "CAD": 2,+ "CDF": 2,+ "CHF": 2,+ "CLF": 4,+ "CLP": 0,+ "CNY": 2,+ "COP": 2,+ "CRC": 2,+ "CUC": 2,+ "CUP": 2,+ "CVE": 2,+ "CZK": 2,+ "DJF": 0,+ "DKK": 2,+ "DOP": 2,+ "DZD": 2,+ "EEK": 2,+ "EGP": 2,+ "ERN": 2,+ "ETB": 2,+ "EUR": 2,+ "FJD": 2,+ "FKP": 2,+ "GBP": 2,+ "GEL": 2,+ "GHS": 2,+ "GIP": 2,+ "GMD": 2,+ "GNF": 0,+ "GTQ": 2,+ "GYD": 2,+ "HKD": 2,+ "HNL": 2,+ "HRK": 2,+ "HTG": 2,+ "HUF": 2,+ "IDR": 2,+ "ILS": 2,+ "INR": 2,+ "IQD": 3,+ "IRR": 2,+ "ISK": 0,+ "JMD": 2,+ "JOD": 3,+ "JPY": 0,+ "KES": 2,+ "KGS": 2,+ "KHR": 2,+ "KMF": 0,+ "KPW": 2,+ "KRW": 0,+ "KWD": 3,+ "KYD": 2,+ "KZT": 2,+ "LAK": 2,+ "LBP": 2,+ "LKR": 2,+ "LRD": 2,+ "LSL": 2,+ "LTL": 2,+ "LVL": 2,+ "LYD": 3,+ "MAD": 2,+ "MDL": 2,+ "MGA": 2,+ "MKD": 2,+ "MMK": 2,+ "MNT": 2,+ "MOP": 2,+ "MRO": 2,+ "MRU": 2,+ "MTL": 2,+ "MUR": 2,+ "MVR": 2,+ "MWK": 2,+ "MXN": 2,+ "MYR": 2,+ "MZN": 2,+ "NAD": 2,+ "NGN": 2,+ "NIO": 2,+ "NOK": 2,+ "NPR": 2,+ "NZD": 2,+ "OMR": 3,+ "PAB": 2,+ "PEN": 2,+ "PGK": 2,+ "PHP": 2,+ "PKR": 2,+ "PLN": 2,+ "PYG": 0,+ "QAR": 2,+ "RON": 2,+ "RSD": 2,+ "RUB": 2,+ "RWF": 0,+ "SAR": 2,+ "SBD": 2,+ "SCR": 2,+ "SDG": 2,+ "SEK": 2,+ "SGD": 2,+ "SHP": 2,+ "SKK": 2,+ "SLE": 2,+ "SLL": 2,+ "SOS": 2,+ "SRD": 2,+ "SSP": 2,+ "STD": 2,+ "STN": 2,+ "SVC": 2,+ "SYP": 2,+ "SZL": 2,+ "THB": 2,+ "TJS": 2,+ "TMM": 2,+ "TMT": 2,+ "TND": 3,+ "TOP": 2,+ "TRY": 2,+ "TTD": 2,+ "TWD": 2,+ "TZS": 2,+ "UAH": 2,+ "UGX": 0,+ "USD": 2,+ "UYI": 0,+ "UYU": 2,+ "UYW": 4,+ "UZS": 2,+ "VED": 2,+ "VEF": 2,+ "VES": 2,+ "VND": 0,+ "VUV": 0,+ "WST": 2,+ "XAF": 0,+ "XCD": 2,+ "XCG": 2,+ "XOF": 0,+ "XPF": 0,+ "YER": 2,+ "ZAR": 2,+ "ZMK": 2,+ "ZMW": 2,+ "ZWD": 2,+ "ZWG": 2,+ "ZWL": 2,+ "ZWN": 2,+ "ZWR": 2+}diff --git a/spree/core/lib/spree/money.rb b/spree/core/lib/spree/money.rbindex b8923d8279..97b01985de 100644--- a/spree/core/lib/spree/money.rb+++ b/spree/core/lib/spree/money.rb@@ -5,6 +5,18 @@ Money.rounding_mode = BigDecimal::ROUND_HALF_UPmodule Spreeclass Money+ # An amount that is not a canonical decimal string: a JSON number, a+ # localized or padded string, or more decimals than the field allows.+ class InvalidFormat < ArgumentError+ # @return [Symbol, nil] the request field the amount came from+ attr_reader :field++ def initialize(message = nil, field: nil)+ super(message)+ @field = field+ end+ end+# How Spree rounds an amount to a currency.## Lives here beside the rounding mode above because "how much is this worth@@ -14,6 +26,25 @@ module Spreemodule Roundingmodule_function+ # ISO 4217 minor units, the one table Ruby and the TypeScript clients+ # share. The Money gem disagrees for a few currencies (it writes HUF+ # without decimals), so Spree reads its own copy.+ EXPONENTS = JSON.parse(File.read(File.expand_path('../../config/currency_exponents.json', __dir__))).freeze++ # Unit prices may be quoted below the minor unit ("0.0125" USD); amounts+ # that change hands never are.+ UNIT_PRICE_DECIMALS = 4++ CANONICAL_DECIMAL = /\A-?\d+(\.\d+)?\z/++ ROUNDING_MODES = {+ half_up: BigDecimal::ROUND_HALF_UP,+ half_even: BigDecimal::ROUND_HALF_EVEN,+ half_down: BigDecimal::ROUND_HALF_DOWN,+ up: BigDecimal::ROUND_UP,+ down: BigDecimal::ROUND_DOWN+ }.freeze+# The number of decimal places a currency is written in: 2 for most, 0# for yen, 3 for dinar. An unknown currency falls back to two places# rather than raising — a sale is not the moment to discover a typo in a@@ -28,28 +59,104 @@ module Spree# @param currency [String, ::Money::Currency, nil]# @return [Integer]def precision(currency)- (::Money::Currency.find(currency) || ::Money::Currency.find('USD')).exponent+ code = currency.respond_to?(:iso_code) ? currency.iso_code : currency.to_s.upcase+ EXPONENTS[code] || ::Money::Currency.find(code)&.exponent || EXPONENTS['USD']end- # Rounds to the currency's own minor unit, half-up, so amounts reconcile- # to the cent when they are summed.+ # Rounds to the currency's own minor unit, so amounts reconcile to the+ # cent when they are summed.## @param amount [Numeric, String, nil]# @param currency [String, ::Money::Currency, nil]+ # @param mode [Symbol] one of {ROUNDING_MODES}; tax providers pick their own# @return [BigDecimal]- def to_currency(amount, currency)- quantize(amount, precision(currency))+ def to_currency(amount, currency, mode: :half_up)+ quantize(amount, precision(currency), mode: mode)end# The same rounding against a precision already in hand.## @param amount [Numeric, String, nil]# @param precision [Integer]+ # @param mode [Symbol] one of {ROUNDING_MODES}# @return [BigDecimal]- def quantize(amount, precision)- BigDecimal(amount.to_s).round(precision, BigDecimal::ROUND_HALF_UP)+ def quantize(amount, precision, mode: :half_up)+ BigDecimal(amount.to_s).round(precision, ROUNDING_MODES.fetch(mode))end+ # Reads a money amount from an API request. Only a canonical decimal+ # string is accepted — never a JSON number, which may already have lost+ # precision as a float, and never more decimals than the field holds.+ #+ # @param value [String, nil]+ # @param currency [String, ::Money::Currency, nil]+ # @param unit_price [Boolean] allows up to {UNIT_PRICE_DECIMALS} decimals+ # @return [BigDecimal, nil]+ # @raise [Spree::Money::InvalidFormat]+ def parse_canonical(value, currency, unit_price: false)+ amount = parse_canonical_decimal(value)+ return if amount.nil?++ allowed = unit_price ? [precision(currency), UNIT_PRICE_DECIMALS].max : precision(currency)+ raise InvalidFormat, "has more than #{allowed} decimal places" if decimal_places(value) > allowed++ amount+ end++ # Reads a rate or percentage from an API request: a canonical decimal+ # string with no limit on its decimals.+ #+ # @param value [String, nil]+ # @return [BigDecimal, nil]+ # @raise [Spree::Money::InvalidFormat]+ def parse_canonical_decimal(value)+ return if value.nil?+ raise InvalidFormat, 'must be a decimal string like "19.99"' unless value.is_a?(String) && value.match?(CANONICAL_DECIMAL)++ BigDecimal(value)+ 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+ # places dropped ("0.0125", "19.99").+ #+ # @param amount [Numeric, String, nil]+ # @param currency [String, ::Money::Currency, nil]+ # @param unit_price [Boolean]+ # @return [String, nil]+ def format(amount, currency, unit_price: false)+ return 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')+ fraction.empty? ? whole : "#{whole}.#{fraction}"+ end++ # Writes a rate or percentage with no trailing zeros ("0.23", "23").+ #+ # @param value [Numeric, String, nil]+ # @return [String, nil]+ def format_decimal(value)+ return if value.nil?++ BigDecimal(value.to_s).to_s('F').sub(/\.?0+\z/, '')+ end++ def decimal_places(value)+ value.include?('.') ? value.split('.').last.length : 0+ end+ private_class_method :decimal_places+# An amount as a whole number of the currency's smallest unit — cents for# most currencies, whole yen for one written without decimals.#@@ -102,8 +209,12 @@ module Spree@options = Spree::Money.default_formatting_rules.merge(options)end+ # The amount in hundredths of the currency, whatever its own minor unit —+ # the unit payment gateways have always been called with.+ #+ # @return [Integer]def amount_in_cents- (cents / currency.subunit_to_unit.to_f * 100).round+ Rounding.quantize(to_d * 100, 0).to_ienddef absdiff --git a/spree/core/lib/tasks/money.rake b/spree/core/lib/tasks/money.rakenew file mode 100644index 0000000000..da361b5197--- /dev/null+++ b/spree/core/lib/tasks/money.rake@@ -0,0 +1,40 @@+namespace :spree do+ namespace :money do+ desc <<~DESC+ Lists payment capture events in currencies without two decimals (yen,+ dinar, ...) and writes nothing (Spree 6.0).++ Before 6.0 a partial or manual capture recorded its amount in the wrong+ unit for these currencies: a 1000 JPY capture was recorded as 100000,+ a 1.500 KWD capture as 0.150. A purchase (authorize and capture in one)+ recorded the right amount, and the two cannot be told apart from the+ row, so every event is listed with both readings: as recorded, and+ corrected as if the capture flow wrote it. Compare them with the+ gateway's own records before changing anything.+ DESC+ task audit_capture_events: :environment do+ listed = 0++ Spree::PaymentCaptureEvent.includes(payment: [:order, :cart, :order_group]).find_each do |event|+ payment = event.payment+ next if payment.nil?++ exponent = Spree::Money::Rounding.precision(payment.currency)+ next if exponent == 2++ corrected = event.amount * (10**exponent) / 100+ puts [+ event.prefixed_id,+ payment.number,+ payment.currency,+ "recorded=#{Spree::Money::Rounding.format(event.amount, payment.currency)}",+ "if_from_capture=#{Spree::Money::Rounding.format(corrected, payment.currency)}",+ "payment_amount=#{Spree::Money::Rounding.format(payment.amount, payment.currency)}"+ ].join("\t")+ listed += 1+ end++ puts " #{listed} capture event(s) in currencies without two decimals. Nothing was changed."+ end+ end+enddiff --git a/spree/core/lib/tasks/seller_sample_data.rake b/spree/core/lib/tasks/seller_sample_data.rakeindex a83bf659b4..9a1ab2e358 100644--- a/spree/core/lib/tasks/seller_sample_data.rake+++ b/spree/core/lib/tasks/seller_sample_data.rake@@ -107,7 +107,7 @@ namespace :spree doorder = sample_orders[index]seller.seller_transfers.create!(store: store, order: order, payout: payout,- amount: order.total * 0.85, currency: currency,+ amount: Spree::Money::Rounding.to_currency(order.total * BigDecimal('0.85'), currency), currency: currency,kind: 'earning', provider: provider, status: 'completed',created_at: order.completed_at)@@ -118,7 +118,7 @@ namespace :spree dooriginal = seller.seller_transfers.earnings.order(:created_at).lastseller.seller_transfers.create!(store: store, order: original.order, reversed_from: original,- amount: -(original.amount * 0.5), currency: currency,+ amount: -Spree::Money::Rounding.to_currency(original.amount / 2, currency), currency: currency,kind: 'refund_reversal', provider: provider, status: 'completed')diff --git a/spree/core/lib/tasks/typed_adjustments_migration.rake b/spree/core/lib/tasks/typed_adjustments_migration.rakeindex 7d8f0e3e20..e737203ae3 100644--- a/spree/core/lib/tasks/typed_adjustments_migration.rake+++ b/spree/core/lib/tasks/typed_adjustments_migration.rake@@ -63,7 +63,7 @@ namespace :spree dopromotion = action&.promotionSpree::TypedAdjustmentsMigration.build_distributed_discounts(order, row, adjustable, promotion, action, stats)when nil- if row.amount.to_f.negative?+ if row.amount.to_d.negative?Spree::TypedAdjustmentsMigration.build_distributed_discounts(order, row, adjustable, nil, nil, stats, kind: 'manual')elseSpree::Fee.create!(diff --git a/spree/core/spec/lib/spree/money_spec.rb b/spree/core/spec/lib/spree/money_spec.rbindex 0933b2c758..a37f8e34f1 100644--- a/spree/core/spec/lib/spree/money_spec.rb+++ b/spree/core/spec/lib/spree/money_spec.rb@@ -170,6 +170,12 @@ describe Spree::Money doit { expect(money.amount_in_cents).to eq(10000) }endend++ it 'counts hundredths without float error' do+ expect(described_class.new(BigDecimal('1.15')).amount_in_cents).to eq(115)+ expect(described_class.new(BigDecimal('0.29')).amount_in_cents).to eq(29)+ expect(described_class.new(BigDecimal('1234567.89')).amount_in_cents).to eq(123_456_789)+ endenddescribe '#as_json' do@@ -202,6 +208,88 @@ describe Spree::Money doendend+ describe '.precision' do+ it 'follows ISO 4217 where the Money gem does not' do+ expect(described_class.precision('HUF')).to eq(2)+ expect(described_class.precision('MGA')).to eq(2)+ end++ it 'reads the exponent of zero-, two- and three-decimal currencies' do+ expect(%w[JPY USD KWD].map { |code| described_class.precision(code) }).to eq([0, 2, 3])+ end++ it 'falls back to two places for an unknown code' do+ expect(described_class.precision('ZZZ')).to eq(2)+ end+ end++ describe '.to_currency' do+ it 'rounds half up by default' do+ expect(described_class.to_currency(BigDecimal('2.345'), 'USD')).to eq(BigDecimal('2.35'))+ end++ it 'rounds with the mode a caller asks for' do+ expect(described_class.to_currency(BigDecimal('2.345'), 'USD', mode: :half_even)).to eq(BigDecimal('2.34'))+ end+ end++ describe '.parse_canonical' do+ it 'reads a canonical string exactly' do+ expect(described_class.parse_canonical('1234567.89', 'USD')).to eq(BigDecimal('1234567.89'))+ expect(described_class.parse_canonical('-0.29', 'USD')).to eq(BigDecimal('-0.29'))+ end++ it 'passes nil through' do+ expect(described_class.parse_canonical(nil, 'USD')).to be_nil+ end++ [19.99, 20, '1,99', '1.234,56', ' 5', '+5', '1e3', '', '.5', '5.'].each do |value|+ it "rejects #{value.inspect}" do+ expect { described_class.parse_canonical(value, 'USD') }.to raise_error(Spree::Money::InvalidFormat)+ end+ end++ it 'rejects more decimals than the currency has' do+ expect { described_class.parse_canonical('19.999', 'USD') }.to raise_error(Spree::Money::InvalidFormat)+ expect { described_class.parse_canonical('100.5', 'JPY') }.to raise_error(Spree::Money::InvalidFormat)+ expect(described_class.parse_canonical('1.500', 'KWD')).to eq(BigDecimal('1.5'))+ end++ it 'allows a unit price four decimals' do+ expect(described_class.parse_canonical('0.0125', 'USD', unit_price: true)).to eq(BigDecimal('0.0125'))+ expect { described_class.parse_canonical('0.01255', 'USD', unit_price: true) }.to raise_error(Spree::Money::InvalidFormat)+ end+ end++ describe '.format' do+ it "writes exactly the currency's decimal places" do+ expect(described_class.format(BigDecimal('10'), 'USD')).to eq('10.00')+ expect(described_class.format(BigDecimal('1.5'), 'KWD')).to eq('1.500')+ expect(described_class.format(BigDecimal('100'), 'JPY')).to eq('100')+ expect(described_class.format(BigDecimal('-0.5'), 'USD')).to eq('-0.50')+ end++ it 'keeps a unit price below the minor unit and drops zeros beyond it' do+ expect(described_class.format(BigDecimal('0.0125'), 'USD', unit_price: true)).to eq('0.0125')+ expect(described_class.format(BigDecimal('19.9900'), 'USD', unit_price: true)).to eq('19.99')+ expect(described_class.format(BigDecimal('100'), 'JPY', unit_price: true)).to eq('100')+ expect(described_class.format(BigDecimal('100.5'), 'JPY', unit_price: true)).to eq('100.5')+ end++ it 'passes nil through' do+ expect(described_class.format(nil, 'USD')).to be_nil+ end+ end++ describe '.format_decimal' do+ it 'drops trailing zeros' do+ expect(described_class.format_decimal(BigDecimal('0.23000'))).to eq('0.23')+ expect(described_class.format_decimal(BigDecimal('23.00'))).to eq('23')+ expect(described_class.format_decimal(BigDecimal('100'))).to eq('100')+ expect(described_class.format_decimal(BigDecimal('0'))).to eq('0')+ end+ end+describe '.from_minor_units' doit 'is the inverse for each currency' do{ 'USD' => '12.34', 'JPY' => '1234', 'BHD' => '1.234' }.each do |currency, amount|diff --git a/spree/core/spec/lib/tasks/money_spec.rb b/spree/core/spec/lib/tasks/money_spec.rbnew file mode 100644index 0000000000..f268f9bba2--- /dev/null+++ b/spree/core/spec/lib/tasks/money_spec.rb@@ -0,0 +1,29 @@+require 'spec_helper'+require 'rake'++describe 'spree:money:audit_capture_events' do+ subject { Rake::Task['spree:money:audit_capture_events'] }++ before(:all) do+ Rake::Task.define_task(:environment)+ load Spree::Core::Engine.root.join('lib', 'tasks', 'money.rake')+ end++ before { subject.reenable }++ let(:yen_payment) do+ create(:payment, amount: 1000).tap { |payment| payment.order.update_columns(currency: 'JPY') }+ end+ let(:dollar_payment) { create(:payment, amount: 10) }+ let!(:yen_event) { yen_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' do+ expect { 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+ ).to_stdout++ expect(yen_event.reload.amount).to eq(100_000)+ end+enddiff --git a/spree/core/spec/models/concerns/spree/vat_price_calculation_spec.rb b/spree/core/spec/models/concerns/spree/vat_price_calculation_spec.rbindex bde405ec6d..66c081b281 100644--- a/spree/core/spec/models/concerns/spree/vat_price_calculation_spec.rb+++ b/spree/core/spec/models/concerns/spree/vat_price_calculation_spec.rb@@ -39,6 +39,27 @@ describe Spree::VatPriceCalculation, type: :model doexpect(gross_for(france)).to eq(100.84)end+ context 'rounding conformance' do+ before do+ create(:tax_rate, name: 'FR 20% incl', amount: 0.20, tax_category: category,+ country_code: france&.iso, included_in_price: true, store: store)+ end++ it 'restates to the exact cent, half up' do+ price.update!(amount: BigDecimal('19.99'))++ # 19.99 / 1.19 * 1.20 = 20.15798…+ expect(gross_for(france)).to eq(BigDecimal('20.16'))+ end++ it 'restates a yen price to whole yen' do+ yen_price = build(:price, variant: variant, currency: 'JPY', amount: BigDecimal('1000'))++ # 1000 / 1.19 * 1.20 = 1008.403…+ expect(yen_price.price_including_vat_for(country: france, market: home_market)).to eq(BigDecimal('1008'))+ end+ end+it 'charges the net where the destination levies nothing — a zero-rated export' doexpect(gross_for(japan)).to eq(84.03)enddiff --git a/spree/core/spec/models/spree/adjusters/promotion_spec.rb b/spree/core/spec/models/spree/adjusters/promotion_spec.rbindex 75b5a64a08..d17347d9fe 100644--- a/spree/core/spec/models/spree/adjusters/promotion_spec.rb+++ b/spree/core/spec/models/spree/adjusters/promotion_spec.rb@@ -86,6 +86,25 @@ describe Spree::Adjusters::Promotion, type: :model doexpect(rows.map(&:line_item_id)).to match_array(order.line_items.ids)end+ it 'splits a remainder to the cent and sums exactly to the promotion amount' do+ promo = create(:promotion_with_order_adjustment, weighted_order_adjustment_amount: 10, code: nil, kind: :automatic, store: store)+ promo.activate(order: order)++ amounts = order.discounts.reload.map(&:amount)+ expect(amounts).to match_array([BigDecimal('-3.34'), BigDecimal('-3.33'), BigDecimal('-3.33')])+ expect(amounts.sum).to eq(BigDecimal('-10'))+ end++ it 'splits a yen promotion in whole yen' do+ order.update_columns(currency: 'JPY')+ promo = create(:promotion_with_order_adjustment, weighted_order_adjustment_amount: 10, code: nil, kind: :automatic, store: store)+ promo.promotion_actions.first.calculator.update!(preferred_currency: 'JPY')+ promo.activate(order: order)++ amounts = order.discounts.reload.map(&:amount)+ expect(amounts).to match_array([BigDecimal('-4'), BigDecimal('-3'), BigDecimal('-3')])+ end+it 'never distributes more than the remaining line bases' dopromo = create(:promotion_with_order_adjustment, weighted_order_adjustment_amount: 9_999, code: nil, kind: :automatic, store: store)promo.activate(order: order)diff --git a/spree/core/spec/models/spree/refund_spec.rb b/spree/core/spec/models/spree/refund_spec.rbindex f3ae35df66..39bb1e3537 100644--- a/spree/core/spec/models/spree/refund_spec.rb+++ b/spree/core/spec/models/spree/refund_spec.rb@@ -12,15 +12,10 @@ describe Spree::Refund, type: :model dodescribe '#amount=' dolet(:refund) { build(:refund) }- let(:amount) { '1,599,99' }- before do- allow_any_instance_of(Spree::Refund).to receive(:amount_is_less_than_or_equal_to_allowed_amount)- refund.amount = amount- end-- it 'is expected to equal to localized number' do- expect(refund.amount).to eq(Spree::LocalizedNumber.parse(amount))+ it 'stores a canonical decimal exactly under a comma-decimal locale' do+ I18n.with_locale(:nl) { refund.amount = '49.50' }+ expect(refund.amount).to eq(BigDecimal('49.50'))endend@@ -60,6 +55,17 @@ describe Spree::Refund, type: :model doand_return(gateway_response)end+ context 'with an amount a float cannot hold exactly' do+ let(:amount) { BigDecimal('1.15') }+ let(:amount_in_cents) { 115 }++ it 'credits the exact hundredths at the gateway' do+ subject++ expect(payment.payment_method).to have_received(:credit).with(115, any_args)+ end+ end+it 'is never attempted by creation alone' doexpect(payment.payment_method).not_to receive(:credit)diff --git a/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rbindex 4dd1cf25cb..0402d5c7bb 100644--- a/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb+++ b/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb@@ -28,8 +28,8 @@ RSpec.describe Spree::CSV::ProductVariantPresenter doexpect(subject[9]).to eq product.meta_keywordsexpect(subject[10]).to eq product.tag_list.to_sexpect(subject[11]).to eq product.label_list.to_s- expect(subject[12]).to eq variant.amount_in(store.default_currency).to_f- expect(subject[13]).to eq variant.compare_at_amount_in(store.default_currency).to_f+ expect(subject[12]).to eq '19.99'+ expect(subject[13]).to eq '0.00'expect(subject[14]).to eq store.default_currencyexpect(subject[15]).to eq variant.widthexpect(subject[16]).to eq variant.height@@ -159,7 +159,7 @@ RSpec.describe Spree::CSV::ProductVariantPresenter doit 'returns variant specific fields' doexpect(subject[1]).to eq variant.sku- expect(subject[12]).to eq variant.amount_in(store.default_currency).to_f+ expect(subject[12]).to eq '19.99'expect(subject[23]).to eq falseexpect(subject[32]).to eq 'Color'expect(subject[33]).to eq 'Red'@@ -269,8 +269,8 @@ RSpec.describe Spree::CSV::ProductVariantPresenter do# Price fields populatedexpect(result[described_class::CSV_HEADERS.index('slug')]).to eq product.slugexpect(result[described_class::CSV_HEADERS.index('sku')]).to eq variant.sku- expect(result[described_class::CSV_HEADERS.index('price')]).to eq 58.99- expect(result[described_class::CSV_HEADERS.index('compare_at_price')]).to eq 69.99+ expect(result[described_class::CSV_HEADERS.index('price')]).to eq '58.99'+ expect(result[described_class::CSV_HEADERS.index('compare_at_price')]).to eq '69.99'expect(result[described_class::CSV_HEADERS.index('currency')]).to eq 'EUR'# Everything else nildiff --git a/spree/core/spec/services/spree/order_groups/allocate_payments_spec.rb b/spree/core/spec/services/spree/order_groups/allocate_payments_spec.rbindex 4326dd69d2..8bf88b500b 100644--- a/spree/core/spec/services/spree/order_groups/allocate_payments_spec.rb+++ b/spree/core/spec/services/spree/order_groups/allocate_payments_spec.rb@@ -39,6 +39,28 @@ RSpec.describe Spree::OrderGroups::AllocatePayments doendend+ describe 'a yen checkout' do+ let!(:orders) do+ [BigDecimal('333'), BigDecimal('333'), BigDecimal('334')].map do |total|+ create(:order, store: store, order_group: group, seller: seller, total: total).tap do |order|+ order.update_columns(currency: 'JPY')+ end+ end+ end++ before do+ group.update_columns(currency: 'JPY')+ payment_for(500)+ payment_for(500)+ described_class.call(group: group.reload)+ end++ it 'shares out whole yen, each child getting exactly its total' do+ expect(shares_by_order).to eq([BigDecimal('333'), BigDecimal('333'), BigDecimal('334')])+ expect(Spree::PaymentSplit.sum(:authorized_amount)).to eq(BigDecimal('1000'))+ end+ end+describe 'one payment' dolet!(:orders) do[BigDecimal('40'), BigDecimal('60')].map do |total|diff --git a/spree/core/spec/workflows/spree/payments/capture_spec.rb b/spree/core/spec/workflows/spree/payments/capture_spec.rbindex 7dd2bf6aff..bbd3fddba3 100644--- a/spree/core/spec/workflows/spree/payments/capture_spec.rb+++ b/spree/core/spec/workflows/spree/payments/capture_spec.rb@@ -49,6 +49,33 @@ RSpec.describe Spree::Payments::Capture doexpect(remainder.amount).to eq(35.75)end+ context 'with exact amounts' do+ { '0.29' => 29, '1.15' => 115, '1234567.89' => 123_456_789 }.each do |amount, hundredths|+ it "records a capture of #{amount} to the cent" do+ payment.update_columns(amount: BigDecimal(amount))+ order.update_columns(total: BigDecimal(amount))+ expect(gateway).to receive(:capture).with(hundredths, '123', anything).and_return(success_response)++ described_class.call(payment: payment)++ expect(payment.reload.captured_amount).to eq(BigDecimal(amount))+ end+ end++ 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'))+ end+ end+it 'is a no-op for an already-captured payment' docompleted = create(:payment, payment_method: gateway, source: card, status: 'completed')expect(gateway).not_to receive(:capture)diff --git a/spree/core/spec/workflows/spree/refunds/create_spec.rb b/spree/core/spec/workflows/spree/refunds/create_spec.rbindex 28f83040bb..03cc894625 100644--- a/spree/core/spec/workflows/spree/refunds/create_spec.rb+++ b/spree/core/spec/workflows/spree/refunds/create_spec.rb@@ -28,6 +28,18 @@ RSpec.describe Spree::Refunds::Create doexpect(result.value.amount).to eq(10)end+ it 'leaves the exact residual after partial refunds, and refunds it to the cent' do+ described_class.call(payment: payment, amount: BigDecimal('10.33'))+ described_class.call(payment: payment.reload, amount: BigDecimal('0.29'))++ expect(payment.reload.credit_allowed).to eq(BigDecimal('35.13'))++ result = described_class.call(payment: payment, amount: BigDecimal('35.13'))++ expect(result).to be_success+ expect(payment.reload.credit_allowed).to eq(BigDecimal('0'))+ end+it 'records the originator' dooriginator = create(:return)diff --git a/spree/providers/easypost/lib/spree_easypost.rb b/spree/providers/easypost/lib/spree_easypost.rbindex ae1543c1db..2dbe80e192 100644--- a/spree/providers/easypost/lib/spree_easypost.rb+++ b/spree/providers/easypost/lib/spree_easypost.rb@@ -176,7 +176,7 @@ module SpreeEasyPostreturn unless origin&.country_code == 'US'return unless items.all? { |item| item[:currency].to_s.upcase == 'USD' }- declared_value = items.sum { |item| item[:value].to_f }+ declared_value = items.sum { |item| BigDecimal(item[:value].to_s) }'NOEEI 30.37(a)' if declared_value < EEI_EXEMPTION_LIMIT_USDend@@ -195,7 +195,7 @@ module SpreeEasyPost{description: variant.customs_description_for_declaration,quantity: item.quantity,- value: (item.price.to_f * item.quantity).round(2),+ value: Spree::Money::Rounding.to_currency(item.price * item.quantity, package.owner&.currency).to_f, # EasyPost reads customs values as JSON numbersweight: ounces(item.weight, store),origin_country: variant.country_of_origin.presence,hs_tariff_number: variant.hs_code.presence,diff --git a/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb b/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rbindex 4422b02099..7b938ff94f 100644--- a/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb+++ b/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb@@ -386,9 +386,11 @@ module SpreeMeilisearchdef build_filter_condition(key, value)case keywhen 'price_gte'- "price >= #{value.to_f}"+ price_bound = price_filter_value(value)+ "price >= #{price_bound}" if price_boundwhen 'price_lte'- "price <= #{value.to_f}"+ price_bound = price_filter_value(value)+ "price <= #{price_bound}" if price_boundwhen 'in_stock''in_stock = true' if value.to_s != '0'when 'out_of_stock'@@ -438,6 +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.+ def price_filter_value(value)+ bound = BigDecimal(value.to_s, exception: false)+ Spree::Money::Rounding.format_decimal(bound) if bound&.finite?+ end+def format_custom_field_filter_value(value, numeric)if numericFloat(value.to_s, exception: false)&.to_sdiff --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 4a31debaa8..9cf42309ec 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@@ -94,11 +94,21 @@ RSpec.describe SpreeMeilisearch::SearchProvider docontext 'with price filter' doit 'passes price filter to Meilisearch' doexpect(mock_index).to receive(:search).with(anything, hash_including(- filter: include('price >= 10.0')+ filter: include('price >= 10'))).and_return(ms_response)provider.search_and_filter(scope: store.products, filters: { 'price_gte' => '10' })end++ it 'keeps a decimal bound exact and drops one that is not a finite number' do+ expect(mock_index).to receive(:search) do |_query, options|+ expect(options[:filter]).to include('price <= 19.99')+ expect(options[:filter]).not_to include(a_string_starting_with('price >='))+ ms_response+ end++ provider.search_and_filter(scope: store.products, filters: { 'price_gte' => 'Infinity', 'price_lte' => '19.99' })+ endendcontext 'with in_stock filter' do