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 `spree_prices` unique indexes for price list support (#13433)
Damian Legawiec5f0638ddd90d
diff --git a/api/spec/requests/spree/api/v2/storefront/cart_spec.rb b/api/spec/requests/spree/api/v2/storefront/cart_spec.rbindex b1739e7abc..14a80141b2 100644--- a/api/spec/requests/spree/api/v2/storefront/cart_spec.rb+++ b/api/spec/requests/spree/api/v2/storefront/cart_spec.rb@@ -7,7 +7,7 @@ describe 'API V2 Storefront Cart Spec', type: :request dolet(:user) { create(:user) }let(:order) { create(:order, user: user, store: store, currency: currency) }let(:product) { create(:product, stores: [store]) }- let(:variant) { create(:variant, product: product, prices: [create(:price, currency: store.default_currency)]) }+ let(:variant) { create(:variant, product: product) }before doallow_any_instance_of(Spree::Api::V2::Storefront::CartController).to receive(:current_store).and_return(store)diff --git a/api/spec/serializers/spree/api/v2/platform/price_serializer_spec.rb b/api/spec/serializers/spree/api/v2/platform/price_serializer_spec.rbindex fd6e1e463d..eea579821c 100644--- a/api/spec/serializers/spree/api/v2/platform/price_serializer_spec.rb+++ b/api/spec/serializers/spree/api/v2/platform/price_serializer_spec.rb@@ -5,7 +5,9 @@ describe Spree::Api::V2::Platform::PriceSerializer dosubject { described_class.new(resource, params: serializer_params).serializable_hash }- let(:resource) { create(:price) }+ let(:currency) { 'USD' }+ let(:variant) { create(:variant) }+ let(:resource) { variant.price_in(currency) }let(:type) { :price }it dodiff --git a/core/app/models/spree/price_list.rb b/core/app/models/spree/price_list.rbindex c46d2c128b..efc919e098 100644--- a/core/app/models/spree/price_list.rb+++ b/core/app/models/spree/price_list.rb@@ -117,6 +117,7 @@ module Spreeend# Adds products to the price list+ # Creates placeholder prices (with nil amount) for all variants and currencies# @param product_ids [Array<String>] of product ids# @return [void]def add_products(product_ids)@@ -124,16 +125,20 @@ module Spreecurrencies = store.supported_currencies_list.map(&:iso_code)variant_ids = Spree::Variant.eligible.where(product_id: product_ids).distinct.pluck(:id)- now = Time.current+ return if variant_ids.empty?++ # Get existing variant_id/currency combinations to avoid duplicates+ existing = prices.where(variant_id: variant_ids)+ .pluck(:variant_id, :currency)+ .to_set- prices_to_insert = []+ now = Time.current- currencies.each do |currency|- existing_variant_ids = prices.where(currency: currency).pluck(:variant_id)- new_variant_ids = variant_ids - existing_variant_ids+ prices_to_insert = variant_ids.flat_map do |variant_id|+ currencies.filter_map do |currency|+ next if existing.include?([variant_id, currency])- new_variant_ids.each do |variant_id|- prices_to_insert << {+ {variant_id: variant_id,currency: currency,amount: nil,@@ -144,19 +149,23 @@ module Spreeendend- if prices_to_insert.any?- Spree::Price.insert_all(prices_to_insert)- touch_variants(variant_ids)- end+ return if prices_to_insert.empty?++ # Use upsert_all with on_duplicate: :skip to handle race conditions+ Spree::Price.upsert_all(prices_to_insert, on_duplicate: :skip)+ touch_variants(variant_ids)end# Removes products from the price list+ # Hard deletes prices (not soft delete) to allow re-adding products later# @param product_ids [Array<String>] of product ids# @return [void]def remove_products(product_ids)return if product_ids.blank?variant_ids = Spree::Variant.where(product_id: product_ids).distinct.pluck(:id)+ # Use delete_all for hard delete - this bypasses acts_as_paranoid+ # which is required for the unique index to work when re-adding productsprices.where(variant_id: variant_ids).delete_alltouch_variants(variant_ids)end@@ -205,7 +214,7 @@ module Spreereturn true if records_to_upsert.empty?- opts = { update_only: [:amount, :compare_at_amount] }+ opts = { update_only: [:amount, :compare_at_amount], on_duplicate: :update }opts[:unique_by] = :id unless ActiveRecord::Base.connection.adapter_name == 'Mysql2'Spree::Price.upsert_all(records_to_upsert, **opts)diff --git a/core/db/migrate/20260112000000_fix_spree_prices_unique_indexes.rb b/core/db/migrate/20260112000000_fix_spree_prices_unique_indexes.rbnew file mode 100644index 0000000000..6288f664ba--- /dev/null+++ b/core/db/migrate/20260112000000_fix_spree_prices_unique_indexes.rb@@ -0,0 +1,33 @@+class FixSpreePricesUniqueIndexes < ActiveRecord::Migration[7.0]+ def change+ remove_index :spree_prices, name: 'index_spree_prices_on_variant_currency_price_list', if_exists: true++ if ActiveRecord::Base.connection.adapter_name == 'Mysql2'+ # MySQL doesn't support partial indexes, so we use a composite unique index+ # that includes price_list_id. NULL values are treated as distinct in MySQL unique indexes,+ # so this allows multiple base prices (price_list_id = NULL) per variant/currency+ # but only one price per variant/currency/price_list combination.+ # Keep existing index_spree_prices_on_variant_id_and_currency as-is (non-unique, for performance).+ add_index :spree_prices, [:variant_id, :currency, :price_list_id],+ name: 'index_spree_prices_on_variant_currency_price_list',+ unique: true+ else+ # PostgreSQL and SQLite support partial indexes+ remove_index :spree_prices, name: 'index_spree_prices_on_variant_id_and_currency', if_exists: true++ # Add unique index for base prices only (price_list_id IS NULL)+ # The amount IS NOT NULL condition allows placeholder prices with nil amounts+ add_index :spree_prices, [:variant_id, :currency],+ name: 'index_spree_prices_on_variant_id_and_currency',+ unique: true,+ where: 'price_list_id IS NULL AND deleted_at IS NULL AND amount IS NOT NULL'++ # Add unique index for price list prices (one price per variant/currency/price_list)+ # The amount IS NOT NULL condition allows placeholder prices with nil amounts+ add_index :spree_prices, [:variant_id, :currency, :price_list_id],+ name: 'index_spree_prices_on_variant_currency_price_list',+ unique: true,+ where: 'price_list_id IS NOT NULL AND deleted_at IS NULL AND amount IS NOT NULL'+ end+ end+enddiff --git a/core/lib/spree/testing_support/factories/price_factory.rb b/core/lib/spree/testing_support/factories/price_factory.rbindex c066897808..24fc5439d1 100644--- a/core/lib/spree/testing_support/factories/price_factory.rb+++ b/core/lib/spree/testing_support/factories/price_factory.rb@@ -3,5 +3,9 @@ FactoryBot.define dovariantamount { 19.99 }currency { 'USD' }++ factory :price_eur do+ currency { 'EUR' }+ endendenddiff --git a/core/spec/models/spree/price_list_spec.rb b/core/spec/models/spree/price_list_spec.rbindex 694ded71b4..b5ac11c6a2 100644--- a/core/spec/models/spree/price_list_spec.rb+++ b/core/spec/models/spree/price_list_spec.rb@@ -237,6 +237,57 @@ describe Spree::PriceList, type: :model do}.to change { price_list.prices.count }.by(eligible_count * 3) # variants * 3 currenciesendend++ context 'with non-existent product IDs' do+ it 'handles gracefully without error' do+ expect {+ price_list.add_products([999_999, 999_998])+ }.not_to change { price_list.prices.count }+ end++ it 'creates prices only for existing products' do+ expect {+ price_list.add_products([product1.id, 999_999])+ }.to change { price_list.prices.count }.by(3) # only product1 * 3 currencies+ end+ end++ context 'when price already has amount set' do+ before do+ price_list.prices.create!(variant: product1.master, currency: 'USD', amount: 49.99)+ end++ it 'does not overwrite existing price with amount' do+ price_list.add_products([product1.id])++ price = price_list.prices.find_by(variant_id: product1.master.id, currency: 'USD')+ expect(price.amount).to eq(49.99)+ end++ it 'only creates prices for missing currencies' do+ expect {+ price_list.add_products([product1.id])+ }.to change { price_list.prices.count }.by(2) # Only EUR and GBP+ end+ end++ context 'with deleted variants' do+ let(:product_with_deleted) { create(:product, stores: [store]) }+ let!(:active_variant) { create(:variant, product: product_with_deleted) }+ let!(:deleted_variant) { create(:variant, product: product_with_deleted) }++ before { deleted_variant.destroy }++ it 'only creates prices for non-deleted variants' do+ eligible_count = Spree::Variant.eligible.where(product_id: product_with_deleted.id).count++ expect {+ price_list.add_products([product_with_deleted.id])+ }.to change { price_list.prices.count }.by(eligible_count * 3)++ expect(price_list.prices.where(variant_id: deleted_variant.id)).to be_empty+ end+ endenddescribe '#remove_products' do@@ -290,6 +341,37 @@ describe Spree::PriceList, type: :model doprice_list.remove_products([product1.id])}.to have_enqueued_job(Spree::Variants::TouchJob).with([product1.master.id])end++ context 'when re-adding a previously removed product' do+ it 'allows re-adding a product with empty prices' do+ # Add product, then remove it+ price_list.add_products([product1.id])+ price_list.remove_products([product1.id])++ # Re-add the same product - this should not raise a unique constraint error+ expect {+ price_list.add_products([product1.id])+ }.to change { price_list.prices.count }.by(3) # 1 product * 3 currencies+ end++ it 'allows re-adding a product that had prices with amounts set' do+ # Add product and set some prices+ price_list.add_products([product1.id])+ price = price_list.prices.find_by(variant_id: product1.master.id, currency: 'USD')+ price.update!(amount: 19.99)++ # Remove product+ price_list.remove_products([product1.id])++ # Re-add the same product+ expect {+ price_list.add_products([product1.id])+ }.to change { price_list.prices.count }.by(3)++ # New prices should have nil amounts+ expect(price_list.prices.where(variant_id: product1.master.id).pluck(:amount).uniq).to eq([nil])+ end+ endenddescribe '#bulk_update_prices' dodiff --git a/core/spec/models/spree/price_spec.rb b/core/spec/models/spree/price_spec.rbindex 60449e37ef..a37231319a 100644--- a/core/spec/models/spree/price_spec.rb+++ b/core/spec/models/spree/price_spec.rb@@ -1,7 +1,7 @@require 'spec_helper'describe Spree::Price, type: :model do- it_behaves_like 'lifecycle events'+ it_behaves_like 'lifecycle events', factory: :price_eurdescribe 'Callbacks' docontext 'when compare_at_amount is equal to amount' dodiff --git a/core/spec/models/spree/product_spec.rb b/core/spec/models/spree/product_spec.rbindex 83b8079410..0f69046276 100644--- a/core/spec/models/spree/product_spec.rb+++ b/core/spec/models/spree/product_spec.rb@@ -1395,10 +1395,10 @@ describe Spree::Product, type: :model do# Both have 2 orders, but product_2 has higher totalexpect(products.first.name).to eq('Product 2')expect(products.second.name).to eq('Product 1')-+product_1_result = products.find { |p| p.id == product_1.id }product_2_result = products.find { |p| p.id == product_2.id }-+expect(product_2_result.completed_orders_total).to be > product_1_result.completed_orders_totalendend@@ -1424,7 +1424,7 @@ describe Spree::Product, type: :model doit 'calculates total correctly with price * quantity for each line item' doproducts = described_class.where(id: test_product_ids).by_best_selling-+product_1_result = products.find { |p| p.id == product_1.id }product_2_result = products.find { |p| p.id == product_2.id }@@ -1436,7 +1436,7 @@ describe Spree::Product, type: :model do# Product 2 should have total of $200 (100*2)expect(product_1_result.completed_orders_total).to eq(250)expect(product_2_result.completed_orders_total).to eq(200)-+# Product 1 should be ranked higher due to higher totalexpect(products.first.name).to eq('Product 1')end@@ -1466,7 +1466,7 @@ describe Spree::Product, type: :model doit 'prioritizes order count over total when ranking' doproducts = described_class.where(id: test_product_ids).by_best_selling-+product_1_result = products.find { |p| p.id == product_1.id }product_2_result = products.find { |p| p.id == product_2.id }@@ -1477,7 +1477,7 @@ describe Spree::Product, type: :model do# Verify totalsexpect(product_1_result.completed_orders_total).to eq(250)expect(product_2_result.completed_orders_total).to eq(400)-+# Product 1 should rank first because it has more orders (2 vs 1)# even though Product 2 has a higher total ($400 vs $250)expect(products.first.name).to eq('Product 1')@@ -1552,12 +1552,10 @@ describe Spree::Product, type: :model dolet!(:future_product) { create(:product, available_on: 1.day.from_now, status: 'active', stores: [store]) }let!(:active_product) { create(:product, available_on: 1.day.ago, status: 'active', stores: [store]) }- let!(:prices) do- [- create(:price, variant: active_product.default_variant, currency: 'USD', amount: 10),- create(:price, variant: future_product.default_variant, currency: 'USD', amount: 10),- create(:price, variant: discontinued_product.default_variant, currency: 'USD', amount: 10)- ]+ before do+ active_product.default_variant.set_price('USD', 10)+ future_product.default_variant.set_price('USD', 10)+ discontinued_product.default_variant.set_price('USD', 10)endcontext 'when available_on is specified' do@@ -1588,12 +1586,12 @@ describe Spree::Product, type: :model dolet!(:active_product_4) { create(:product, status: 'active', stores: [store]) }before do- active_product_2.prices_including_master.where(currency: 'USD').delete_all- active_product_3.prices_including_master.where(currency: 'USD').delete_all- active_product_4.prices_including_master.where(currency: 'USD').delete_all-- active_product_2.default_variant.prices.create(currency: 'USD', amount: 10)- active_product_3.default_variant.prices.create(currency: 'PLN', amount: 10)+ active_product_2.default_variant.set_price('USD', 10)+ # Remove USD price and set only PLN for active_product_3+ active_product_3.default_variant.prices.delete_all+ active_product_3.default_variant.set_price('PLN', 10)+ # Remove USD price from active_product_4 (no price at all)+ active_product_4.default_variant.prices.delete_allendit 'only returns products with prices in the specified currency' do@@ -1608,13 +1606,17 @@ describe Spree::Product, type: :model doSpree::Config.show_products_without_price = trueend- let(:active_product_2) { create(:product, status: 'active', stores: [store]) }- let(:active_product_3) { create(:product, status: 'active', stores: [store]) }- let(:active_product_4) { create(:product, status: 'active', stores: [store]) }+ let!(:active_product_2) { create(:product, status: 'active', stores: [store]) }+ let!(:active_product_3) { create(:product, status: 'active', stores: [store]) }+ let!(:active_product_4) { create(:product, status: 'active', stores: [store]) }before do- active_product_2.default_variant.prices.create(currency: 'USD', amount: 10)- active_product_3.default_variant.prices.create(currency: 'PLN', amount: 10)+ active_product_2.default_variant.set_price('USD', 10)+ # Remove USD price and set only PLN for active_product_3+ active_product_3.default_variant.prices.delete_all+ active_product_3.default_variant.set_price('PLN', 10)+ # Remove USD price from active_product_4 (no price at all)+ active_product_4.default_variant.prices.delete_allendit 'returns products regardless of price' dodiff --git a/core/spec/models/spree/variant_spec.rb b/core/spec/models/spree/variant_spec.rbindex af0efbc030..80d872a8ce 100644--- a/core/spec/models/spree/variant_spec.rb+++ b/core/spec/models/spree/variant_spec.rb@@ -347,15 +347,6 @@ describe Spree::Variant, type: :model doendend- context 'when multiple prices for same currency present' do- let!(:price_1) { create(:price, currency: currency, variant: variant) }- let!(:price_2) { create(:price, currency: currency, variant: variant) }-- it 'does not duplicate variant' do- expect(Spree::Variant.for_currency_and_available_price_amount(currency)).to eq([variant])- end- end-context 'when currency parameter is nil' dolet!(:price_1) { create(:price, currency: currency, variant: variant, amount: 10) }diff --git a/core/spec/services/spree/products/duplicator_spec.rb b/core/spec/services/spree/products/duplicator_spec.rbindex 4db3be80a5..abf19b6d2a 100644--- a/core/spec/services/spree/products/duplicator_spec.rb+++ b/core/spec/services/spree/products/duplicator_spec.rb@@ -92,11 +92,8 @@ RSpec.describe Spree::Products::Duplicator dolet(:new_product) { duplicate.value }before do- product.master.prices.destroy_all- product.master.prices = [- create(:price, amount: 10.99, compare_at_amount: 11.99, currency: 'USD'),- create(:price, amount: 8.99, compare_at_amount: 9.99, currency: 'GBP')- ]+ product.master.set_price('USD', 10.99, 11.99)+ product.master.set_price('GBP', 8.99, 9.99)endit 'clones prices' do@@ -204,17 +201,11 @@ RSpec.describe Spree::Products::Duplicator dolet(:new_product) { duplicate.value }before do- variant1.prices.destroy_all- variant1.prices = [- create(:price, amount: 14.99, compare_at_amount: 15.99, currency: 'USD'),- create(:price, amount: 12.99, compare_at_amount: 13.99, currency: 'GBP')- ]-- variant2.prices.destroy_all- variant2.prices = [- create(:price, amount: 15.99, compare_at_amount: 16.99, currency: 'USD'),- create(:price, amount: 13.99, compare_at_amount: 14.99, currency: 'GBP')- ]+ variant1.set_price('USD', 14.99, 15.99)+ variant1.set_price('GBP', 12.99, 13.99)++ variant2.set_price('USD', 15.99, 16.99)+ variant2.set_price('GBP', 13.99, 14.99)endit 'clones prices' dodiff --git a/core/spec/services/spree/products/prepare_nested_attributes_spec.rb b/core/spec/services/spree/products/prepare_nested_attributes_spec.rbindex bd9d4aed6f..61c17a0ac4 100644--- a/core/spec/services/spree/products/prepare_nested_attributes_spec.rb+++ b/core/spec/services/spree/products/prepare_nested_attributes_spec.rb@@ -233,7 +233,6 @@ RSpec.describe Spree::Products::PrepareNestedAttributes docontext 'when user can update prices' docontext 'when price amount is blank' do- let(:price) { create(:price, variant: variant) }let(:raw_params) do{variants_attributes: {@@ -241,7 +240,7 @@ RSpec.describe Spree::Products::PrepareNestedAttributes doid: variant.id,prices_attributes: {'0' => {- id: price.id,+ id: variant.price_in('USD').id,amount: ''}}diff --git a/emails/spec/mailers/spree/order_mailer_spec.rb b/emails/spec/mailers/spree/order_mailer_spec.rbindex bd1d8599ff..2c23737bf1 100644--- a/emails/spec/mailers/spree/order_mailer_spec.rb+++ b/emails/spec/mailers/spree/order_mailer_spec.rb@@ -12,10 +12,8 @@ describe Spree::OrderMailer, type: :mailer doorder = create(:completed_order_with_totals, email: '[email protected]', store: store)product = create(:product, name: %{The "BEST" product})variant = create(:variant, product: product)- price = create(:price, variant: variant, amount: 5.00)line_item = create(:line_item, variant: variant, order: order, quantity: 1, price: 4.99)allow(product).to receive_messages(default_variant: variant)- allow(variant).to receive_messages(default_price: price)allow(order).to receive_messages(line_items: [line_item])allow(order).to receive_messages(store: store)order@@ -25,11 +23,9 @@ describe Spree::OrderMailer, type: :mailer doorder = create(:completed_order_with_totals, email: '[email protected]', store: second_store)product = create(:product, name: %{The "BESTEST" product})variant = create(:variant, product: product)- price = create(:price, variant: variant, amount: 15.00)store = second_storeline_item = create(:line_item, variant: variant, order: order, quantity: 1, price: 4.99)allow(product).to receive_messages(default_variant: variant)- allow(variant).to receive_messages(default_price: price)allow(order).to receive_messages(line_items: [line_item])allow(order).to receive_messages(store: store)order