Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Changed money columns to decimal(19,4)

Damian Legawiec133e18151876
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index 1840e91ee0..3ec0823a2b 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -822,6 +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 take a number or a canonical decimal string (`"1234.56"`); any other text raises `Spree::Money::InvalidFormat`, which the API answers with `invalid_money_format`. 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.
+- **Money columns widen to `decimal(19,4)`.** They now hold a Kuwaiti dinar's third decimal, unit prices below a cent (`0.0125`), and very large amounts in currencies like the Vietnamese dong. No stored value changes. Totals, payments and refunds are still rounded to the currency's decimals; only unit prices (`price`, `compare_at_amount`, `cost_price`, `unit_cost`) keep up to four. The migration rewrites each money table while it runs, which locks `spree_orders`, `spree_line_items` and `spree_adjustments` for as long as that takes. If you cannot take that lock, widen those columns online first (add a `decimal(19,4)` shadow column, backfill it in batches, swap it in), and the migration skips any column already at `(19,4)`. Extensions with their own money tables, such as `spree_stripe_payment_intents` from the standalone Stripe gem, should widen theirs the same way.
- **Payment gateways receive the amount with its currency.** `authorize`, `purchase`, `capture` and `credit` are called with a `Spree::Money` (amount and currency) instead of an integer in hundredths, which was wrong for yen and dinar. A gateway opts in with `self.accepts_money_amounts = true` and converts the amount to its provider's unit (Stripe's rules live in `SpreeStripe::Units`). A gateway that has not opted in still receives hundredths, with a deprecation warning, until 6.1. `Spree.payment_capture_workflow.call(amount:)` takes the amount in the currency's own units; an Integer is still read as hundredths, with a warning.
- **Capture records in yen and dinar written before 6.0 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. New captures are recorded exactly. To list the old records, writing nothing, run:
diff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rb
index 6d03699f15..2239a36605 100644
--- a/spree/core/app/models/concerns/spree/product_scopes.rb
+++ b/spree/core/app/models/concerns/spree/product_scopes.rb
@@ -20,7 +20,8 @@ module Spree
.group("#{Variant.table_name}.product_id")
.to_sql
- price_expr = Arel.sql('COALESCE(price_agg.agg_price, 999999999)')
+ # Above any price decimal(19,4) holds, so an unpriced product sorts last.
+ price_expr = Arel.sql('COALESCE(price_agg.agg_price, 1000000000000000)')
joins("LEFT JOIN (#{price_agg_sql}) AS price_agg ON price_agg.product_id = #{Product.table_name}.id").
select("#{Product.table_name}.*").
diff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rb
index 99fc8b3870..859c391871 100644
--- a/spree/core/app/models/spree/line_item.rb
+++ b/spree/core/app/models/spree/line_item.rb
@@ -231,7 +231,7 @@ module Spree
#
# @return [BigDecimal]
def amount
- price * quantity
+ Spree::Money::Rounding.to_currency(price * quantity, currency)
end
# Returns the compare at amount (compare at price * quantity) of the line item
diff --git a/spree/core/app/models/spree/price.rb b/spree/core/app/models/spree/price.rb
index 070e076c22..7df5e9c285 100644
--- a/spree/core/app/models/spree/price.rb
+++ b/spree/core/app/models/spree/price.rb
@@ -19,7 +19,8 @@ module Spree
acts_as_paranoid
- MAXIMUM_AMOUNT = BigDecimal('99_999_999.99')
+ # The largest amount decimal(19,4) holds.
+ MAXIMUM_AMOUNT = BigDecimal('999_999_999_999_999.9999')
# How many breaks one variant may carry on one list in one currency. A UI
# sanity bound rather than a technical one — but enforced here so no
diff --git a/spree/core/db/migrate/20261009000001_change_money_columns_to_decimal_19_4.rb b/spree/core/db/migrate/20261009000001_change_money_columns_to_decimal_19_4.rb
new file mode 100644
index 0000000000..d28ce44394
--- /dev/null
+++ b/spree/core/db/migrate/20261009000001_change_money_columns_to_decimal_19_4.rb
@@ -0,0 +1,99 @@
+# Widens every money column to decimal(19,4): room for a dinar's third decimal,
+# sub-cent unit prices and very large amounts. Every stored value fits exactly,
+# so no value changes. A column already at (19,4) is skipped, so an install
+# that widened its largest tables online ahead of the upgrade runs this as a
+# no-op for those (see the 5.6 to 6.0 upgrade guide).
+class ChangeMoneyColumnsToDecimal194 < ActiveRecord::Migration[8.1]
+ COLUMNS = {
+ spree_adjustments: %i[amount],
+ spree_carts: %i[additional_tax_total adjustment_total delivery_total discount_total fee_total included_tax_total
+ item_total non_taxable_adjustment_total payment_total taxable_adjustment_total total],
+ spree_catalog_order_minimums: %i[amount],
+ spree_claim_line_items: %i[additional_tax_total included_tax_total refund_amount],
+ spree_commission_lines: %i[amount tax_amount total],
+ spree_commission_rate_values: %i[amount max_amount min_amount],
+ spree_delivery_method_services: %i[markup_flat],
+ spree_delivery_methods: %i[markup_flat],
+ spree_delivery_rates: %i[cost],
+ spree_discounts: %i[amount value],
+ spree_exchange_line_items: %i[new_additional_tax_total new_included_tax_total original_additional_tax_total
+ original_included_tax_total],
+ spree_fees: %i[amount],
+ spree_fulfillments: %i[additional_tax_total adjustment_total cost discount_total included_tax_total
+ non_taxable_adjustment_total pre_tax_amount taxable_adjustment_total],
+ spree_gift_card_batches: %i[amount],
+ spree_gift_cards: %i[amount amount_authorized amount_used],
+ spree_line_items: %i[additional_tax_total adjustment_total cost_price discount_total included_tax_total
+ non_taxable_adjustment_total pre_tax_amount price taxable_adjustment_total],
+ spree_orders: %i[additional_tax_total adjustment_total commission_amount_total commission_tax_total commission_total
+ delivery_total discount_total fee_total included_tax_total item_total non_taxable_adjustment_total
+ payment_total taxable_adjustment_total total],
+ spree_payment_capture_events: %i[amount],
+ spree_payment_sessions: %i[amount],
+ spree_payment_splits: %i[authorized_amount captured_amount claimed_amount refunded_amount],
+ spree_payments: %i[amount],
+ spree_price_histories: %i[amount compare_at_amount],
+ spree_prices: %i[amount compare_at_amount],
+ spree_products: %i[revenue],
+ spree_products_stores: %i[revenue],
+ spree_purchase_order_items: %i[unit_cost],
+ spree_refunds: %i[amount tax_amount],
+ spree_reimbursement_credits: %i[amount],
+ spree_reimbursements: %i[total],
+ spree_return_items: %i[additional_tax_total included_tax_total pre_tax_amount],
+ spree_return_line_items: %i[additional_tax_total included_tax_total pre_tax_amount],
+ spree_seller_payouts: %i[amount],
+ spree_seller_transfers: %i[amount settled_amount],
+ spree_sellers: %i[minimum_payout_amount],
+ spree_shipping_labels: %i[cost],
+ spree_stock_movements: %i[unit_cost],
+ spree_store_credit_events: %i[amount user_total_amount],
+ spree_store_credits: %i[amount amount_authorized amount_used],
+ spree_tax_lines: %i[amount],
+ spree_variants: %i[cost_price]
+ }.freeze
+
+ # What `down` restores: decimal(10,2) unless listed.
+ ORIGINAL = {
+ 'spree_delivery_rates.cost' => [8, 2],
+ 'spree_store_credit_events.amount' => [8, 2],
+ 'spree_store_credit_events.user_total_amount' => [8, 2],
+ 'spree_store_credits.amount' => [8, 2],
+ 'spree_store_credits.amount_authorized' => [8, 2],
+ 'spree_store_credits.amount_used' => [8, 2],
+ 'spree_fulfillments.pre_tax_amount' => [12, 4],
+ 'spree_line_items.pre_tax_amount' => [12, 4],
+ 'spree_return_items.additional_tax_total' => [12, 4],
+ 'spree_return_items.included_tax_total' => [12, 4],
+ 'spree_return_items.pre_tax_amount' => [12, 4],
+ 'spree_products.revenue' => [16, 4]
+ }.freeze
+
+ def up
+ each_column { |table, column| widen(table, column, 19, 4) }
+ end
+
+ def down
+ each_column do |table, column|
+ precision, scale = ORIGINAL.fetch("#{table}.#{column}", [10, 2])
+ widen(table, column, precision, scale)
+ end
+ end
+
+ private
+
+ def each_column
+ COLUMNS.each do |table, columns|
+ next unless table_exists?(table)
+
+ columns.each { |column| yield(table, column) if column_exists?(table, column) }
+ end
+ end
+
+ def widen(table, name, precision, scale)
+ column = connection.columns(table).find { |candidate| candidate.name == name.to_s }
+ return if column.precision == precision && column.scale == scale
+
+ change_column table, name, :decimal, precision: precision, scale: scale, null: column.null, default: column.default
+ end
+end
diff --git a/spree/core/lib/spree/money.rb b/spree/core/lib/spree/money.rb
index a43266670f..7125633368 100644
--- a/spree/core/lib/spree/money.rb
+++ b/spree/core/lib/spree/money.rb
@@ -50,12 +50,6 @@ module Spree
# rather than raising — a sale is not the moment to discover a typo in a
# currency code.
#
- # Note that Spree's money columns are `decimal(_, 2)` throughout, so a
- # three-decimal currency still loses its last place on the way into the
- # database. Rounding here to the currency's own precision keeps the
- # arithmetic honest and means widening those columns would be the only
- # change needed; it does not by itself make Spree dinar-exact.
- #
# @param currency [String, ::Money::Currency, nil]
# @return [Integer]
def precision(currency)
diff --git a/spree/core/spec/workflows/spree/carts/recalculate_totals_spec.rb b/spree/core/spec/workflows/spree/carts/recalculate_totals_spec.rb
index 7f4b2e672a..aab7a826c8 100644
--- a/spree/core/spec/workflows/spree/carts/recalculate_totals_spec.rb
+++ b/spree/core/spec/workflows/spree/carts/recalculate_totals_spec.rb
@@ -19,6 +19,47 @@ module Spree
expect(order.total).to eq(order.item_total + order.delivery_total + order.adjustment_total)
end
+ context 'rounding conformance across currencies' do
+ def priced_order(currency, price, quantity)
+ order = create(:order_with_line_items, store: store, line_items_count: 1)
+ order.update_columns(currency: currency)
+ order.line_items.first.update_columns(currency: currency, price: BigDecimal(price), quantity: quantity)
+ described_class.call(cart: order.reload)
+ order.reload
+ end
+
+ it 'keeps a dinar total to the thousandth' do
+ order = priced_order('KWD', '1.505', 3)
+
+ expect(order.item_total).to eq(BigDecimal('4.515'))
+ end
+
+ it 'holds a dong total above one hundred million' do
+ order = priced_order('VND', '150000000', 2)
+
+ expect(order.item_total).to eq(BigDecimal('300000000'))
+ end
+
+ it 'rounds a line priced below the cent to whole cents' do
+ order = priced_order('USD', '0.0125', 3)
+
+ expect(order.item_total).to eq(BigDecimal('0.04'))
+ end
+
+ it 'keeps a sub-cent unit price exact when the quantity makes it whole' do
+ order = priced_order('USD', '0.0125', 1000)
+
+ expect(order.line_items.first.price).to eq(BigDecimal('0.0125'))
+ expect(order.item_total).to eq(BigDecimal('12.5'))
+ end
+
+ it 'rounds a yen total to whole yen' do
+ order = priced_order('JPY', '100.5', 1)
+
+ expect(order.item_total).to eq(BigDecimal('101'))
+ end
+ end
+
it 'nets refunds out of the payment total' do
order = create(:completed_order_with_totals, store: store)
payment = create(:payment, order: order, amount: order.total, status: 'completed')