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.

Fix: Run installation-wide sweep jobs in the store that owns each record (#14749)

Damian Legawiec0c4f6b748bf4
diff --git a/spree/core/app/jobs/spree/base_job.rb b/spree/core/app/jobs/spree/base_job.rb
index 10caa5fb6a..d5664bff7f 100644
--- a/spree/core/app/jobs/spree/base_job.rb
+++ b/spree/core/app/jobs/spree/base_job.rb
@@ -19,5 +19,26 @@ module Spree
retry_on ActiveRecord::RecordNotFound, wait: 2.seconds, attempts: 3
discard_on ActiveJob::DeserializationError
+
+ private
+
+ # Runs the block once per store owning a record in +records+, inside that
+ # store and with +records+ narrowed to it.
+ #
+ # For installation-wide sweeps. A job has no store of its own, so the work
+ # done for a record — its emails, events, store settings — would otherwise
+ # run in the default store whichever store the record belongs to.
+ # Narrowing the relation keeps each query store-scoped once the store
+ # context arms Spree::StoreScopeGuard.
+ #
+ # @param records [ActiveRecord::Relation] records of a store-owned model
+ # @yieldparam store_records [ActiveRecord::Relation] +records+ of one store
+ # @return [void]
+ def each_store_of(records)
+ # Deleted stores too — their records were swept before this was per store.
+ Spree::Store.with_deleted.where(id: records.select(:store_id)).find_each do |store|
+ Spree::Current.with_store(store) { yield records.where(store_id: store.id) }
+ end
+ end
end
end
diff --git a/spree/core/app/jobs/spree/carts/reap_expired_job.rb b/spree/core/app/jobs/spree/carts/reap_expired_job.rb
index b69ec2276a..65c7f96563 100644
--- a/spree/core/app/jobs/spree/carts/reap_expired_job.rb
+++ b/spree/core/app/jobs/spree/carts/reap_expired_job.rb
@@ -20,7 +20,7 @@ module Spree
def base_scope
Spree::Cart.incomplete.
where.not(id: Spree::PaymentSession.where(status: %w[pending processing]).select(:cart_id)).
- where.not(id: Spree::Payment.where.not(state: Spree::Payment::INVALID_STATES).where.not(cart_id: nil).select(:cart_id))
+ where.not(id: Spree::Payment.valid.where.not(cart_id: nil).select(:cart_id))
end
def empty_scope
@@ -36,7 +36,7 @@ module Spree
end
def reap(scope)
- scope.in_batches(of: 200, &:destroy_all)
+ each_store_of(scope) { |carts| carts.in_batches(of: 200, &:destroy_all) }
end
end
end
diff --git a/spree/core/app/jobs/spree/collections/regenerate_time_based_job.rb b/spree/core/app/jobs/spree/collections/regenerate_time_based_job.rb
index ef999789b1..3a89c8fd7e 100644
--- a/spree/core/app/jobs/spree/collections/regenerate_time_based_job.rb
+++ b/spree/core/app/jobs/spree/collections/regenerate_time_based_job.rb
@@ -9,9 +9,12 @@ module Spree
def perform
types = Rails.application.config.spree.time_based_collection_rules.map(&:to_s)
- Spree::Collection.automatic.
- where(id: Spree::CollectionRule.where(type: types).select(:collection_id)).
- find_each { |collection| Spree::Collections::RegenerateProducts.call(collection: collection) }
+ time_based = Spree::Collection.automatic.
+ where(id: Spree::CollectionRule.where(type: types).select(:collection_id))
+
+ each_store_of(time_based) do |collections|
+ collections.find_each { |collection| Spree::Collections::RegenerateProducts.call(collection: collection) }
+ end
end
end
end
diff --git a/spree/core/app/jobs/spree/orders/finalize_stale_drafts_job.rb b/spree/core/app/jobs/spree/orders/finalize_stale_drafts_job.rb
index 4bc7a86781..b53a4a252e 100644
--- a/spree/core/app/jobs/spree/orders/finalize_stale_drafts_job.rb
+++ b/spree/core/app/jobs/spree/orders/finalize_stale_drafts_job.rb
@@ -10,11 +10,13 @@ module Spree
STALE_AFTER = 10.minutes
def perform
- Spree::Order.drafts.
- where.not(cart_id: nil).
- where(completed_at: nil).
- where(created_at: ...STALE_AFTER.ago).
- find_each do |order|
+ stale_drafts = Spree::Order.drafts.
+ where.not(cart_id: nil).
+ where(completed_at: nil).
+ where(created_at: ...STALE_AFTER.ago)
+
+ each_store_of(stale_drafts) do |orders|
+ orders.find_each do |order|
cart = order.cart
next if cart.nil? || cart.completed?
@@ -23,6 +25,7 @@ module Spree
rescue StandardError => e
Rails.logger.error("[Spree] Completion recovery raised for order #{order.number}: #{e.message}")
end
+ end
end
end
end
diff --git a/spree/core/app/jobs/spree/seller_payouts/sweep_seller_job.rb b/spree/core/app/jobs/spree/seller_payouts/sweep_seller_job.rb
index f430186658..46a4abda85 100644
--- a/spree/core/app/jobs/spree/seller_payouts/sweep_seller_job.rb
+++ b/spree/core/app/jobs/spree/seller_payouts/sweep_seller_job.rb
@@ -17,6 +17,8 @@ module Spree
def perform(seller_id)
seller = Spree::Seller.find_by(id: seller_id)
return if seller.nil?
+
+ Spree::Current.store = seller.store
return if seller.resolved_payouts_schedule_interval == 'manual'
currencies_owed(seller).each do |currency|
diff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rb
index 61f768fd75..9456b66f0b 100644
--- a/spree/core/app/models/spree/current.rb
+++ b/spree/core/app/models/spree/current.rb
@@ -38,6 +38,29 @@ module Spree
super || Spree::Store.default
end
+ # Runs the block in +store+ from a clean context: nothing a previous store
+ # resolved (channel, market, currency, integrations, pricing) carries in,
+ # and nothing resolved inside leaks out. For work that walks several
+ # stores in one unit of work, such as an installation-wide sweep job; a
+ # request or a single-store job assigns #store once instead.
+ #
+ # The store scope guard stays armed afterwards, like any other store
+ # declaration in this unit of work.
+ #
+ # @param store [Spree::Store]
+ # @return [Object] the block's result
+ def with_store(store)
+ previous = attributes
+
+ begin
+ self.attributes = {}
+ self.store = store
+ yield
+ ensure
+ self.attributes = previous.merge(store_scope_guard_armed: store_scope_guard_armed)
+ end
+ end
+
def channel
super || (self.channel = store&.default_channel)
end
diff --git a/spree/core/spec/jobs/spree/carts/reap_expired_job_spec.rb b/spree/core/spec/jobs/spree/carts/reap_expired_job_spec.rb
new file mode 100644
index 0000000000..5876184d14
--- /dev/null
+++ b/spree/core/spec/jobs/spree/carts/reap_expired_job_spec.rb
@@ -0,0 +1,31 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Carts::ReapExpiredJob do
+ let(:store) { @default_store }
+ let(:other_store) { create(:store) }
+
+ after { Spree::Config.store_scope_guard = nil }
+
+ it 'reaps expired carts in the store that owns them' do
+ Spree::Config.store_scope_guard = 'raise'
+ carts = [store, other_store].map { |owner| create(:cart, store: owner, updated_at: 1.year.ago) }
+ reaped = []
+ allow_any_instance_of(Spree::Cart).to receive(:destroy).and_wrap_original do |original|
+ reaped << [original.receiver, Spree::Current.store]
+ original.call
+ end
+
+ described_class.perform_now
+
+ expect(reaped).to contain_exactly([carts.first, store], [carts.last, other_store])
+ expect(Spree::Cart.where(id: carts.map(&:id))).to be_empty
+ end
+
+ it 'keeps a cart that has not expired' do
+ cart = create(:cart, store: store)
+
+ described_class.perform_now
+
+ expect(Spree::Cart.exists?(cart.id)).to be(true)
+ end
+end
diff --git a/spree/core/spec/jobs/spree/collections/regenerate_time_based_job_spec.rb b/spree/core/spec/jobs/spree/collections/regenerate_time_based_job_spec.rb
index eb76c320f9..7dd1672e42 100644
--- a/spree/core/spec/jobs/spree/collections/regenerate_time_based_job_spec.rb
+++ b/spree/core/spec/jobs/spree/collections/regenerate_time_based_job_spec.rb
@@ -19,5 +19,26 @@ module Spree
expect(collection.reload.products).not_to include(product)
end
+
+ context 'when another store has a time-based collection' do
+ let(:other_store) { create(:store) }
+ let!(:other_collection) { create(:automatic_collection, store: other_store) }
+
+ before { create(:available_on_collection_rule, :is_equal_to, collection: other_collection, value: 30) }
+ after { Spree::Config.store_scope_guard = nil }
+
+ it 'regenerates each collection in the store that owns it' do
+ Spree::Config.store_scope_guard = 'raise'
+ regenerated = []
+ allow_any_instance_of(Spree::Collection).to receive(:products_matching_rules).and_wrap_original do |original|
+ regenerated << [original.receiver, Spree::Current.store]
+ original.call
+ end
+
+ described_class.perform_now
+
+ expect(regenerated).to contain_exactly([collection, store], [other_collection, other_store])
+ end
+ end
end
end
diff --git a/spree/core/spec/jobs/spree/orders/finalize_stale_drafts_job_spec.rb b/spree/core/spec/jobs/spree/orders/finalize_stale_drafts_job_spec.rb
new file mode 100644
index 0000000000..c541d08934
--- /dev/null
+++ b/spree/core/spec/jobs/spree/orders/finalize_stale_drafts_job_spec.rb
@@ -0,0 +1,37 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Orders::FinalizeStaleDraftsJob do
+ let(:store) { @default_store }
+ let(:other_store) { create(:store) }
+ let(:workflow) { Spree::Dependencies.carts_complete_workflow.constantize }
+
+ def stale_draft(store)
+ cart = create(:cart, store: store)
+ create(:order, store: store, cart: cart, status: 'draft', created_at: 1.hour.ago)
+ end
+
+ after { Spree::Config.store_scope_guard = nil }
+
+ it 'finalizes each stale draft in the store that owns it' do
+ Spree::Config.store_scope_guard = 'raise'
+ orders = [stale_draft(store), stale_draft(other_store)]
+ finalized = []
+ allow(workflow).to receive(:call) do |cart:|
+ finalized << [cart, Spree::Current.store]
+ double(failure?: false)
+ end
+
+ described_class.perform_now
+
+ expect(finalized).to contain_exactly([orders.first.cart, store], [orders.last.cart, other_store])
+ end
+
+ it 'leaves a draft that is not stale yet' do
+ stale_draft(store).update_columns(created_at: 1.minute.ago)
+ allow(workflow).to receive(:call)
+
+ described_class.perform_now
+
+ expect(workflow).not_to have_received(:call)
+ end
+end
diff --git a/spree/core/spec/jobs/spree/seller_payouts/sweep_seller_job_spec.rb b/spree/core/spec/jobs/spree/seller_payouts/sweep_seller_job_spec.rb
index fbff576d91..876b8c5711 100644
--- a/spree/core/spec/jobs/spree/seller_payouts/sweep_seller_job_spec.rb
+++ b/spree/core/spec/jobs/spree/seller_payouts/sweep_seller_job_spec.rb
@@ -16,6 +16,17 @@ RSpec.describe Spree::SellerPayouts::SweepSellerJob do
expect { described_class.perform_now(seller.id) }.to change { Spree::SellerPayout.count }.by(1)
end
+ it "settles a seller in the seller's own store" do
+ other_seller = create(:seller, :approved, store: create(:store))
+ earn(40, seller: other_seller)
+ settled_in = []
+ allow(Spree.seller_payout_sweep_workflow).to receive(:call) { settled_in << Spree::Current.store }
+
+ described_class.perform_now(other_seller.id)
+
+ expect(settled_in).to eq([other_seller.store])
+ end
+
it 'leaves a seller who has earned nothing' do
expect { described_class.perform_now(seller.id) }.not_to change { Spree::SellerPayout.count }
end
diff --git a/spree/core/spec/models/spree/current_spec.rb b/spree/core/spec/models/spree/current_spec.rb
index ea761cc948..10ec4c6b51 100644
--- a/spree/core/spec/models/spree/current_spec.rb
+++ b/spree/core/spec/models/spree/current_spec.rb
@@ -290,6 +290,29 @@ RSpec.describe Spree::Current do
end
end
+ describe '.with_store' do
+ let(:store) { create(:store, default_currency: 'GBP') }
+ let(:other_store) { create(:store, default_currency: 'PLN') }
+
+ it 'runs the block in the store and restores the previous context afterwards' do
+ described_class.store = store
+ described_class.currency = 'EUR'
+
+ inside = described_class.with_store(other_store) { [described_class.store, described_class.currency] }
+
+ expect(inside).to eq([other_store, 'PLN'])
+ expect([described_class.store, described_class.currency]).to eq([store, 'EUR'])
+ end
+
+ # A sweep walks stores one after another in the same job, so what one
+ # store resolved must not answer for the next.
+ it "does not carry one store's resolved context into the next" do
+ described_class.with_store(store) { described_class.channel }
+
+ expect(described_class.with_store(other_store) { described_class.channel }).to eq(other_store.default_channel)
+ end
+ end
+
describe '.reset' do
let(:store) { create(:store) }
let(:country) { create(:country) }