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.

Fixed refreshing in-memtory associations after saving resources in Admin API

Damian Legawiec85c51974aa3c
diff --git a/docs/plans/6.0-remove-master-variant.md b/docs/plans/6.0-remove-master-variant.md
index ce8e520ed2..3939cf58ab 100644
--- a/docs/plans/6.0-remove-master-variant.md
+++ b/docs/plans/6.0-remove-master-variant.md
@@ -251,6 +251,8 @@ This task must be **idempotent** and **reversible** (soft — we can't re-create
8. Remove `option_value_variants` presence validation
9. Update `eligible` scope (no `is_master` filter needed)
10. Update factories: product factory creates one variant instead of master
+11. Update `Product#sync_variant_state!` (called by `apply_variants` to keep the create/update response fresh). Drop the `@default_variant`/`@default_variant_id` memo-clearing — `default_variant` becomes a `belongs_to` FK, so reset the association instead. The `variant_count` re-read (`pick(:variant_count)`) stays: the counter is still maintained by an out-of-band `increment_counter` callback, so the in-memory attribute is still stale after nested-variant mutation.
+12. Remove the `save_master`/`master_updated?`/`@nested_changes`/`reset_nested_changes` cluster — it only exists to force-save the master delegate (issue #5306). Once delegations target the real `default_variant` association, ActiveRecord autosaves it and the touch-dirty flag is unnecessary.
### Phase 4: API + serializer updates
@@ -299,6 +301,7 @@ After: `product.price` → `default_variant.price` (always the same record, no b
- **Use `variants_including_master` for through-associations** (prices, stock_items, line_items) — these will become just `variants` after migration.
- **Don't add new delegations to `master`.** New delegations should go through `default_variant`.
- **New variant callbacks should not use `unless: :is_master?`.** They should apply to all variants equally.
+- **`variant_count` staleness is structural, not master-specific.** It's maintained by an out-of-band counter `increment_counter` callback, so the in-memory attribute goes stale whenever variants are mutated within a request (e.g. `apply_variants` during create/update). `Product#sync_variant_state!` re-reads it so the serialized response stays fresh; this stays necessary after master removal. Don't assume removing master removes the need to re-sync.
## Resolved Questions
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb
index fc1928e379..15178aab7e 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb
@@ -139,6 +139,26 @@ RSpec.describe Spree::Api::V3::Admin::Products::VariantsController, type: :contr
expect(response).to have_http_status(:ok)
expect(variant.reload.prices.find_by(currency: 'GBP').amount.to_f).to eq(15.99)
end
+
+ # The variant's prices are eager-loaded before serialization, so updating
+ # an EXISTING base price must be reflected in the response WITHOUT a
+ # reload. Asserts on the response body (not a DB re-read) to guard the
+ # stale-price bug.
+ it 'returns the updated price for an existing currency in the response' do
+ existing_currency = variant.prices.base_prices.first.currency
+
+ patch :update, params: {
+ product_id: product.prefixed_id,
+ id: variant.prefixed_id,
+ prices: [
+ { currency: existing_currency, amount: 42.50 }
+ ]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['price']).to be_present
+ expect(json_response['price']['amount'].to_f).to eq(42.50)
+ end
end
context 'with nested stock_items' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
index 1273c714ed..551f4e55aa 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
@@ -365,6 +365,18 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
expect(large.prices.find_by(currency: 'USD').amount.to_f).to eq(31.99)
expect(large.prices.find_by(currency: 'GBP').amount.to_f).to eq(26.99)
end
+
+ # Variants are created in an after_create callback, so the response must
+ # reflect them without a reload. Asserts on the RESPONSE BODY (not a DB
+ # re-read) — the only assertion that guards the stale-response bug.
+ it 'returns fresh variant_count and price in the create response' do
+ post :create, params: product_params, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['variant_count']).to eq(3)
+ expect(json_response['price']).to be_present
+ expect(json_response['price']['amount'].to_f).to eq(29.99)
+ end
end
context 'with invalid params' do
diff --git a/spree/core/app/models/concerns/spree/typed_associations.rb b/spree/core/app/models/concerns/spree/typed_associations.rb
index 4b416ee099..31051e5e85 100644
--- a/spree/core/app/models/concerns/spree/typed_associations.rb
+++ b/spree/core/app/models/concerns/spree/typed_associations.rb
@@ -54,7 +54,14 @@ module Spree
def reconcile_typed_association(association, rows)
collection = public_send(association)
kept_ids = rows.filter_map { |row| save_typed_association_row(collection, row) }
- collection.where.not(id: kept_ids).destroy_all if kept_ids.any? || rows.empty?
+ if kept_ids.any? || rows.empty?
+ collection.where.not(id: kept_ids).destroy_all
+ # `where.not(...).destroy_all` deletes the dropped rows from the DB but
+ # leaves them in the already-loaded association target. Reset so a
+ # same-request read (e.g. the serializer rendering `rule_ids`) reflects
+ # the removal instead of echoing ghosts.
+ collection.reset
+ end
end
def save_typed_association_row(collection, row)
diff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rb
index c496468bd8..3b3a4baeae 100644
--- a/spree/core/app/models/spree/price_list.rb
+++ b/spree/core/app/models/spree/price_list.rb
@@ -303,8 +303,18 @@ module Spree
to_remove = current - desired
to_add = desired - current
+ return unless to_remove.any? || to_add.any?
+
remove_products(to_remove) if to_remove.any?
add_products(to_add) if to_add.any?
+
+ # Membership is changed via raw `upsert_all`/`delete_all` on `prices`,
+ # which bypasses the `variants`/`products` association caches (and the
+ # `product_ids` ids-reader memo `current` populated above). Reset them so
+ # a same-request read — e.g. the serializer's `product_ids` — reflects the
+ # new membership instead of the pre-change set.
+ association(:variants).reset
+ association(:products).reset
end
def apply_pending_prices
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index c84027c257..f4918b9399 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -760,6 +760,7 @@ module Spree
def apply_variants(variants_params)
variant_ids_in_payload = []
master_touched = false
+ mutated = false
variants_params.each do |variant_data|
variant_data = variant_data.to_h.with_indifferent_access
@@ -770,6 +771,7 @@ module Spree
variant = variants_including_master.find_by_param!(variant_id)
variant.update!(variant_data)
variant_ids_in_payload << variant.id
+ mutated = true
elsif options.blank? || (options.is_a?(Array) && options.empty?)
# An entry with no options addresses the master variant. Building a
# non-master here would create a phantom duplicate (the auto-built
@@ -781,18 +783,46 @@ module Spree
target.assign_attributes(variant_data)
target.save!
master_touched = true
+ mutated = true
else
variant = variants.build
variant.assign_attributes(variant_data)
variant.save!
variant_ids_in_payload << variant.id
+ mutated = true
end
end
# Remove variants not in the payload (only non-master). If only the
# master was touched (simple product), leave existing non-master
# variants alone — the payload is partial, not a full replacement.
- variants.where.not(id: variant_ids_in_payload).destroy_all if variant_ids_in_payload.any? && !master_touched
+ if variant_ids_in_payload.any? && !master_touched
+ removed = variants.where.not(id: variant_ids_in_payload).destroy_all
+ mutated ||= removed.any?
+ end
+
+ sync_variant_state! if mutated
+ end
+
+ # Re-syncs the in-memory derived variant state after `apply_variants`
+ # mutates variants out-of-band (the variant counter is bumped via
+ # `Spree::Product.increment_counter` in a Variant callback, and
+ # `default_variant` is memoized). Without this, a freshly built/updated
+ # product serialized in the same request returns a stale `variant_count`
+ # and a stale `price` (delegated to the memoized `default_variant`).
+ #
+ # The `default_variant` memo reset here changes shape once master is
+ # removed (it becomes a `belongs_to` FK). See
+ # docs/plans/6.0-remove-master-variant.md (Phase 3).
+ # @return [void]
+ def sync_variant_state!
+ # `variant_count` is maintained by a direct counter update in a Variant
+ # callback, so the in-memory attribute is stale here — re-read it from the
+ # row without reloading the whole record.
+ self[:variant_count] = self.class.where(id: id).pick(:variant_count)
+ variants.reset
+ @default_variant = nil
+ @default_variant_id = nil
end
def add_associations_from_prototype
@@ -814,6 +844,7 @@ module Spree
# Builds variants from a hash of option types & values
def build_variants_from_option_values_hash
+ Spree::Deprecation.warn('Spree::Product#build_variants_from_option_values_hash is deprecated and will be removed in Spree 6.0.')
ensure_option_types_exist_for_values_hash
values = option_values_hash.values
values = values.inject(values.shift) { |memo, value| memo.product(value).map(&:flatten) }
@@ -829,6 +860,7 @@ module Spree
end
def ensure_master
+ Spree::Deprecation.warn('Spree::Product#ensure_master is deprecated and will be removed in Spree 6.0.')
return unless new_record?
self.master ||= build_master
@@ -928,12 +960,14 @@ module Spree
end
def discontinue_on_must_be_later_than_make_active_at
+ Spree::Deprecation.warn('Spree::Product#discontinue_on_must_be_later_than_make_active_at is deprecated and will be removed in Spree 6.0.')
if discontinue_on < make_active_at
errors.add(:discontinue_on, :invalid_date_range)
end
end
def requires_price?
+ Spree::Deprecation.warn('Spree::Product#requires_price? is deprecated and will be removed in Spree 6.0.')
Spree::Config[:require_master_price]
end
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index 40ffa0a39a..ee57c5bde4 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -539,7 +539,20 @@ module Spree
# @param compare_at_amount [BigDecimal] the compare at amount to set
# @return [void]
def set_price(currency, amount, compare_at_amount = nil)
- price = prices.base_prices.find_or_initialize_by(currency: currency)
+ # When the prices association is already loaded (eager-loaded for
+ # serialization), reuse the cached base-price instance so readers that
+ # branch on `prices.loaded?` (Pricing::Resolver, #price_in, serializers)
+ # observe the write without a reload. `base_prices.find_or_initialize_by`
+ # would issue a fresh query and return a detached object, leaving the
+ # loaded collection — and the serialized response — stale.
+ price =
+ if prices.loaded?
+ prices.detect { |p| p.price_list_id.nil? && p.currency == currency } ||
+ prices.build(currency: currency)
+ else
+ prices.base_prices.find_or_initialize_by(currency: currency)
+ end
+
price.amount = amount
price.compare_at_amount = compare_at_amount
price.save! if persisted?
diff --git a/spree/core/spec/models/spree/price_list_spec.rb b/spree/core/spec/models/spree/price_list_spec.rb
index 3af761cf1f..45b065bb16 100644
--- a/spree/core/spec/models/spree/price_list_spec.rb
+++ b/spree/core/spec/models/spree/price_list_spec.rb
@@ -173,6 +173,37 @@ describe Spree::PriceList, type: :model do
end
end
+ describe '#product_ids=' do
+ let(:store) { create(:store, supported_currencies: 'USD,EUR,GBP') }
+ let(:price_list) { create(:price_list, store: store) }
+ let(:product1) { create(:product) }
+ let(:product2) { create(:product) }
+
+ # Guards the POST/PATCH /price_lists response: membership is reconciled in
+ # an after_save via raw upsert_all/delete_all (bypassing the products
+ # association cache), so `product_ids` / `product_prefixed_ids` — which the
+ # serializer renders — must reflect the change WITHOUT a reload.
+ it 'reflects assigned products in product_ids without reload' do
+ price_list.product_ids = [product1.id, product2.id]
+ price_list.save!
+
+ expect(price_list.product_ids).to match_array([product1.id, product2.id])
+ expect(price_list.product_prefixed_ids).to match_array(
+ [product1.prefixed_id, product2.prefixed_id]
+ )
+ end
+
+ it 'reflects a partial removal in product_ids without reload' do
+ price_list.product_ids = [product1.id, product2.id]
+ price_list.save!
+
+ price_list.product_ids = [product1.id]
+ price_list.save!
+
+ expect(price_list.product_ids).to eq([product1.id])
+ end
+ end
+
describe '#add_products' do
let(:store) { create(:store, supported_currencies: 'USD,EUR,GBP') }
let(:price_list) { create(:price_list, store: store) }
diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rb
index 2ec1817e6c..1fa01f5624 100644
--- a/spree/core/spec/models/spree/product_spec.rb
+++ b/spree/core/spec/models/spree/product_spec.rb
@@ -1945,6 +1945,43 @@ describe Spree::Product, type: :model do
expect(product.variants).to include(variant)
end
end
+
+ # Guards the POST /products response: derived state the serializer reads
+ # (variant_count, default_variant, price) must reflect the deferred
+ # variant creation WITHOUT a reload, since the controller serializes the
+ # same in-memory product it just saved.
+ context 'in-memory derived state after build + save (no reload)' do
+ it 'reflects new option-bearing variants in variant_count and default_variant' do
+ new_product = Spree::Product.new(
+ name: 'Fresh Variants',
+ shipping_category: shipping_category,
+ store: store,
+ variants: [
+ { sku: 'FV-1', price: 10, options: [{ name: 'Size', value: 'S' }] },
+ { sku: 'FV-2', price: 20, options: [{ name: 'Size', value: 'M' }] }
+ ]
+ )
+ new_product.save!
+
+ expect(new_product.variant_count).to eq(2)
+ expect(new_product.default_variant).not_to eq(new_product.master)
+ expect(new_product.price).to be_present
+ end
+
+ it 'reflects an options-less master upsert in default_variant and price' do
+ new_product = Spree::Product.new(
+ name: 'Fresh Simple',
+ shipping_category: shipping_category,
+ store: store,
+ variants: [{ sku: 'FS-1', price: 15, options: [] }]
+ )
+ new_product.save!
+
+ expect(new_product.variant_count).to eq(0)
+ expect(new_product.default_variant).to eq(new_product.master)
+ expect(new_product.price).to eq(15)
+ end
+ end
end
describe '#media=' do
diff --git a/spree/core/spec/models/spree/promotion_spec.rb b/spree/core/spec/models/spree/promotion_spec.rb
index 7b7834e0b5..70960bdb65 100644
--- a/spree/core/spec/models/spree/promotion_spec.rb
+++ b/spree/core/spec/models/spree/promotion_spec.rb
@@ -968,6 +968,21 @@ describe Spree::Promotion, type: :model do
expect(promotion.rules).to be_empty
end
+ # Guards the PATCH /promotions response: removing a rule must drop it from
+ # the in-memory collection WITHOUT a reload, since the admin serializer
+ # renders `rule_ids` off the loaded association on the same object.
+ it 'reflects a partial removal in the loaded collection without reload' do
+ kept = promotion.rules.create!(type: 'Spree::Promotion::Rules::ItemTotal', preferences: { amount_min: 10 })
+ removed = promotion.rules.create!(type: 'Spree::Promotion::Rules::FirstOrder')
+
+ promotion.promotion_rules.load # eager-load, as the controller scope does
+
+ promotion.rules = [{ id: kept.id, type: 'item_total' }]
+
+ expect(promotion.promotion_rules.map(&:id)).to eq([kept.id])
+ expect(promotion.promotion_rules.map(&:id)).not_to include(removed.id)
+ end
+
# Regression: assigning `product_ids` on a brand-new rule used to fail
# because Rails autosaved the through-join rows before the parent
# rule had an id, tripping `presence: true` on the join model.
diff --git a/spree/core/spec/models/spree/variant_spec.rb b/spree/core/spec/models/spree/variant_spec.rb
index b12b124821..4fe9fdb054 100644
--- a/spree/core/spec/models/spree/variant_spec.rb
+++ b/spree/core/spec/models/spree/variant_spec.rb
@@ -737,6 +737,26 @@ describe Spree::Variant, type: :model do
expect(price.amount).to eq(25.00)
expect(price.compare_at_amount).to eq(35.00)
end
+
+ # Guards the PATCH /variants response: when the prices association is
+ # eager-loaded for serialization, updating a base price must be visible
+ # to readers that branch on `prices.loaded?` (#price_in, #price_for)
+ # WITHOUT a reload — the controller serializes the same in-memory variant.
+ context 'when the prices association is already loaded' do
+ before { create(:price, variant: variant, currency: currency, amount: 10.00) }
+
+ it 'reflects the update in the loaded collection and price readers' do
+ variant.prices.load
+ expect(variant.prices).to be_loaded
+
+ variant.set_price(currency, 30.00)
+
+ expect(variant.prices.detect { |p| p.currency == currency }.amount).to eq(30.00)
+ expect(variant.price_in(currency).amount).to eq(30.00)
+ expect(variant.price_for(currency: currency).amount).to eq(30.00)
+ expect(variant.prices).to be_loaded
+ end
+ end
end
describe '#on_sale?' do