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
Move touching variants in a background queue, save prices in bulk
Damian Legawiec244c304ac7c9
diff --git a/admin/app/controllers/spree/admin/price_lists_controller.rb b/admin/app/controllers/spree/admin/price_lists_controller.rbindex 228762bd62..307eaa8fc1 100644--- a/admin/app/controllers/spree/admin/price_lists_controller.rb+++ b/admin/app/controllers/spree/admin/price_lists_controller.rb@@ -26,7 +26,7 @@ module Spreedef permitted_resource_paramsparams.require(:price_list).permit(permitted_price_list_attributes,- prices_attributes: [:id, :variant_id, :currency, :amount, :compare_at_amount, :_destroy]+ prices_attributes: [:id, :variant_id, :currency, :amount, :compare_at_amount])endenddiff --git a/admin/app/views/spree/admin/price_lists/_table_header.html.erb b/admin/app/views/spree/admin/price_lists/_table_header.html.erbindex 27dc1e3a9a..979bc51cb6 100644--- a/admin/app/views/spree/admin/price_lists/_table_header.html.erb+++ b/admin/app/views/spree/admin/price_lists/_table_header.html.erb@@ -1,4 +1,5 @@<tr>+ <th class="no-border handel-head"></th><th scope="col"><%= sort_link @search, :name, Spree.t(:name) %></th><th scope="col"><%= Spree.t(:status) %></th><th scope="col"><%= Spree.t(:starts_at) %></th>diff --git a/admin/app/views/spree/admin/price_lists/_table_row.html.erb b/admin/app/views/spree/admin/price_lists/_table_row.html.erbindex 23226fa1e5..8f5452b2d5 100644--- a/admin/app/views/spree/admin/price_lists/_table_row.html.erb+++ b/admin/app/views/spree/admin/price_lists/_table_row.html.erb@@ -1,4 +1,7 @@-<tr id="<%= spree_dom_id price_list %>" data-controller="row-link">+<tr id="<%= spree_dom_id price_list %>" data-controller="row-link" data-sortable-update-url="<%= spree.admin_price_list_path(price_list) %>">+ <td class="w-5 move-handle text-center">+ <%= icon('grip-vertical', class: 'rounded-md hover:bg-gray-100 p-2') %>+ </td><td class="w-30 p-0"><%= link_to price_list.name, spree.admin_price_list_path(price_list), class: 'font-bold block py-2 px-4 w-full h-full', data: { row_link_target: :link, turbo_frame: '_top' } %></td>diff --git a/admin/app/views/spree/admin/price_lists/update.turbo_stream.erb b/admin/app/views/spree/admin/price_lists/update.turbo_stream.erbnew file mode 100644index 0000000000..d9fb79328e--- /dev/null+++ b/admin/app/views/spree/admin/price_lists/update.turbo_stream.erb@@ -0,0 +1 @@+<%= turbo_render_alerts %>\ No newline at end of filediff --git a/admin/spec/controllers/spree/admin/price_lists_controller_spec.rb b/admin/spec/controllers/spree/admin/price_lists_controller_spec.rbindex a813087df2..1ed54ab7c5 100644--- a/admin/spec/controllers/spree/admin/price_lists_controller_spec.rb+++ b/admin/spec/controllers/spree/admin/price_lists_controller_spec.rb@@ -97,6 +97,12 @@ RSpec.describe Spree::Admin::PriceListsController, type: :controller doexpect(price.compare_at_amount).to eq(35.00)end+ it 'enqueues a job to touch affected variants' do+ expect {+ update_price_list+ }.to have_enqueued_job(Spree::Variants::TouchJob).with([variant.id])+ end+context 'when updating multiple prices' dolet(:product2) { create(:product, stores: [store]) }let(:variant2) { product2.master }diff --git a/core/app/jobs/spree/variants/touch_job.rb b/core/app/jobs/spree/variants/touch_job.rbnew file mode 100644index 0000000000..05ea2af951--- /dev/null+++ b/core/app/jobs/spree/variants/touch_job.rb@@ -0,0 +1,9 @@+module Spree+ module Variants+ class TouchJob < Spree::BaseJob+ def perform(variant_ids)+ Spree::Variant.where(id: variant_ids).find_each(&:touch)+ end+ end+ end+enddiff --git a/core/app/models/spree/price_list.rb b/core/app/models/spree/price_list.rbindex 1360a48269..5e1b6ce789 100644--- a/core/app/models/spree/price_list.rb+++ b/core/app/models/spree/price_list.rb@@ -15,9 +15,21 @@ module Spreehas_many :products, -> { where(spree_prices: { deleted_at: nil }) }, through: :variants, source: :productalias price_list_products products- accepts_nested_attributes_for :prices,- allow_destroy: true,- reject_if: ->(attrs) { attrs['amount'].blank? && attrs['id'].blank? }+ # Override default nested attributes to use bulk_update_prices for performance+ attr_reader :prices_attributes++ def prices_attributes=(attributes)+ @prices_attributes = attributes.values+ end++ after_update :process_bulk_prices_update++ def process_bulk_prices_update+ return if @prices_attributes.blank?++ bulk_update_prices(@prices_attributes)+ @prices_attributes = nil+ endvalidates :name, :store, presence: truevalidates :match_policy, presence: true, inclusion: { in: MATCH_POLICIES }@@ -32,7 +44,7 @@ module Spree.where('ends_at IS NULL OR ends_at >= ?', current_time)}- state_machine :status, initial: :inactive do+ state_machine :status doevent :activate dotransition to: :activeend@@ -121,10 +133,68 @@ module Spreetouch_variants(variant_ids)end+ # Bulk update prices using upsert_all for performance+ # @param prices_attributes [Array<Hash>] array of price attributes with :id, :amount, :compare_at_amount+ # @return [Boolean] true if successful+ def bulk_update_prices(prices_attributes)+ return true if prices_attributes.blank?++ now = Time.current+ records_to_upsert = []+ variant_ids = Set.new++ # Get current values for comparison+ price_ids = prices_attributes.map { |a| a[:id] || a['id'] }.compact.map(&:to_i)+ current_values = prices.where(id: price_ids).pluck(:id, :amount, :compare_at_amount).to_h { |id, amount, compare_at| [id, { amount: amount, compare_at_amount: compare_at }] }++ prices_attributes.each do |attrs|+ attrs = (attrs.respond_to?(:to_unsafe_h) ? attrs.to_unsafe_h : attrs.to_h).with_indifferent_access+ next if attrs[:id].blank?++ price_id = attrs[:id].to_i+ current = current_values[price_id] || {}++ # Parse amounts using LocalizedNumber for proper decimal handling+ amount = attrs[:amount].present? ? Spree::LocalizedNumber.parse(attrs[:amount]) : nil+ compare_at_amount = attrs[:compare_at_amount].present? ? Spree::LocalizedNumber.parse(attrs[:compare_at_amount]) : nil++ # Clear compare_at_amount if it equals amount+ compare_at_amount = nil if compare_at_amount == amount++ # Skip if nothing changed+ next if amount == current[:amount] && compare_at_amount == current[:compare_at_amount]++ records_to_upsert << {+ id: price_id,+ variant_id: attrs[:variant_id].to_i,+ currency: attrs[:currency],+ amount: amount,+ compare_at_amount: compare_at_amount,+ price_list_id: id,+ updated_at: now+ }++ variant_ids << attrs[:variant_id].to_i+ end++ return true if records_to_upsert.empty?++ Spree::Price.upsert_all(+ records_to_upsert,+ unique_by: :id,+ update_only: [:amount, :compare_at_amount, :updated_at]+ )++ touch_variants(variant_ids.to_a)+ true+ end+privatedef touch_variants(variant_ids)- Spree::Variant.where(id: variant_ids).each(&:touch)+ return if variant_ids.blank?++ Spree::Variants::TouchJob.perform_later(variant_ids)enddef starts_at_before_ends_atdiff --git a/core/lib/spree/testing_support/factories/price_list_factory.rb b/core/lib/spree/testing_support/factories/price_list_factory.rbindex a9d0d63926..2053c4155d 100644--- a/core/lib/spree/testing_support/factories/price_list_factory.rb+++ b/core/lib/spree/testing_support/factories/price_list_factory.rb@@ -3,17 +3,18 @@ FactoryBot.define dosequence(:name) { |n| "Price List #{n}" }store { Spree::Store.default || create(:store) }match_policy { 'all' }+ status { 'active' }trait :active do- after(:create) do |price_list|- price_list.activate!- end+ status { 'active' }+ end++ trait :inactive do+ status { 'inactive' }endtrait :scheduled do- after(:create) do |price_list|- price_list.schedule!- end+ status { 'scheduled' }endtrait :with_date_range dodiff --git a/core/spec/jobs/spree/variants/touch_job_spec.rb b/core/spec/jobs/spree/variants/touch_job_spec.rbnew file mode 100644index 0000000000..d52932bc97--- /dev/null+++ b/core/spec/jobs/spree/variants/touch_job_spec.rb@@ -0,0 +1,25 @@+require 'spec_helper'++RSpec.describe Spree::Variants::TouchJob, type: :job do+ let(:variant1) { create(:variant) }+ let(:variant2) { create(:variant) }++ before do+ variant1.update_column(:updated_at, 1.day.ago)+ variant2.update_column(:updated_at, 1.day.ago)+ end++ it 'touches all variants with the given IDs' do+ original_updated_at1 = variant1.reload.updated_at+ original_updated_at2 = variant2.reload.updated_at++ described_class.perform_now([variant1.id, variant2.id])++ expect(variant1.reload.updated_at).to be > original_updated_at1+ expect(variant2.reload.updated_at).to be > original_updated_at2+ end++ it 'handles empty array' do+ expect { described_class.perform_now([]) }.not_to raise_error+ end+enddiff --git a/core/spec/models/spree/price_list_spec.rb b/core/spec/models/spree/price_list_spec.rbindex 20a36d1334..2825f0287a 100644--- a/core/spec/models/spree/price_list_spec.rb+++ b/core/spec/models/spree/price_list_spec.rb@@ -15,8 +15,8 @@ describe Spree::PriceList, type: :model dodescribe 'state_machine' dolet(:price_list) { create(:price_list) }- it 'has initial status of inactive' do- expect(price_list.status).to eq('inactive')+ it 'has initial status of active' do+ expect(price_list.status).to eq('active')enddescribe '#activate' do@@ -27,8 +27,6 @@ describe Spree::PriceList, type: :model doenddescribe '#deactivate' do- before { price_list.activate }-it 'transitions to inactive' doprice_list.deactivateexpect(price_list.status).to eq('inactive')@@ -46,7 +44,7 @@ describe Spree::PriceList, type: :model dodescribe 'scopes' dolet(:store) { create(:store) }let!(:active_price_list) { create(:price_list, :active, store: store) }- let!(:inactive_price_list) { create(:price_list, store: store) }+ let!(:inactive_price_list) { create(:price_list, :inactive, store: store) }let!(:scheduled_price_list) { create(:price_list, :scheduled, store: store) }describe '.with_status(:active)' do@@ -170,7 +168,7 @@ describe Spree::PriceList, type: :model doendit 'returns false when status is not active' do- price_list = create(:price_list)+ price_list = create(:price_list, :inactive)expect(price_list.active?).to be falseendend@@ -208,6 +206,12 @@ describe Spree::PriceList, type: :model do}.to change { price_list.prices.count }.by(2) # Only EUR and GBP, not USDend+ it 'enqueues a job to touch affected variants' do+ expect {+ price_list.add_products([product1.id])+ }.to have_enqueued_job(Spree::Variants::TouchJob).with([product1.master.id])+ end+it 'handles empty product_ids' doexpect {price_list.add_products([])@@ -280,5 +284,116 @@ describe Spree::PriceList, type: :model doprice_list.remove_products([product1.id, product2.id])}.to change { price_list.prices.count }.by(-6) # 2 products * 3 currenciesend++ it 'enqueues a job to touch affected variants' do+ expect {+ price_list.remove_products([product1.id])+ }.to have_enqueued_job(Spree::Variants::TouchJob).with([product1.master.id])+ end+ end++ describe '#bulk_update_prices' do+ let(:store) { create(:store, supported_currencies: 'USD,EUR') }+ let(:price_list) { create(:price_list, store: store) }+ let(:product) { create(:product, stores: [store]) }+ let!(:price1) { create(:price, variant: product.master, price_list: price_list, currency: 'USD', amount: nil) }+ let!(:price2) { create(:price, variant: product.master, price_list: price_list, currency: 'EUR', amount: nil) }++ it 'updates prices in bulk using upsert_all' do+ prices_attributes = [+ { id: price1.id, variant_id: price1.variant_id, currency: 'USD', amount: '19.99', compare_at_amount: '29.99' },+ { id: price2.id, variant_id: price2.variant_id, currency: 'EUR', amount: '17.99', compare_at_amount: '' }+ ]++ price_list.bulk_update_prices(prices_attributes)++ price1.reload+ price2.reload+ expect(price1.amount).to eq(BigDecimal('19.99'))+ expect(price1.compare_at_amount).to eq(BigDecimal('29.99'))+ expect(price2.amount).to eq(BigDecimal('17.99'))+ expect(price2.compare_at_amount).to be_nil+ end++ it 'clears compare_at_amount when it equals amount' do+ prices_attributes = [+ { id: price1.id, variant_id: price1.variant_id, currency: 'USD', amount: '19.99', compare_at_amount: '19.99' }+ ]++ price_list.bulk_update_prices(prices_attributes)++ price1.reload+ expect(price1.amount).to eq(BigDecimal('19.99'))+ expect(price1.compare_at_amount).to be_nil+ end++ it 'clears amount when user removes existing value' do+ price1.update!(amount: BigDecimal('10.00'))++ prices_attributes = [+ { id: price1.id, variant_id: price1.variant_id, currency: 'USD', amount: '', compare_at_amount: '' }+ ]++ price_list.bulk_update_prices(prices_attributes)++ price1.reload+ expect(price1.amount).to be_nil # cleared+ end++ it 'skips prices where nothing changed' do+ price1.update!(amount: BigDecimal('19.99'), compare_at_amount: BigDecimal('29.99'))++ prices_attributes = [+ { id: price1.id, variant_id: price1.variant_id, currency: 'USD', amount: '19.99', compare_at_amount: '29.99' }+ ]++ # Should not include this in upsert (no actual change)+ expect(Spree::Price).not_to receive(:upsert_all)++ price_list.bulk_update_prices(prices_attributes)+ end++ it 'updates when only compare_at_amount changed' do+ price1.update!(amount: BigDecimal('19.99'), compare_at_amount: nil)++ prices_attributes = [+ { id: price1.id, variant_id: price1.variant_id, currency: 'USD', amount: '19.99', compare_at_amount: '29.99' }+ ]++ price_list.bulk_update_prices(prices_attributes)++ price1.reload+ expect(price1.amount).to eq(BigDecimal('19.99'))+ expect(price1.compare_at_amount).to eq(BigDecimal('29.99'))+ end++ it 'enqueues a job to touch affected variants' do+ prices_attributes = [+ { id: price1.id, variant_id: price1.variant_id, currency: 'USD', amount: '19.99', compare_at_amount: '' }+ ]++ expect {+ price_list.bulk_update_prices(prices_attributes)+ }.to have_enqueued_job(Spree::Variants::TouchJob).with([price1.variant_id])+ end++ it 'returns true for empty attributes' do+ expect(price_list.bulk_update_prices([])).to be true+ expect(price_list.bulk_update_prices(nil)).to be true+ end++ it 'skips entries without id' do+ prices_attributes = [+ { id: price1.id, variant_id: price1.variant_id, currency: 'USD', amount: '19.99' },+ { variant_id: price2.variant_id, currency: 'EUR', amount: '17.99' } # no id+ ]++ price_list.bulk_update_prices(prices_attributes)++ price1.reload+ price2.reload+ expect(price1.amount).to eq(BigDecimal('19.99'))+ expect(price2.amount).to be_nil # not updated+ endendend