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.

Retire the hidden master variant in favor of default_variant

Łukasz Adamczyk647473e41bf1
diff --git a/docs/plans/6.0-remove-master-variant.md b/docs/plans/6.0-remove-master-variant.md
index 8bca6d315d..8f33506716 100644
--- a/docs/plans/6.0-remove-master-variant.md
+++ b/docs/plans/6.0-remove-master-variant.md
@@ -264,7 +264,8 @@ This task must be **idempotent** and **reversible** (soft — we can't re-create
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.
+12. Replace the `save_master`/`master_updated?`/`@nested_changes`/`reset_nested_changes` cluster with `belongs_to :default_variant, autosave: true`. On **create**, a variant built via the delegated setters is autosaved through the `variants` collection; on **update**, `autosave: true` persists the modified default variant (and cascades its validation) when the product is saved — this covers the delegated-write case (`product.sku = …; save`) that issue #5306 addressed, with no custom save hook. Plain `belongs_to` alone doesn't do this: it autosaves only _new_ associated records, not _modified existing_ ones. The `@nested_changes` touch-dirty flag is dropped — `Variant belongs_to :product, touch: true` covers touch propagation.
+13. Remove the deprecated `option_values_hash` variant-building cluster — `build_variants_from_option_values_hash`, its `after_create` callback, `ensure_option_types_exist_for_values_hash`, `attr_accessor :option_values_hash`, and `:option_values_hash` from `Spree::PermittedAttributes`. It already carried a "removed in 6.0" warning and is used nowhere but its own specs; removing it also avoids a phantom optionless variant that arose only when product-level `sku`/`price` (which eagerly build the default variant) were combined with that hash flow.
### Phase 4: API + serializer updates
diff --git a/spree/admin/app/helpers/spree/admin/products_helper.rb b/spree/admin/app/helpers/spree/admin/products_helper.rb
index 6883c53325..046f907c15 100644
--- a/spree/admin/app/helpers/spree/admin/products_helper.rb
+++ b/spree/admin/app/helpers/spree/admin/products_helper.rb
@@ -42,7 +42,7 @@ module Spree
end
def product_currencies(product)
- product_currencies = product.prices_including_master.map(&:currency).compact.uniq.map do |currency|
+ product_currencies = product.prices.non_zero.map(&:currency).compact.uniq.map do |currency|
::Money::Currency.find(currency)
end
diff --git a/spree/core/app/finders/spree/products/find.rb b/spree/core/app/finders/spree/products/find.rb
index d7e6fddf78..3e467bfb6c 100644
--- a/spree/core/app/finders/spree/products/find.rb
+++ b/spree/core/app/finders/spree/products/find.rb
@@ -124,7 +124,7 @@ module Spree
def by_skus(products)
return products unless skus?
- products.joins(:variants_including_master).where(spree_variants: { sku: skus })
+ products.joins(:variants).where(spree_variants: { sku: skus })
end
def by_price(products)
@@ -302,7 +302,7 @@ module Spree
def order_by_price(scope, sort_order)
scope.
- joins(variants_including_master: :prices).
+ joins(variants: :prices).
select("#{Spree::Product.table_name}.* , min(#{Spree::Price.table_name}.amount)").
where(Spree::Price.table_name => { currency: currency }).
where.not(Spree::Price.table_name => { amount: nil }).
diff --git a/spree/core/app/helpers/spree/products_helper.rb b/spree/core/app/helpers/spree/products_helper.rb
index cd9bd6b4a9..8b7e22056c 100644
--- a/spree/core/app/helpers/spree/products_helper.rb
+++ b/spree/core/app/helpers/spree/products_helper.rb
@@ -76,11 +76,9 @@ module Spree
def product_images(product, variants)
if product.variants_and_option_values(current_currency).any?
- variants_without_master_images = variants.reject(&:is_master).map(&:images).flatten
+ variant_images = variants.map(&:images).flatten
- if variants_without_master_images.any?
- return variants_without_master_images
- end
+ return variant_images if variant_images.any?
end
variants.map(&:images).flatten
@@ -112,7 +110,7 @@ module Spree
where(id: product_ids).
includes(
:tax_category,
- master: [
+ default_variant: [
:prices,
{ images: { attachment_attachment: :blob } },
]
diff --git a/spree/core/app/jobs/spree/images/save_from_url_job.rb b/spree/core/app/jobs/spree/images/save_from_url_job.rb
index 21238b8833..6fcbcd1b96 100644
--- a/spree/core/app/jobs/spree/images/save_from_url_job.rb
+++ b/spree/core/app/jobs/spree/images/save_from_url_job.rb
@@ -90,8 +90,8 @@ module Spree
image.persisted? && image.attachment.attached? && image.external_url.present? && external_url == image.external_url
end
- # `Product#images` delegates to the master variant (legacy alias) — use
- # `Product#media` so 5.5 product-level uploads don't get re-pinned to master.
+ # `Product#images` delegates to the default variant — use `Product#media`
+ # so 5.5 product-level uploads don't get re-pinned to that variant.
def viewable_assets(viewable)
viewable.is_a?(Spree::Product) ? viewable.media : viewable.images
end
diff --git a/spree/core/app/jobs/spree/media/migrate_product_assets_job.rb b/spree/core/app/jobs/spree/media/migrate_product_assets_job.rb
index 990440b31c..7d5ad80771 100644
--- a/spree/core/app/jobs/spree/media/migrate_product_assets_job.rb
+++ b/spree/core/app/jobs/spree/media/migrate_product_assets_job.rb
@@ -5,13 +5,12 @@ module Spree
queue_as Spree.queues.images
def perform(product_id)
- product = Spree::Product.includes(:master, :variants).find_by(id: product_id)
+ product = Spree::Product.includes(:variants).find_by(id: product_id)
return unless product
- # One query for all variant-pinned assets on the product (master +
- # non-master). Grouping by viewable_id avoids N queries per variant.
+ # One query for all variant-pinned assets on the product. Grouping by
+ # viewable_id avoids N queries per variant.
viewable_ids = product.variants.map(&:id)
- viewable_ids << product.master.id if product.master
return if viewable_ids.empty?
assets_by_variant = Spree::Asset
@@ -21,7 +20,6 @@ module Spree
.transform_values { |rows| rows.map(&:first) }
return if assets_by_variant.empty?
- master_id = product.master&.id
touched_variants = []
product.variants.each do |variant|
@@ -29,15 +27,12 @@ module Spree
next if asset_ids.blank?
move_assets_to_product(asset_ids, product)
- link_assets_to_variant(asset_ids, variant.id)
+ # The default variant's assets become product-level only; option
+ # variants keep a VariantMedia link back to the moved asset.
+ link_assets_to_variant(asset_ids, variant.id) unless variant.id == product.default_variant_id
touched_variants << variant
end
- if master_id && (master_asset_ids = assets_by_variant[master_id]).present?
- move_assets_to_product(master_asset_ids, product)
- touched_variants << product.master
- end
-
# update_all + upsert_all skip callbacks, so refresh thumbnails by hand.
touched_variants.each(&:update_thumbnail!)
recalculate_counters(product)
diff --git a/spree/core/app/jobs/spree/products/refresh_metrics_job.rb b/spree/core/app/jobs/spree/products/refresh_metrics_job.rb
index d8322da5ff..f60062633d 100644
--- a/spree/core/app/jobs/spree/products/refresh_metrics_job.rb
+++ b/spree/core/app/jobs/spree/products/refresh_metrics_job.rb
@@ -8,7 +8,7 @@ module Spree
return unless product
completed_order_ids = product.completed_orders.select(:id)
- variant_ids = product.variants_including_master.ids
+ variant_ids = product.variants.ids
line_items = Spree::LineItem.joins(:order)
.where(spree_orders: { id: completed_order_ids })
diff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rb
index 1304458f21..49229d53f3 100644
--- a/spree/core/app/models/concerns/spree/product_scopes.rb
+++ b/spree/core/app/models/concerns/spree/product_scopes.rb
@@ -18,20 +18,8 @@ module Spree
scope :ascend_by_name, -> { order("#{Product.quoted_table_name}.name ASC") }
scope :descend_by_name, -> { order("#{Product.quoted_table_name}.name DESC") }
- # Deprecated — master variant being removed in 6.0. Use ascend_by_price / descend_by_price instead.
- def self.ascend_by_master_price
- Spree::Deprecation.warn('ascend_by_master_price is deprecated and will be removed in Spree 6.0. Use ascend_by_price instead.')
- order(price_table_name => { amount: :asc })
- end
-
- # Deprecated — master variant being removed in 6.0. Use ascend_by_price / descend_by_price instead.
- def self.descend_by_master_price
- Spree::Deprecation.warn('descend_by_master_price is deprecated and will be removed in Spree 6.0. Use descend_by_price instead.')
- order(price_table_name => { amount: :desc })
- end
-
# Price sorting scopes that use a derived table JOIN to get prices across all variants.
- # These ensure products with only variant prices (no master price) are included in results.
+ # These ensure products are matched on any of their variants' prices.
#
# Uses Arel::Nodes::As for select expressions so that:
# - PG allows ORDER BY with DISTINCT (expressions must appear in SELECT list)
@@ -68,18 +56,6 @@ module Spree
where(Price.table_name => { amount: low..high })
}
- # Deprecated — master variant being removed in 6.0. Use price_lte / price_gte instead.
- def self.master_price_lte(price)
- Spree::Deprecation.warn('master_price_lte is deprecated and will be removed in Spree 6.0. Use price_lte instead.')
- where(Price.table_name => { amount: ..price })
- end
-
- # Deprecated — master variant being removed in 6.0. Use price_lte / price_gte instead.
- def self.master_price_gte(price)
- Spree::Deprecation.warn('master_price_gte is deprecated and will be removed in Spree 6.0. Use price_gte instead.')
- where(Price.table_name => { amount: price.. })
- end
-
# Joins spree_variants and spree_stock_items directly (without association
# aliases) so that the table names stay as-is. This avoids alias conflicts
# when combined with other scopes (e.g., price sorting) that also join
@@ -295,7 +271,7 @@ module Spree
end
def self.with_currency(currency)
- joins(variants_including_master: :prices).
+ joins(variants: :prices).
where(Price.table_name => { currency: currency.upcase }).
where.not(Price.table_name => { amount: nil }).
distinct
@@ -399,26 +375,6 @@ module Spree
order(revenue_expr.send(order_dir))
}
- # Deprecated — remove in 6.0. Use by_best_selling instead.
- def self.descend_by_popularity
- Spree::Deprecation.warn('descend_by_popularity is deprecated and will be removed in Spree 6.0. Use by_best_selling instead.')
- joins(:master).
- order(%Q{
- COALESCE((
- SELECT
- COUNT(#{LineItem.quoted_table_name}.id)
- FROM
- #{LineItem.quoted_table_name}
- JOIN
- #{Variant.quoted_table_name} AS popular_variants
- ON
- popular_variants.id = #{LineItem.quoted_table_name}.variant_id
- WHERE
- popular_variants.product_id = #{Product.quoted_table_name}.id
- ), 0) DESC
- })
- end
-
# .search_by_name — simple ILIKE on product name
def self.search_by_name(query)
i18n { name.lower.matches("%#{query.downcase}%") }
diff --git a/spree/core/app/models/spree/asset.rb b/spree/core/app/models/spree/asset.rb
index 7266e8e5f7..7f6c587866 100644
--- a/spree/core/app/models/spree/asset.rb
+++ b/spree/core/app/models/spree/asset.rb
@@ -161,14 +161,9 @@ module Spree
def should_touch_product_variants?
return false unless saved_change_to_position?
- case viewable
- when Spree::Product
- true
- when Spree::Variant
- viewable.is_master? && viewable.product.has_variants?
- else
- false
- end
+ # Variants fall back to product-level media, so only reordering a
+ # product-level asset changes what the variants display.
+ viewable.is_a?(Spree::Product)
end
def increment_viewable_media_count
diff --git a/spree/core/app/models/spree/exports/products.rb b/spree/core/app/models/spree/exports/products.rb
index 93b7dbe2a1..a59398de6f 100644
--- a/spree/core/app/models/spree/exports/products.rb
+++ b/spree/core/app/models/spree/exports/products.rb
@@ -3,7 +3,7 @@ module Spree
class Products < Spree::Export
# to avoid N+1 queries
def scope_includes
- includes = [:tax_category, :master, :option_types, { taxons: :taxonomy }, { variants_including_master: variant_includes }]
+ includes = [:tax_category, :option_types, { taxons: :taxonomy }, { variants: variant_includes }]
includes << { metafields: :metafield_definition }
includes
end
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 5ff07545bf..c8d119734b 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -4,18 +4,12 @@
# Products properties include description, permalink, availability,
# shipping category, etc. that do not change by variant.
#
-# MASTER VARIANT
-# Every product has one master variant, which stores master price and sku, size and weight, etc.
-# The master variant does not have option values associated with it.
-# Price, SKU, size, weight, etc. are all delegated to the master variant.
-# Contains on_hand inventory levels only when there are no variants for the product.
-#
# VARIANTS
-# All variants can access the product properties directly (via reverse delegation).
-# Inventory units are tied to Variant.
-# The master variant can have inventory units, but not option values.
-# All other variants have option values and may have inventory units.
-# Sum of on_hand each variant's inventory level determine "on_hand" level for the product.
+# Every product has at least one variant. Simple products have a single variant
+# with no option values; products with options have one variant per combination.
+# `default_variant` is the "face" of the product — price, SKU, size, weight, etc.
+# are delegated to it. Inventory units are tied to Variant; the sum of each
+# variant's on_hand determines the product's "on_hand" level.
#
module Spree
@@ -87,58 +81,47 @@ module Spree
belongs_to :shipping_category, class_name: 'Spree::ShippingCategory', inverse_of: :products
has_many :shipping_methods, through: :shipping_category, class_name: 'Spree::ShippingMethod'
- has_one :master,
- -> { where is_master: true },
- inverse_of: :product,
- class_name: 'Spree::Variant'
-
+ # Every product has at least one variant. `default_variant` is the "face" of
+ # the product (price display, default add-to-cart, property delegation).
has_many :variants,
- -> { where(is_master: false).order(:position) },
- inverse_of: :product,
- class_name: 'Spree::Variant'
-
- has_many :variants_including_master,
-> { order(:position) },
inverse_of: :product,
class_name: 'Spree::Variant',
dependent: :destroy
- has_many :prices, -> { order('spree_variants.position, spree_variants.id, currency') }, through: :variants
+ belongs_to :default_variant, class_name: 'Spree::Variant', optional: true, autosave: true
- has_many :stock_items, through: :variants_including_master
+ has_many :prices, through: :variants
- has_many :line_items, through: :variants_including_master
+ has_many :stock_items, through: :variants
+
+ has_many :line_items, through: :variants
has_many :orders, through: :line_items
has_many :completed_orders, -> { reorder(nil).distinct.complete }, through: :line_items, source: :order
has_many :media, -> { order(:position) }, as: :viewable, dependent: :destroy, class_name: 'Spree::Asset'
- has_many :variant_images, -> { order(:position) }, source: :images, through: :variants_including_master
- has_many :variant_images_without_master, -> { order(:position) }, source: :images, through: :variants
+ has_many :variant_images, -> { order(:position) }, source: :images, through: :variants
belongs_to :primary_media, class_name: 'Spree::Asset', optional: true, foreign_key: :primary_media_id
has_many :option_value_variants, class_name: 'Spree::OptionValueVariant', through: :variants
has_many :option_values, class_name: 'Spree::OptionValue', through: :variants
- has_many :prices_including_master, -> { non_zero }, through: :variants_including_master, source: :prices
-
- has_many :digitals, through: :variants_including_master
+ has_many :digitals, through: :variants
- after_initialize :ensure_master
after_initialize :assign_default_tax_category
- before_validation :validate_master
before_validation :ensure_default_shipping_category
after_create :add_associations_from_prototype
- after_create :build_variants_from_option_values_hash, if: :option_values_hash
after_create :apply_pending_variants, if: :pending_variants?
+ after_create :ensure_default_variant
+ after_create :set_default_variant
after_save :apply_pending_media, if: :pending_media?
- after_save :save_master
- after_save :run_touch_callbacks, if: :anything_changed?
- after_save :reset_nested_changes
+ after_save :auto_promote_default_variant
+ after_save :run_touch_callbacks, if: :saved_changes?
after_touch :touch_taxons
after_commit :auto_match_taxons, if: :eligible_for_taxon_matching?
@@ -161,7 +144,8 @@ module Spree
scope :not_archived, -> { where.not(status: 'archived') }
scope :on_sale, lambda { |currency = nil|
currency ||= Spree::Store.default.default_currency
- joins(:prices_including_master).with_currency(currency).
+ with_currency(currency).
+ where.not(spree_prices: { amount: 0 }).
where.not(spree_prices: { compare_at_amount: [nil, 0] }).
where("#{Spree::Price.table_name}.compare_at_amount > #{Spree::Price.table_name}.amount")
}
@@ -181,8 +165,6 @@ module Spree
scope :paused, -> { where(status: 'paused') }
scope :published, -> { where(status: 'active') }
- attr_accessor :option_values_hash
-
accepts_nested_attributes_for(
:variants,
allow_destroy: true,
@@ -190,7 +172,6 @@ module Spree
v[:option_value_variants_attributes].blank? && v[:stock_items_attributes].blank? && v[:prices_attributes].blank?
end
)
- accepts_nested_attributes_for :master, reject_if: :all_blank
accepts_nested_attributes_for(
:product_option_types,
allow_destroy: true,
@@ -205,10 +186,10 @@ module Spree
self.tag_list = tags
end
- # Sets prices on the master variant.
+ # Sets prices on the default variant.
# Accepts array of { currency:, amount:, compare_at_amount: } hashes.
def prices=(prices_params)
- find_or_build_master.prices = prices_params
+ find_or_build_default_variant.prices = prices_params
end
# Maps 6.0 API name (category_ids) to model column (taxon_ids).
@@ -266,7 +247,7 @@ module Spree
end
self.whitelisted_ransackable_attributes = %w[description name slug discontinue_on status available_on created_at updated_at]
- self.whitelisted_ransackable_associations = %w[taxons categories store channels variants_including_master master variants tags labels
+ self.whitelisted_ransackable_associations = %w[taxons categories store channels variants default_variant tags labels
shipping_category classifications option_types]
self.whitelisted_ransackable_scopes = %w[not_discontinued search_by_name in_taxon in_category in_categories price_between
price_lte price_gte
@@ -274,26 +255,19 @@ module Spree
ascend_by_price descend_by_price]
+ # All product-level convenience attributes delegate to the default variant —
+ # one target, no branching. Setters build the default variant on demand so
+ # they work before the product is persisted (e.g. `product.sku = ...`).
[
- :sku, :barcode, :weight, :height, :width, :depth, :is_master, :dimensions_unit, :weight_unit
- ].each do |method_name|
- delegate method_name, :"#{method_name}=", to: :find_or_build_master
- end
-
- [
+ :sku, :barcode, :weight, :height, :width, :depth, :dimensions_unit, :weight_unit,
:price, :price_in, :amount_in, :compare_at_price, :compare_at_amount_in,
:currency, :cost_currency, :cost_price, :track_inventory
].each do |method_name|
- delegate method_name, :"#{method_name}=", to: :default_variant
+ delegate method_name, :"#{method_name}=", to: :find_or_build_default_variant
end
delegate :display_amount, :display_price, :has_default_price?, :track_inventory?,
- :display_compare_at_price, :images, to: :default_variant
-
- # Rails doesn't provide _id methods for has_one associations by default
- delegate :id, to: :master, prefix: true, allow_nil: true
-
- alias master_images images
+ :display_compare_at_price, :images, to: :find_or_build_default_variant
state_machine :status, initial: :draft do
event :activate do
@@ -326,57 +300,44 @@ module Spree
# Can't use short form block syntax due to https://github.com/Netflix/fast_jsonapi/issues/259
def purchasable?
- @purchasable ||= default_variant.purchasable? || variants.any?(&:purchasable?)
+ @purchasable ||= variants.any?(&:purchasable?)
end
# Can't use short form block syntax due to https://github.com/Netflix/fast_jsonapi/issues/259
def in_stock?
- @in_stock ||= default_variant.in_stock? || variants.any?(&:in_stock?)
+ @in_stock ||= variants.any?(&:in_stock?)
end
- # Can't use short form block syntax due to https://github.com/Netflix/fast_jsonapi/issues/259
def backorderable?
- default_variant.backorderable? || variants.any?(&:backorderable?)
+ variants.any?(&:backorderable?)
end
def on_sale?(currency)
- prices_including_master.find_all { |p| p.currency == currency }.any?(&:discounted?)
+ prices.find_all { |p| p.currency == currency && p.non_zero? }.any?(&:discounted?)
end
- def find_or_build_master
- master || build_master
+ # The default variant is a persisted FK, but before the product is saved (or
+ # if it somehow has no default set) fall back to the first variant —
+ # including one built in memory via the delegated setters.
+ # @return [Spree::Variant]
+ def default_variant
+ super || variants.first
end
- # Checks if product has variants (non-master variants)
- # Uses variant_count counter cache for performance
- # @return [Boolean]
- def has_variants?
- return variants.size.positive? if variants.loaded?
-
- variant_count.positive?
+ def find_or_build_default_variant
+ default_variant || variants.build
end
- # Returns default Variant for Product
- # If `track_inventory_levels` is enabled it will try to find the first Variant
- # in stock or backorderable, if there's none it will return first Variant sorted
- # by `position` attribute
- # If `track_inventory_levels` is disabled it will return first Variant sorted
- # by `position` attribute
- #
- # @return [Spree::Variant]
- def default_variant
- @default_variant ||= if Spree::Config[:track_inventory_levels] && has_variants? && available_variant = variants.detect(&:purchasable?)
- available_variant
- else
- has_variants? ? variants.first : find_or_build_master
- end
- end
+ # "Does this product have more than one variant (i.e. options to choose from)?"
+ # Uses the variant_count counter cache for performance.
+ # @return [Boolean]
+ def has_multiple_variants?
+ return variants.size > 1 if variants.loaded?
- # Returns default Variant ID for Product
- # @return [Integer]
- def default_variant_id
- @default_variant_id ||= default_variant.id
+ variant_count > 1
end
+ # @deprecated Use #has_multiple_variants? — will be removed in Spree 6.1.
+ alias has_variants? has_multiple_variants?
# Returns the product's media gallery.
# Uses product-level media if present, otherwise falls back to variant images.
@@ -400,7 +361,7 @@ module Spree
alias has_variant_images? has_media?
# Returns the variant that should be used for displaying images.
- # Priority: master > default_variant > first variant with images
+ # Priority: default_variant > first variant with images
# @return [Spree::Variant, nil]
def variant_for_images
@variant_for_images ||= find_variant_for_images
@@ -481,33 +442,17 @@ module Spree
end
def price_varies?(currency)
- prices_including_master.find_all { |p| p.currency == currency && p.amount.present? }.map(&:amount).uniq.count > 1
+ prices.find_all { |p| p.currency == currency && p.non_zero? }.map(&:amount).uniq.count > 1
end
def any_variant_available?(currency)
- if has_variants?
- first_available_variant(currency).present?
- else
- master.purchasable? && master.price_in(currency).amount.present?
- end
+ first_available_variant(currency).present?
end
# returns the lowest price for the product in the given currency
- # prices_including_master are usually already loaded, so this should not trigger an extra query
+ # prices are usually already loaded, so this should not trigger an extra query
def lowest_price(currency)
- prices_including_master.find_all { |p| p.currency == currency }.min_by(&:amount)
- end
-
- # Ensures option_types and product_option_types exist for keys in option_values_hash
- def ensure_option_types_exist_for_values_hash
- return if option_values_hash.nil?
-
- # we need to convert the keys to string to make it work with UUIDs
- required_option_type_ids = option_values_hash.keys.map(&:to_s)
- missing_option_type_ids = required_option_type_ids - option_type_ids.map(&:to_s)
- missing_option_type_ids.each do |id|
- product_option_types.create(option_type_id: id)
- end
+ prices.find_all { |p| p.currency == currency && p.non_zero? }.min_by(&:amount)
end
# for adding products which are closely related to existing ones
@@ -553,14 +498,14 @@ module Spree
!!discontinue_on && discontinue_on <= Time.current
end
- # determine if any variant (including master) can be supplied
+ # determine if any variant can be supplied
def can_supply?
- variants_including_master.any?(&:can_supply?)
+ variants.any?(&:can_supply?)
end
- # determine if any variant (including master) is out of stock and backorderable
+ # determine if any variant is out of stock and backorderable
def backordered?
- variants_including_master.any?(&:backordered?)
+ variants.any?(&:backordered?)
end
def self.like_any(fields, values)
@@ -583,19 +528,29 @@ module Spree
@total_on_hand ||= if any_variants_not_track_inventory?
BigDecimal::INFINITY
else
- if variants_including_master.loaded?
- variants_including_master.sum(&:total_on_hand)
+ if variants.loaded?
+ variants.sum(&:total_on_hand)
else
stock_items.loaded? ? stock_items.sum(&:count_on_hand) : stock_items.sum(:count_on_hand)
end
end
end
- # Master variant may be deleted (i.e. when the product is deleted)
- # which would make AR's default finder return nil.
- # This is a stopgap for that little problem.
+ # @deprecated Use #default_variant — the master variant is being removed in Spree 6.1.
def master
- super || variants_including_master.with_deleted.find_by(is_master: true)
+ Spree::Deprecation.warn('Spree::Product#master is deprecated and will be removed in Spree 6.1. Use #default_variant instead.')
+ default_variant
+ end
+
+ # @deprecated Use #variants — will be removed in Spree 6.1.
+ def variants_including_master
+ Spree::Deprecation.warn('Spree::Product#variants_including_master is deprecated and will be removed in Spree 6.1. Use #variants instead.')
+ variants
+ end
+
+ # @deprecated Use #default_variant_id — will be removed in Spree 6.1.
+ def master_id
+ default_variant_id
end
# Returns the brand taxon for the product
@@ -634,9 +589,9 @@ module Spree
def any_variant_in_stock_or_backorderable?
if has_variants?
- variants_including_master.in_stock_or_backorderable.exists?
+ variants.in_stock_or_backorderable.exists?
else
- master.in_stock_or_backorderable?
+ default_variant.in_stock_or_backorderable?
end
end
@@ -676,7 +631,7 @@ module Spree
taxons_for_csv.fill(nil, taxons_for_csv.size...3)
csv_lines = []
- all_variants = has_variants? ? variants_including_master.to_a : [master]
+ all_variants = variants.to_a
default_currency = store.default_currency
additional_currencies = store.supported_currencies_list.map(&:iso_code) - [default_currency]
@@ -713,10 +668,9 @@ module Spree
private
# Determines which variant should be used for displaying media.
- # Priority: master > default_variant > first variant with media
+ # Priority: default_variant > first variant with media
def find_variant_for_images
- return master if master.has_media?
- return default_variant if has_variants? && default_variant.has_media?
+ return default_variant if default_variant&.has_media?
return find_variant_with_images if has_media?
nil
@@ -780,44 +734,27 @@ 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
variant_id = variant_data.delete(:id)
- options = variant_data[:options]
if variant_id.present?
- variant = variants_including_master.find_by_param!(variant_id)
+ variant = variants.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
- # master already exists, and `variants` excludes it). Upsert onto
- # the master instead — the merchant-visible "default variant" on a
- # simple product IS the master.
- variant_data = variant_data.except(:options)
- target = find_or_build_master
- 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
+
+ variant_ids_in_payload << variant.id
+ mutated = true
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.
- if variant_ids_in_payload.any? && !master_touched
+ # Full replacement: variants not in the payload are removed.
+ if variant_ids_in_payload.any?
removed = variants.where.not(id: variant_ids_in_payload).destroy_all
mutated ||= removed.any?
end
@@ -826,24 +763,16 @@ module Spree
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).
+ # mutates variants out-of-band. `variant_count` is bumped via
+ # `Spree::Product.increment_counter` in a Variant callback, so the in-memory
+ # attribute is stale; the `default_variant` association is also cached.
+ # Without this, a freshly built/updated product serialized in the same
+ # request returns a stale `variant_count` and `price`.
# @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
+ association(:default_variant).reset
end
def add_associations_from_prototype
@@ -856,91 +785,40 @@ module Spree
def any_variants_not_track_inventory?
return true unless Spree::Config.track_inventory_levels
- if variants_including_master.loaded?
- variants_including_master.any? { |v| !v.track_inventory? }
+ if variants.loaded?
+ variants.any? { |v| !v.track_inventory? }
else
- variants_including_master.where(track_inventory: false).exists?
+ variants.where(track_inventory: false).exists?
end
end
- # 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) }
+ # Every product must have at least one variant. If none was built via the
+ # delegated setters or supplied as nested attributes, create an empty one.
+ def ensure_default_variant
+ variants.create! if variants.empty?
+ end
- default_currency = store&.default_currency || Spree::Store.default.default_currency
- master_price = master.price_in(default_currency).amount
+ def set_default_variant
+ return if default_variant_id.present?
- values.each do |ids|
- variant = variants.create!(option_value_ids: ids)
- variant.set_price(default_currency, master_price) if master_price.present?
- end
- save
+ first_variant = variants.first
+ update_column(:default_variant_id, first_variant.id) if first_variant
end
- def ensure_master
- return unless new_record?
+ # Re-point the default variant when the current one has been removed. Sticky
+ # otherwise — an in-stock change never re-points (see the plan's open question).
+ def auto_promote_default_variant
+ current = association(:default_variant).reader
+ return if current && current.deleted_at.nil?
- self.master ||= build_master
+ next_variant = variants.reload.first
+ update_column(:default_variant_id, next_variant&.id) if next_variant && next_variant.id != default_variant_id
end
def assign_default_tax_category
self.tax_category = Spree::TaxCategory.default if new_record? && self[:tax_category_id].blank?
end
- def anything_changed?
- saved_changes? || @nested_changes
- end
-
- def reset_nested_changes
- @nested_changes = false
- end
-
- def master_updated?
- master && (
- master.new_record? ||
- master.changed? ||
- (
- Spree::Config.enable_legacy_default_price &&
- master.default_price &&
- (
- master.default_price.new_record? ||
- master.default_price.changed?
- )
- )
- )
- end
-
- # there's a weird quirk with the delegate stuff that does not automatically save the delegate object
- # when saving so we force a save using a hook
- # Fix for issue #5306
- def save_master
- if master_updated?
- master.save!
- @nested_changes = true
- end
- end
-
- # If the master cannot be saved, the Product object will get its errors
- # and will be destroyed
- def validate_master
- if Spree::Config.enable_legacy_default_price
- # We call master.default_price here to ensure price is initialized.
- # Required to avoid Variant#check_price validation failing on create.
- master.default_price
- end
-
- unless master.valid?
- master.errors.map { |error| { field: error.attribute, message: error&.message } }.each do |err|
- next if err[:field].blank? || err[:message].blank?
-
- errors.add(err[:field], err[:message])
- end
- end
- end
-
def ensure_default_shipping_category
return if shipping_category.present?
@@ -987,7 +865,7 @@ module Spree
end
def requires_price?
- Spree::Config[:require_master_price]
+ Spree::Config[:require_default_variant_price]
end
def requires_shipping_category?
diff --git a/spree/core/app/models/spree/reports/products_performance.rb b/spree/core/app/models/spree/reports/products_performance.rb
index 0f669d8ba1..7f175197ca 100644
--- a/spree/core/app/models/spree/reports/products_performance.rb
+++ b/spree/core/app/models/spree/reports/products_performance.rb
@@ -28,7 +28,7 @@ module Spree
product_scope = store.products
product_scope = product_scope.where(vendor_id: vendor.id) if defined?(vendor) && vendor.present?
- product_scope.includes(:taxons, :tax_category, variants: :prices, master: :prices).
+ product_scope.includes(:taxons, :tax_category, variants: :prices).
joins("LEFT JOIN (#{line_items_sql}) AS line_items ON #{Spree::Product.table_name}.id = line_items.product_id").
select("
spree_products.*,
diff --git a/spree/core/app/models/spree/return_item/exchange_variant_eligibility/same_product.rb b/spree/core/app/models/spree/return_item/exchange_variant_eligibility/same_product.rb
index b256e2e623..34c91f4b58 100644
--- a/spree/core/app/models/spree/return_item/exchange_variant_eligibility/same_product.rb
+++ b/spree/core/app/models/spree/return_item/exchange_variant_eligibility/same_product.rb
@@ -2,7 +2,7 @@ module Spree
module ReturnItem::ExchangeVariantEligibility
class SameProduct
def self.eligible_variants(variant)
- Spree::Variant.where(product_id: variant.product_id, is_master: variant.is_master?).in_stock_or_backorderable
+ Spree::Variant.where(product_id: variant.product_id).in_stock_or_backorderable
end
end
end
diff --git a/spree/core/app/models/spree/stock/package.rb b/spree/core/app/models/spree/stock/package.rb
index 98363cf2e2..ad719eaf7e 100644
--- a/spree/core/app/models/spree/stock/package.rb
+++ b/spree/core/app/models/spree/stock/package.rb
@@ -71,7 +71,7 @@ module Spree
end
def shipping_categories
- Spree::ShippingCategory.joins(products: :variants_including_master).
+ Spree::ShippingCategory.joins(products: :variants).
where(spree_variants: { id: variant_ids }).distinct
end
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 6d858992e6..bc33e06691 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -84,7 +84,7 @@ module Spree
has_many :products, class_name: 'Spree::Product', dependent: :nullify
has_many :product_publications, through: :channels, source: :publications, class_name: 'Spree::ProductPublication'
- has_many :variants, through: :products, class_name: 'Spree::Variant', source: :variants_including_master
+ has_many :variants, through: :products, class_name: 'Spree::Variant', source: :variants
has_many :stock_items, through: :variants, class_name: 'Spree::StockItem'
has_many :prices, through: :variants, class_name: 'Spree::Price'
has_many :price_lists, class_name: 'Spree::PriceList', inverse_of: :store
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index 1a01bbc2f1..e77d4bc0d5 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -77,8 +77,6 @@ module Spree
validate :check_price, if: -> { Spree::Config.enable_legacy_default_price }
- validates :option_value_variants, presence: true, unless: :is_master?
-
validates :cost_price, numericality: { greater_than_or_equal_to: 0, allow_nil: true }
validates :price, numericality: { greater_than_or_equal_to: 0, allow_nil: true },
if: -> { Spree::Config.enable_legacy_default_price }
@@ -91,28 +89,19 @@ module Spree
validates :backorder_limit, numericality: { only_integer: true, greater_than_or_equal_to: 0, allow_nil: true }
after_create :create_stock_items
- after_create :set_master_out_of_stock, unless: :is_master?
after_commit :clear_line_items_cache, on: :update
after_save :create_default_stock_item, unless: :track_inventory?
after_update_commit :handle_track_inventory_change
- after_commit :remove_prices_from_master_variant, on: [:create, :update], unless: :is_master?
- after_commit :remove_stock_items_from_master_variant, on: :create, unless: :is_master?
- after_create :increment_product_variant_count, unless: :is_master?
- after_destroy :decrement_product_variant_count, unless: :is_master?
+ after_create :increment_product_variant_count
+ after_destroy :decrement_product_variant_count
scope :in_stock, -> { left_joins(:stock_items).where("#{Spree::Variant.table_name}.track_inventory = ? OR #{Spree::StockItem.table_name}.count_on_hand > ?", false, 0) }
scope :backorderable, -> { left_joins(:stock_items).where(spree_stock_items: { backorderable: true }) }
scope :in_stock_or_backorderable, -> { in_stock.or(backorderable) }
- scope :eligible, lambda {
- joins(:product).where(
- arel_table[:is_master].eq(false).or(
- Spree::Product.arel_table[:variant_count].eq(0)
- )
- )
- }
+ scope :eligible, -> { all }
scope :not_discontinued, lambda {
where(
@@ -198,7 +187,7 @@ module Spree
)
self.whitelisted_ransackable_associations = %w[option_values product tax_category prices default_price]
- self.whitelisted_ransackable_attributes = %w[weight depth width height sku discontinue_on is_master cost_price cost_currency track_inventory
+ self.whitelisted_ransackable_attributes = %w[weight depth width height sku discontinue_on cost_price cost_currency track_inventory
deleted_at product_id]
self.whitelisted_ransackable_scopes = %i(product_name_or_sku_cont search_by_product_name_or_sku search)
@@ -296,13 +285,13 @@ module Spree
# Returns the exchange name of the variant.
# @return [String] the exchange name of the variant
def exchange_name
- is_master? ? name : options_text
+ option_values.any? ? options_text : name
end
# Returns the descriptive name of the variant.
# @return [String] the descriptive name of the variant
def descriptive_name
- is_master? ? name + ' - Master' : name + ' - ' + options_text
+ option_values.any? ? "#{name} - #{options_text}" : name
end
# Returns the variant's media gallery.
@@ -408,9 +397,6 @@ module Spree
# @param opt_type_position [Integer] the position of the option type
# @return [void]
def set_option_value(opt_name, opt_value, opt_type_position = nil)
- # no option values on master
- return if is_master
-
option_type = Spree::OptionType.where(name: opt_name.parameterize).first_or_initialize do |o|
o.name = o.presentation = opt_name
o.save!
@@ -754,14 +740,7 @@ module Spree
Spree::Stock::Quantifier.new(self)
end
- def set_master_out_of_stock
- if product.master&.in_stock?
- product.master.stock_items.update_all(backorderable: false)
- product.master.stock_items.each(&:reduce_count_on_hand_to_zero)
- end
- end
-
- # Ensures a new variant takes the product master price when price is not supplied
+ # Ensures a new variant takes the product's default variant price when price is not supplied
def check_price
return if prices.any?
@@ -773,9 +752,9 @@ module Spree
current_price = price_in(default_currency).amount
if current_price.nil?
- return errors.add(:base, :no_master_variant_found_to_infer_price) unless product&.master
+ return errors.add(:base, :no_default_variant_found_to_infer_price) unless product&.default_variant
- # At this point, master can have or have no price, so let's use price from the default variant
+ # The default variant may or may not have a price yet; use it when present.
inferred_price = product.default_variant.price_in(default_currency).amount
set_price(default_currency, inferred_price) if inferred_price.present?
end
@@ -812,14 +791,6 @@ module Spree
stock_items.update_all(count_on_hand: 0, updated_at: Time.current)
end
- def remove_prices_from_master_variant
- product.master.prices.delete_all if prices.exists?
- end
-
- def remove_stock_items_from_master_variant
- product.master.stock_items.delete_all
- end
-
def increment_product_variant_count
Spree::Product.increment_counter(:variant_count, product_id)
end
diff --git a/spree/core/app/presenters/spree/data_feeds/google_presenter.rb b/spree/core/app/presenters/spree/data_feeds/google_presenter.rb
index ca19dcafde..f6270539a2 100644
--- a/spree/core/app/presenters/spree/data_feeds/google_presenter.rb
+++ b/spree/core/app/presenters/spree/data_feeds/google_presenter.rb
@@ -26,10 +26,8 @@ module Spree
end
def build_items(xml)
- products.includes(:primary_media, public_metafields: :metafield_definition, variants_including_master: [:primary_media, option_values: :option_type]).find_each do |product|
- product.variants_including_master.active.each do |variant|
- next if variant.is_master? && product.has_variants?
-
+ products.includes(:primary_media, public_metafields: :metafield_definition, variants: [:primary_media, option_values: :option_type]).find_each do |product|
+ product.variants.active.each do |variant|
build_item(xml, product, variant)
end
end
diff --git a/spree/core/app/presenters/spree/search_provider/product_presenter.rb b/spree/core/app/presenters/spree/search_provider/product_presenter.rb
index c1c5884cb1..883fd1a900 100644
--- a/spree/core/app/presenters/spree/search_provider/product_presenter.rb
+++ b/spree/core/app/presenters/spree/search_provider/product_presenter.rb
@@ -129,9 +129,9 @@ module Spree
variant_option_values_data.map(&:prefixed_id).uniq
end
- # Use variants_including_master (matches reindex preload) instead of variants.includes
+ # Use variants (matches reindex preload) instead of variants.includes
def variant_option_values_data
- @variant_option_values_data ||= product.variants_including_master.flat_map(&:option_values).uniq
+ @variant_option_values_data ||= product.variants.flat_map(&:option_values).uniq
end
end
end
diff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
index 97c61ef245..83c43d1a42 100644
--- a/spree/core/app/services/spree/imports/row_processors/product_variant.rb
+++ b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
@@ -13,14 +13,12 @@ module Spree
attr_reader :product, :store
def process!
- variant_scope = options.empty? ? product.variants_including_master : product.variants
-
variant = if attributes['sku'].present?
- variant_scope.where(
+ product.variants.where(
Spree::Variant.arel_table[:sku].lower.eq(attributes['sku'].strip.downcase)
).first || product.variants.new
elsif options.empty?
- product.master
+ product.default_variant
else
product.variants.new
end
@@ -52,14 +50,32 @@ module Spree
handle_images(variant)
- variant
+ remove_placeholder_default_variant if options.any?
+
+ # A row that resolves to a real option variant owns that Variant; a
+ # product/header row resolves to the option-less default (a placeholder
+ # that may later be removed), so it owns the Product instead — keeping the
+ # import row linked to a record that always survives.
+ variant.option_values.any? ? variant : product
end
private
+ # A product-header (options-empty) row creates an option-less default
+ # variant to hold product-level attributes. Once an option-bearing
+ # variant exists, that placeholder is a leftover — remove it and
+ # re-point the default so the product has exactly its option variants.
+ def remove_placeholder_default_variant
+ placeholders = product.variants.where.missing(:option_value_variants)
+ return if placeholders.empty?
+
+ placeholders.destroy_all
+ product.update_column(:default_variant_id, product.variants.reload.first&.id)
+ end
+
def ensure_product_exists
if options.empty?
- # For master variants, create or update the product
+ # For product/header rows (no options), create or update the product
product = Spree::Product.new
if attributes['slug'].present?
existing_product = product_scope.find_by(slug: attributes['slug'].strip.downcase)
@@ -80,7 +96,7 @@ module Spree
product
else
- # For non-master variants, only look up the product
+ # For variant rows (with options), only look up the product
if attributes['slug'].present?
product_scope.find_by!(slug: attributes['slug'].strip.downcase)
else
@@ -94,7 +110,7 @@ module Spree
end
def assign_attributes_to_product(product)
- # setting SKU for master variant so it will be picked up in process! and won't try to create a non-master variant
+ # set the SKU on a product/header row so process! updates the default variant instead of creating a new one
if product.new_record?
product.slug = attributes['slug']
product.sku = attributes['sku'] if attributes['sku'].present? && options.empty?
@@ -210,9 +226,10 @@ module Spree
return if image_urls.empty?
# Always attach to the product so blobs aren't duplicated across
- # variants. For non-master rows, pass the variant id so the job links
- # the resulting product-level asset to that variant via VariantMedia.
- link_variant_id = variant.is_master? ? nil : variant.id
+ # variants. For option rows, pass the variant id so the job links the
+ # resulting product-level asset to that variant via VariantMedia; a
+ # simple product's default variant keeps images product-level.
+ link_variant_id = options.empty? ? nil : variant.id
image_urls.each do |image_url|
Spree::Images::SaveFromUrlJob.perform_later(
diff --git a/spree/core/app/services/spree/prices/bulk_upsert.rb b/spree/core/app/services/spree/prices/bulk_upsert.rb
index 91aeb7c893..4acbcc6ecd 100644
--- a/spree/core/app/services/spree/prices/bulk_upsert.rb
+++ b/spree/core/app/services/spree/prices/bulk_upsert.rb
@@ -141,12 +141,9 @@ module Spree
# `upsert_all` and `delete_all` skip the `Price -> Variant` and
# `Variant -> Product` `touch:` chains otherwise.
#
- # We deliberately bypass AR callbacks: invoking `Variant#touch`
- # would fire `after_commit :remove_prices_from_master_variant`,
- # which `delete_all`s the master's prices whenever a non-master
- # sibling has any prices — wiping exactly the rows the bulk
- # upsert just persisted on a freshly-created list. `touch_all`
- # gives us the cache bust without that side effect.
+ # We use `touch_all` rather than per-record `Variant#touch`: it bumps
+ # every affected row in a single UPDATE and skips AR callbacks, giving
+ # the cache bust without extra side effects.
def touch_variants(variant_ids)
return if variant_ids.empty?
diff --git a/spree/core/app/services/spree/products/duplicator.rb b/spree/core/app/services/spree/products/duplicator.rb
index 2cf3327d8c..84328368b0 100644
--- a/spree/core/app/services/spree/products/duplicator.rb
+++ b/spree/core/app/services/spree/products/duplicator.rb
@@ -33,22 +33,11 @@ module Spree
new_product.deleted_at = nil
new_product.updated_at = nil
new_product.tag_list = product.tag_list
- new_product.master = duplicate_master(product.master, include_images)
+ new_product.default_variant_id = nil
new_product.variants = product.variants.map { |variant| duplicate_variant(variant, include_images) }
end
end
- def duplicate_master(master, include_images)
- master.dup.tap do |new_master|
- new_master.sku = sku_generator(master.sku)
- new_master.deleted_at = nil
- new_master.prices = duplicate_prices(master.prices)
- new_master.stock_items = duplicate_stock_items(master.stock_items)
-
- master.images.each { |image| duplicate_image(image, new_master) } if include_images
- end
- end
-
def duplicate_variant(variant, include_images)
new_variant = variant.dup
new_variant.sku = sku_generator(new_variant.sku)
@@ -96,7 +85,6 @@ module Spree
def duplicate_error_message(new_product)
errors = []
errors << new_product.errors.full_messages
- errors << new_product.master.errors.full_messages
new_product.variants.each do |variant|
errors << variant.errors.full_messages
diff --git a/spree/core/app/services/spree/products/prepare_nested_attributes.rb b/spree/core/app/services/spree/products/prepare_nested_attributes.rb
index e0b0f8a60b..5b1ab8413e 100644
--- a/spree/core/app/services/spree/products/prepare_nested_attributes.rb
+++ b/spree/core/app/services/spree/products/prepare_nested_attributes.rb
@@ -54,17 +54,6 @@ module Spree
params[:variants_attributes] = params[:variants_attributes].merge(removed_variants_attributes)
params[:product_option_types_attributes] = product_option_types_params.merge(removed_product_option_types_attributes)
- elsif params[:master_attributes]
- params[:master_attributes].delete(:stock_items_attributes) unless can_update_stock_items?
-
- if can_update_prices?
- # If the master price is nil then mark it for destruction
- params.dig(:master_attributes, :prices_attributes)&.each do |price_key, price_params|
- params[:master_attributes][:prices_attributes][price_key]['_destroy'] = '1' if price_params[:amount].blank?
- end
- else
- params[:master_attributes].delete(:prices_attributes)
- end
end
params.delete(:legacy_product_publications_attributes) unless can?(:manage, Spree::ProductPublication)
diff --git a/spree/core/app/sorters/spree/classifications/sort.rb b/spree/core/app/sorters/spree/classifications/sort.rb
index ed9a9a73e0..c768ac76ce 100644
--- a/spree/core/app/sorters/spree/classifications/sort.rb
+++ b/spree/core/app/sorters/spree/classifications/sort.rb
@@ -52,7 +52,7 @@ module Spree
def by_price(scope)
return scope unless (value = sort_by?('price'))
- scope.joins(product: { variants_including_master: :prices }).
+ scope.joins(product: { variants: :prices }).
select("#{Spree::Classification.table_name}.*, min(#{Spree::Price.table_name}.amount)").
distinct.
where(spree_prices: { currency: currency }).
diff --git a/spree/core/app/sorters/spree/products/sort.rb b/spree/core/app/sorters/spree/products/sort.rb
index d6bd8eb9e4..0d45c64c90 100644
--- a/spree/core/app/sorters/spree/products/sort.rb
+++ b/spree/core/app/sorters/spree/products/sort.rb
@@ -23,7 +23,7 @@ module Spree
def by_price(scope)
return scope unless (value = sort_by?('price'))
- scope.joins(variants_including_master: :prices).
+ scope.joins(variants: :prices).
select("#{Spree::Product.table_name}.*, #{Spree::Price.table_name}.amount").
distinct.
where("#{Spree::Price.table_name}.currency": currency).
@@ -39,7 +39,7 @@ module Spree
"#{Spree::Product.table_name}.*, "
end
- scope.joins(:master).
+ scope.joins(:default_variant).
select("#{select_product_attributes}#{Spree::Variant.table_name}.sku").
order("#{Spree::Variant.table_name}.sku #{value[1]}")
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 41fe97f467..97211301df 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -381,7 +381,7 @@ en:
base:
cannot_destroy_if_attached_to_line_items: Cannot delete Variants that are added to placed Orders. In such cases, please discontinue them.
must_supply_price_for_variant_or_master: Must supply price for variant or master price for product.
- no_master_variant_found_to_infer_price: No master variant found to infer price
+ no_default_variant_found_to_infer_price: No default variant found to infer price
spree/webhook_endpoint:
attributes:
url:
diff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rb
index c8fe2847ff..47565ca648 100644
--- a/spree/core/lib/spree/core/configuration.rb
+++ b/spree/core/lib/spree/core/configuration.rb
@@ -89,7 +89,7 @@ module Spree
preference :max_level_in_taxons_menu, :integer, deprecated: true
preference :non_expiring_credit_types, :array, default: []
preference :products_per_page, :integer, default: 12
- preference :require_master_price, :boolean, default: false
+ preference :require_default_variant_price, :boolean, default: false
preference :restock_inventory, :boolean, default: true # Determines if a return item is restocked automatically once it has been received
preference :return_eligibility_number_of_days, :integer, default: 365
preference :reserve_stock_on, :string, default: 'checkout' # 'checkout' (default) or 'cart' — landing in 6.0 alongside Cart/Order split
diff --git a/spree/core/lib/spree/core/controller_helpers/order.rb b/spree/core/lib/spree/core/controller_helpers/order.rb
index 03eb2ae26c..e58369c904 100644
--- a/spree/core/lib/spree/core/controller_helpers/order.rb
+++ b/spree/core/lib/spree/core/controller_helpers/order.rb
@@ -156,7 +156,7 @@ module Spree
:stock_locations,
{ option_values: :option_type },
{ stock_items: :stock_location },
- { product: :master }
+ { product: :default_variant }
]
variant_includes << :default_price if Spree::Config.enable_legacy_default_price
diff --git a/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb b/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb
index 627d3e8592..c3770b8981 100644
--- a/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb
+++ b/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb
@@ -33,8 +33,7 @@ module Spree
def permitted_product_attributes
permitted_attributes.product_attributes + [
- variants_attributes: permitted_variant_attributes + ['id', :_destroy],
- master_attributes: permitted_variant_attributes + ['id']
+ variants_attributes: permitted_variant_attributes + ['id', :_destroy]
]
end
diff --git a/spree/core/lib/spree/permitted_attributes.rb b/spree/core/lib/spree/permitted_attributes.rb
index 26302aa787..d03d7a65f0 100644
--- a/spree/core/lib/spree/permitted_attributes.rb
+++ b/spree/core/lib/spree/permitted_attributes.rb
@@ -182,7 +182,7 @@ module Spree
@@product_attributes = [
:name, :description, :available_on, :make_active_at, :discontinue_on, :permalink, :meta_description,
:meta_keywords, :meta_title, :price, :sku, :deleted_at, :prototype_id,
- :option_values_hash, :weight, :height, :width, :depth,
+ :weight, :height, :width, :depth,
:shipping_category_id, :tax_category_id,
:cost_currency, :cost_price, :compare_at_price,
:slug, :track_inventory, :backorderable, :barcode, :status,
diff --git a/spree/core/lib/spree/testing_support/factories/product_factory.rb b/spree/core/lib/spree/testing_support/factories/product_factory.rb
index 2007289f3a..7601ce3fa1 100644
--- a/spree/core/lib/spree/testing_support/factories/product_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/product_factory.rb
@@ -1,4 +1,31 @@
FactoryBot.define do
+ # A product with no product-level sku/price. Because those delegated setters
+ # are what eagerly build the default variant, an empty product builds none up
+ # front — its single default variant is created by +ensure_default_variant+ on
+ # create, and supplying nested +variants+ yields exactly those variants. Use
+ # this to exercise the true product-creation flow (API shape) without the
+ # convenience attributes.
+ factory :empty_product, class: Spree::Product do
+ sequence(:name) { |n| "Empty Product #{n}#{Kernel.rand(9999)}" }
+ shipping_category { |r| Spree::ShippingCategory.first || r.association(:shipping_category) }
+ status { 'active' }
+ store { Spree::Store.default || association(:store) }
+
+ before(:create) do |_product|
+ create(:stock_location) unless Spree::StockLocation.any?
+ end
+ after(:create) do |product|
+ if product.store&.default_channel && product.product_publications.empty?
+ Spree::ProductPublication.create!(
+ product: product,
+ channel: product.store.default_channel,
+ published_at: product.available_on,
+ unpublished_at: product.discontinue_on
+ )
+ end
+ end
+ end
+
factory :base_product, class: Spree::Product do
sequence(:name) { |n| "Product #{n}#{Kernel.rand(9999)}" }
description { generate(:random_description) }
@@ -19,14 +46,14 @@ FactoryBot.define do
create(:stock_location) unless Spree::StockLocation.any?
end
after(:create) do |product, evaluator|
- existing_location_ids = product.master.stock_items.pluck(:stock_location_id)
+ existing_location_ids = product.default_variant.stock_items.pluck(:stock_location_id)
Spree::StockLocation.where.not(id: existing_location_ids).find_each do |stock_location|
- stock_location.propagate_variant(product.master)
+ stock_location.propagate_variant(product.default_variant)
end
if evaluator.price.present?
price_currency = evaluator.currency || product.store&.default_currency || 'USD'
- product.master.set_price(price_currency, evaluator.price, evaluator.compare_at_price)
+ product.default_variant.set_price(price_currency, evaluator.price, evaluator.compare_at_price)
end
# Test convenience only: auto-publish each product on its store's
@@ -56,12 +83,12 @@ FactoryBot.define do
factory :product_in_stock do
after :create do |product|
- product.master.stock_items.first.adjust_count_on_hand(10)
+ product.default_variant.stock_items.first.adjust_count_on_hand(10)
end
trait :without_backorder do
after :create do |product|
- product.master.stock_items.update_all(backorderable: false)
+ product.default_variant.stock_items.update_all(backorderable: false)
end
end
end
diff --git a/spree/core/lib/spree/testing_support/factories/stock_location_factory.rb b/spree/core/lib/spree/testing_support/factories/stock_location_factory.rb
index cc006a97a6..d9ef237c51 100644
--- a/spree/core/lib/spree/testing_support/factories/stock_location_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/stock_location_factory.rb
@@ -17,13 +17,13 @@ FactoryBot.define do
factory :stock_location_with_items do
after(:create) do |stock_location, _evaluator|
# variant will add itself to all stock_locations in an after_create
- # creating a product will automatically create a master variant
+ # creating a product will automatically create a default variant
store = Spree::Store.first || create(:store)
product_1 = create(:product)
product_2 = create(:product)
- stock_location.stock_item_or_create(product_1.master).adjust_count_on_hand(10)
- stock_location.stock_item_or_create(product_2.master).adjust_count_on_hand(20)
+ stock_location.stock_item_or_create(product_1.default_variant).adjust_count_on_hand(10)
+ stock_location.stock_item_or_create(product_2.default_variant).adjust_count_on_hand(20)
end
end
end
diff --git a/spree/core/spec/helpers/products_helper_spec.rb b/spree/core/spec/helpers/products_helper_spec.rb
index 0b887c7df7..fd579129e0 100644
--- a/spree/core/spec/helpers/products_helper_spec.rb
+++ b/spree/core/spec/helpers/products_helper_spec.rb
@@ -27,18 +27,18 @@ module Spree
allow(@variant).to receive(:amount_in) { variant_price }
end
- context 'when variant is same as master' do
+ context 'when variant is same as the default variant' do
it { is_expected.to be_nil }
end
- context 'when the master has no price' do
+ context 'when the default variant has no price' do
let(:product_price) { nil }
it { is_expected.to be_nil }
end
context 'when currency is default' do
- context 'when variant is more than master' do
+ context 'when variant is more than the default variant' do
let(:variant_price) { 15 }
it { is_expected.to eq('(Add: $5.00)') }
@@ -46,7 +46,7 @@ module Spree
it { is_expected.to be_html_safe }
end
- context 'when variant is less than master' do
+ context 'when variant is less than the default variant' do
let(:product_price) { 15 }
it { is_expected.to eq('(Subtract: $5.00)') }
@@ -58,13 +58,13 @@ module Spree
let(:product_price) { 100 }
let(:currency) { 'JPY' }
- context 'when variant is more than master' do
+ context 'when variant is more than the default variant' do
let(:variant_price) { 150 }
it { is_expected.to eq("(Add: \u00A550)") }
end
- context 'when variant is less than master' do
+ context 'when variant is less than the default variant' do
let(:product_price) { 150 }
it { is_expected.to eq("(Subtract: \u00A550)") }
@@ -80,7 +80,7 @@ module Spree
end
context 'when currency is default' do
- it 'returns the variant price if the price is different than master' do
+ it 'returns the variant price if the price is different than the default variant' do
product.price = 10
@variant1.price = 15
@variant2.price = 20
@@ -101,7 +101,7 @@ module Spree
end
end
- it 'returns the variant price if the price is different than master' do
+ it 'returns the variant price if the price is different than the default variant' do
product.price = 100
@variant1.price = 150
expect(helper.variant_price(@variant1)).to eq("\u00A5150")
diff --git a/spree/core/spec/jobs/spree/imports/process_group_job_spec.rb b/spree/core/spec/jobs/spree/imports/process_group_job_spec.rb
index b98c987e77..ce2debd038 100644
--- a/spree/core/spec/jobs/spree/imports/process_group_job_spec.rb
+++ b/spree/core/spec/jobs/spree/imports/process_group_job_spec.rb
@@ -31,8 +31,8 @@ RSpec.describe Spree::Imports::ProcessGroupJob, type: :job do
row.reload
expect(row.status).to eq('completed')
- expect(row.item).to be_a(Spree::Variant)
- expect(row.item.product.name).to eq('Test Product')
+ expect(row.item).to be_a(Spree::Product)
+ expect(row.item.name).to eq('Test Product')
expect(row.item.sku).to eq('SKU1')
import.reload
@@ -165,7 +165,7 @@ RSpec.describe Spree::Imports::ProcessGroupJob, type: :job do
expect(row.reload.status).to eq('completed')
expect(variant_row.reload.status).to eq('completed')
- product = row.item.product
+ product = row.item
expect(product.name).to eq('Test Product')
expect(variant_row.item).to be_a(Spree::Variant)
expect(variant_row.item.product).to eq(product)
@@ -185,8 +185,8 @@ RSpec.describe Spree::Imports::ProcessGroupJob, type: :job do
row.reload
expect(row.status).to eq('completed')
- expect(row.item).to be_a(Spree::Variant)
- expect(row.item.product.name).to eq('Test Product')
+ expect(row.item).to be_a(Spree::Product)
+ expect(row.item.name).to eq('Test Product')
expect(row.item.sku).to eq('SKU1')
end
@@ -206,14 +206,14 @@ RSpec.describe Spree::Imports::ProcessGroupJob, type: :job do
expect {
described_class.perform_now(import.id, [row.id, variant_row.id])
}.to change(Spree::Product, :count).by(1)
- .and change(Spree::Variant, :count).by(2) # master + variant
+ .and change(Spree::Variant, :count).by(1)
row.reload
variant_row.reload
expect(row.status).to eq('completed')
expect(variant_row.status).to eq('completed')
- product = row.item.product
+ product = row.item
expect(product.name).to eq('Test Product')
expect(variant_row.item.product).to eq(product)
expect(variant_row.item.sku).to eq('SKU2')
diff --git a/spree/core/spec/jobs/spree/media/migrate_product_assets_job_spec.rb b/spree/core/spec/jobs/spree/media/migrate_product_assets_job_spec.rb
index c27721ba6d..b8a0636867 100644
--- a/spree/core/spec/jobs/spree/media/migrate_product_assets_job_spec.rb
+++ b/spree/core/spec/jobs/spree/media/migrate_product_assets_job_spec.rb
@@ -6,7 +6,7 @@ RSpec.describe Spree::Media::MigrateProductAssetsJob, type: :job do
describe '#perform' do
context 'with master-pinned assets' do
let!(:product) { create(:product) }
- let!(:asset) { create(:image, viewable: product.master) }
+ let!(:asset) { create(:image, viewable: product.default_variant) }
it 'moves master-pinned assets to the product' do
expect { subject }
@@ -71,7 +71,7 @@ RSpec.describe Spree::Media::MigrateProductAssetsJob, type: :job do
context 'with mixed master + non-master assets' do
let!(:product) { create(:product) }
let!(:variant) { create(:variant, product: product) }
- let!(:master_asset) { create(:image, viewable: product.master) }
+ let!(:master_asset) { create(:image, viewable: product.default_variant) }
let!(:variant_asset) { create(:image, viewable: variant) }
it 'moves both, but only creates a join row for the non-master one' do
diff --git a/spree/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb b/spree/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb
index 54150c1503..3121e93acc 100644
--- a/spree/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb
+++ b/spree/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb
@@ -8,7 +8,7 @@ RSpec.describe Spree::Products::RefreshMetricsJob, type: :job do
subject { described_class.perform_now(product.id) }
context 'when the product has completed orders' do
- let!(:order) { create(:completed_order_with_totals, line_items_price: 50, store: store, variants: [product.master]) }
+ let!(:order) { create(:completed_order_with_totals, line_items_price: 50, store: store, variants: [product.default_variant]) }
it 'sets +units_sold_count+ and +revenue+ on the product from completed line items' do
subject
diff --git a/spree/core/spec/lib/tasks/media_spec.rb b/spree/core/spec/lib/tasks/media_spec.rb
index ece8275038..f297d56e89 100644
--- a/spree/core/spec/lib/tasks/media_spec.rb
+++ b/spree/core/spec/lib/tasks/media_spec.rb
@@ -21,7 +21,7 @@ describe 'spree:media:migrate_master_images_to_product_media' do
let!(:product_with_variant_image) { create(:product) }
let!(:variant) { create(:variant, product: product_with_variant_image) }
let!(:clean_product) { create(:product) }
- let!(:master_image) { create(:image, viewable: product_with_master_image.master) }
+ let!(:master_image) { create(:image, viewable: product_with_master_image.default_variant) }
let!(:variant_image) { create(:image, viewable: variant) }
it 'enqueues a job for each product with variant-pinned assets' do
diff --git a/spree/core/spec/models/concerns/spree/default_price_spec.rb b/spree/core/spec/models/concerns/spree/default_price_spec.rb
index 875d42e193..b28795a910 100644
--- a/spree/core/spec/models/concerns/spree/default_price_spec.rb
+++ b/spree/core/spec/models/concerns/spree/default_price_spec.rb
@@ -3,7 +3,7 @@ require 'spec_helper'
RSpec.describe Spree::DefaultPrice do
let(:store) { Spree::Store.default }
let(:product) { create(:product) }
- let(:variant) { product.master }
+ let(:variant) { product.default_variant }
describe 'with enable_legacy_default_price disabled (default)' do
before do
@@ -80,9 +80,9 @@ RSpec.describe Spree::DefaultPrice do
describe 'variant save without price' do
it 'allows saving a variant without any price' do
new_product = create(:product)
- master = new_product.master
- master.prices.destroy_all
- expect { master.save! }.not_to raise_error
+ default_variant = new_product.default_variant
+ default_variant.prices.destroy_all
+ expect { default_variant.save! }.not_to raise_error
end
end
diff --git a/spree/core/spec/models/spree/image_spec.rb b/spree/core/spec/models/spree/image_spec.rb
index 897fd5bc41..f0acce9a28 100644
--- a/spree/core/spec/models/spree/image_spec.rb
+++ b/spree/core/spec/models/spree/image_spec.rb
@@ -43,11 +43,11 @@ describe Spree::Image, type: :model do
let(:product) { create(:product) }
let!(:variants) { create_list(:variant, 2, product: product) }
- context 'when viewable is a master variant' do
- let(:viewable) { product.reload.master }
+ context 'when viewable is a product-level asset' do
+ let(:viewable) { product }
it 'touches product variants' do
- image.viewable.product.reload
+ image.viewable.reload
expect(image).to receive(:touch_product_variants)
image.set_list_position(2)
end
@@ -88,8 +88,8 @@ describe Spree::Image, type: :model do
let(:product) { create(:product) }
let(:variant) { create(:variant, product: product) }
- it 'increments media_count when image is created on master' do
- expect { create(:image, viewable: product.master) }.to change { product.reload.media_count }.by(1)
+ it 'increments media_count when image is created on the default variant' do
+ expect { create(:image, viewable: product.default_variant) }.to change { product.reload.media_count }.by(1)
end
it 'increments media_count when image is created on variant' do
@@ -103,7 +103,7 @@ describe Spree::Image, type: :model do
it 'tracks media across all variants correctly' do
expect(product.media_count).to eq(0)
- create(:image, viewable: product.master)
+ create(:image, viewable: product.default_variant)
create(:image, viewable: variant)
create(:image, viewable: variant)
expect(product.reload.media_count).to eq(3)
@@ -112,7 +112,7 @@ describe Spree::Image, type: :model do
describe 'primary_media_id updates' do
let(:product) { create(:product) }
- let(:variant) { product.master }
+ let(:variant) { product.default_variant }
it 'sets variant primary_media_id when first image is created' do
expect(variant.primary_media_id).to be_nil
diff --git a/spree/core/spec/models/spree/line_item_spec.rb b/spree/core/spec/models/spree/line_item_spec.rb
index c8f331c407..6fefecec60 100644
--- a/spree/core/spec/models/spree/line_item_spec.rb
+++ b/spree/core/spec/models/spree/line_item_spec.rb
@@ -267,8 +267,8 @@ describe Spree::LineItem, type: :model do
let(:currency) { 'EUR' }
let(:order) { create(:order, currency: currency) }
let(:product) { create(:product_in_stock) }
- let!(:line_item) { create(:line_item, order_id: order.id, currency: currency, product: product, variant: product.master) }
- let!(:price) { create(:price, currency: currency, variant: product.master, amount: 12) }
+ let!(:line_item) { create(:line_item, order_id: order.id, currency: currency, product: product, variant: product.default_variant) }
+ let!(:price) { create(:price, currency: currency, variant: product.default_variant, amount: 12) }
it 'copies over a variants differing price for another vat zone' do
line_item.price = 10
diff --git a/spree/core/spec/models/spree/price_list_spec.rb b/spree/core/spec/models/spree/price_list_spec.rb
index 45b065bb16..ea7b51d24a 100644
--- a/spree/core/spec/models/spree/price_list_spec.rb
+++ b/spree/core/spec/models/spree/price_list_spec.rb
@@ -219,7 +219,7 @@ describe Spree::PriceList, type: :model do
it 'creates prices for all supported currencies' do
price_list.add_products([product1.id])
- currencies = price_list.prices.where(variant_id: product1.master.id).pluck(:currency)
+ currencies = price_list.prices.where(variant_id: product1.default_variant.id).pluck(:currency)
expect(currencies).to match_array(%w[USD EUR GBP])
end
@@ -230,7 +230,7 @@ describe Spree::PriceList, type: :model do
end
it 'does not create duplicate prices for existing variants' do
- price_list.prices.create!(variant: product1.master, currency: 'USD', amount: nil)
+ price_list.prices.create!(variant: product1.default_variant, currency: 'USD', amount: nil)
expect {
price_list.add_products([product1.id])
@@ -240,7 +240,7 @@ describe Spree::PriceList, type: :model do
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])
+ }.to have_enqueued_job(Spree::Variants::TouchJob).with([product1.default_variant.id])
end
it 'touches the price list to bust cache' do
@@ -291,13 +291,13 @@ describe Spree::PriceList, type: :model do
context 'when price already has amount set' do
before do
- price_list.prices.create!(variant: product1.master, currency: 'USD', amount: 49.99)
+ price_list.prices.create!(variant: product1.default_variant, 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')
+ price = price_list.prices.find_by(variant_id: product1.default_variant.id, currency: 'USD')
expect(price.amount).to eq(49.99)
end
@@ -376,7 +376,7 @@ describe Spree::PriceList, type: :model do
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])
+ }.to have_enqueued_job(Spree::Variants::TouchJob).with([product1.default_variant.id])
end
it 'touches the price list to bust cache' do
@@ -400,7 +400,7 @@ describe Spree::PriceList, type: :model do
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 = price_list.prices.find_by(variant_id: product1.default_variant.id, currency: 'USD')
price.update!(amount: 19.99)
# Remove product
@@ -412,7 +412,7 @@ describe Spree::PriceList, type: :model do
}.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])
+ expect(price_list.prices.where(variant_id: product1.default_variant.id).pluck(:amount).uniq).to eq([nil])
end
end
end
@@ -421,8 +421,8 @@ describe Spree::PriceList, type: :model do
let(:store) { create(:store, supported_currencies: 'USD,EUR') }
let(:price_list) { create(:price_list, store: store) }
let(:product) { create(:product) }
- 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) }
+ let!(:price1) { create(:price, variant: product.default_variant, price_list: price_list, currency: 'USD', amount: nil) }
+ let!(:price2) { create(:price, variant: product.default_variant, price_list: price_list, currency: 'EUR', amount: nil) }
it 'updates prices in bulk using upsert_all' do
prices_attributes = [
diff --git a/spree/core/spec/models/spree/product/scopes_spec.rb b/spree/core/spec/models/spree/product/scopes_spec.rb
index 8369d84580..4d51df38b7 100644
--- a/spree/core/spec/models/spree/product/scopes_spec.rb
+++ b/spree/core/spec/models/spree/product/scopes_spec.rb
@@ -30,7 +30,7 @@ describe 'Product scopes', type: :model do
end
context 'different currency' do
- let!(:price_eur) { create(:price, variant: product.master, currency: 'EUR') }
+ let!(:price_eur) { create(:price, variant: product.default_variant, currency: 'EUR') }
let!(:product_2) { create(:product) }
it { expect(Spree::Product.available(nil, 'EUR')).to include(product) }
@@ -243,7 +243,7 @@ describe 'Product scopes', type: :model do
end
# Regression test: in_stock combined with price sorting scopes should not
- # raise table alias conflicts (variants_including_masters_spree_products)
+ # raise table alias conflicts (variants_spree_products)
it 'can be chained with price sorting scopes without error' do
expect { Spree::Product.in_stock.descend_by_price.to_a }.not_to raise_error
expect { Spree::Product.in_stock.ascend_by_price.to_a }.not_to raise_error
@@ -281,13 +281,13 @@ describe 'Product scopes', type: :model do
context 'with completed orders' do
before do
# Product 2: 3 units sold (3 orders x 1 quantity each)
- create_list(:completed_order_with_totals, 3, line_items_price: 100, store: store, variants: [product_2.master])
+ create_list(:completed_order_with_totals, 3, line_items_price: 100, store: store, variants: [product_2.default_variant])
# Product 1: 2 units sold (2 orders x 1 quantity each)
- create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
+ create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.default_variant])
# Product 3: 1 unit sold (1 order x 1 quantity)
- create(:completed_order_with_totals, line_items_price: 150, store: store, variants: [product_3.master])
+ create(:completed_order_with_totals, line_items_price: 150, store: store, variants: [product_3.default_variant])
# Product 4: no completed orders
@@ -308,11 +308,11 @@ describe 'Product scopes', type: :model do
context 'with incomplete orders' do
before do
# Product 1: 2 units sold (2 completed orders)
- create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
+ create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.default_variant])
# Product 2: 1 unit sold (1 completed order) + 2 incomplete orders (should not be counted)
- create(:completed_order_with_totals, line_items_price: 100, store: store, variants: [product_2.master])
- create_list(:order_with_totals, 2, line_items_price: 100, store: store, variants: [product_2.master])
+ create(:completed_order_with_totals, line_items_price: 100, store: store, variants: [product_2.default_variant])
+ create_list(:order_with_totals, 2, line_items_price: 100, store: store, variants: [product_2.default_variant])
refresh_all_metrics!
end
@@ -333,10 +333,10 @@ describe 'Product scopes', type: :model do
before do
# Both products have 2 units sold, but different revenue
# Product 1: 2 units, lower revenue
- create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
+ create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.default_variant])
# Product 2: 2 units, higher revenue
- create_list(:completed_order_with_totals, 2, line_items_price: 150, store: store, variants: [product_2.master])
+ create_list(:completed_order_with_totals, 2, line_items_price: 150, store: store, variants: [product_2.default_variant])
refresh_all_metrics!
end
@@ -358,13 +358,13 @@ describe 'Product scopes', type: :model do
before do
# Product 1: 5 units sold (quantity 2 + quantity 3)
order1 = create(:order_with_line_items, line_items_count: 0, store: store)
- create(:line_item, order: order1, variant: product_1.master, price: 50, quantity: 2)
- create(:line_item, order: order1, variant: product_1.master, price: 50, quantity: 3)
+ create(:line_item, order: order1, variant: product_1.default_variant, price: 50, quantity: 2)
+ create(:line_item, order: order1, variant: product_1.default_variant, price: 50, quantity: 3)
order1.update!(completed_at: Time.current)
# Product 2: 2 units sold (quantity 2)
order2 = create(:order_with_line_items, line_items_count: 0, store: store)
- create(:line_item, order: order2, variant: product_2.master, price: 100, quantity: 2)
+ create(:line_item, order: order2, variant: product_2.default_variant, price: 100, quantity: 2)
order2.update!(completed_at: Time.current)
refresh_all_metrics!
@@ -390,16 +390,16 @@ describe 'Product scopes', type: :model do
before do
# Product 1: 5 units sold across 2 orders (quantity 3 + quantity 2)
order1 = create(:order_with_line_items, line_items_count: 0, store: store)
- create(:line_item, order: order1, variant: product_1.master, price: 50, quantity: 3)
+ create(:line_item, order: order1, variant: product_1.default_variant, price: 50, quantity: 3)
order1.update!(completed_at: Time.current)
order2 = create(:order_with_line_items, line_items_count: 0, store: store)
- create(:line_item, order: order2, variant: product_1.master, price: 50, quantity: 2)
+ create(:line_item, order: order2, variant: product_1.default_variant, price: 50, quantity: 2)
order2.update!(completed_at: Time.current)
# Product 2: 4 units sold in 1 order (quantity 4)
order3 = create(:order_with_line_items, line_items_count: 0, store: store)
- create(:line_item, order: order3, variant: product_2.master, price: 100, quantity: 4)
+ create(:line_item, order: order3, variant: product_2.default_variant, price: 100, quantity: 4)
order3.update!(completed_at: Time.current)
refresh_all_metrics!
@@ -442,14 +442,14 @@ describe 'Product scopes', type: :model do
context 'with products having only pending orders (no completed_at)' do
before do
# Product 1: 2 units sold (2 completed orders)
- create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.master])
+ create_list(:completed_order_with_totals, 2, line_items_price: 100, store: store, variants: [product_1.default_variant])
# Product 2: 1 pending order (no completed_at) - should not be counted
- create(:order_with_line_items, line_items_count: 1, store: store, variants: [product_2.master])
+ create(:order_with_line_items, line_items_count: 1, store: store, variants: [product_2.default_variant])
# Product 3: 2 pending orders (not counted) + 1 completed order (1 unit)
- create_list(:order_with_line_items, 2, line_items_count: 1, store: store, variants: [product_3.master])
- create(:completed_order_with_totals, line_items_price: 100, store: store, variants: [product_3.master])
+ create_list(:order_with_line_items, 2, line_items_count: 1, store: store, variants: [product_3.default_variant])
+ create(:completed_order_with_totals, line_items_price: 100, store: store, variants: [product_3.default_variant])
# Product 4: no orders at all
diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rb
index 1fa01f5624..e80512c303 100644
--- a/spree/core/spec/models/spree/product_spec.rb
+++ b/spree/core/spec/models/spree/product_spec.rb
@@ -72,41 +72,33 @@ describe Spree::Product, type: :model do
let(:product) { create(:product) }
let(:variant) { create(:variant, product: product) }
+ # Baseline: put every variant out of stock and non-backorderable.
+ def all_variants_unavailable(product)
+ product.reload.variants.each do |v|
+ v.stock_items.update_all(count_on_hand: 0, backorderable: false)
+ end
+ end
+
%w[purchasable backorderable in_stock].each do |method_name|
describe "#{method_name}?" do
- context 'with variants' do
- it "returns false if no variant is #{method_name.humanize.downcase} even if master is" do
- variant.stock_items.update_all(backorderable: false) if %w[purchasable backorderable].include?(method_name)
- variant.stock_items.update_all(count_on_hand: 0) if method_name == 'in_stock'
-
- product.master.stock_items.where(variant: product.master).update_all(backorderable: true) if %w[purchasable backorderable].include?(method_name)
- product.master.stock_items.where(variant: product.master).update_all(count_on_hand: 10) if method_name == 'in_stock'
-
- expect(product.reload.send("#{method_name}?")).to eq false
- end
-
- it "returns true if variant is #{method_name.humanize.downcase}" do
- variant.stock_items.update_all(backorderable: true) if %w[purchasable backorderable].include?(method_name)
- variant.stock_items.update_all(count_on_hand: 10) if method_name == 'in_stock'
+ it "is false when no variant is #{method_name.humanize.downcase}" do
+ variant # add a second variant alongside the default
+ all_variants_unavailable(product)
- expect(product.reload.send("#{method_name}?")).to eq true
- end
+ expect(product.reload.send("#{method_name}?")).to eq false
end
- context 'without variants' do
- it "returns false if master is not #{method_name.humanize.downcase}" do
- product.master.stock_items.update_all(backorderable: false) if %w[purchasable backorderable].include?(method_name)
- product.master.stock_items.update_all(count_on_hand: 0) if method_name == 'in_stock'
+ it "is true when a variant is #{method_name.humanize.downcase}" do
+ variant
+ all_variants_unavailable(product)
- expect(product.reload.send("#{method_name}?")).to eq false
+ if method_name == 'in_stock'
+ variant.stock_items.update_all(count_on_hand: 10)
+ else
+ variant.stock_items.update_all(backorderable: true)
end
- it "returns true if master is #{method_name.humanize.downcase}" do
- product.master.stock_items.update_all(backorderable: true) if %w[purchasable backorderable].include?(method_name)
- product.master.stock_items.update_all(count_on_hand: 10) if method_name == 'in_stock'
-
- expect(product.reload.send("#{method_name}?")).to eq true
- end
+ expect(product.reload.send("#{method_name}?")).to eq true
end
end
end
@@ -123,7 +115,7 @@ describe Spree::Product, type: :model do
clone = duplicate_result.value
expect(clone.name).to eq("COPY OF #{product.name}")
expect(clone.slug).to eq("copy-of-#{product.slug}")
- expect(clone.master.sku).to eq("COPY OF #{product.master.sku}")
+ expect(clone.default_variant.sku).to eq("COPY OF #{product.default_variant.sku}")
expect(clone.taxons).to eq(product.taxons)
expect(clone.store).to eq(product.store)
expect(clone.images.size).to eq(product.images.size)
@@ -152,55 +144,46 @@ describe Spree::Product, type: :model do
end
end
- context 'master variant' do
- context 'when master variant changed' do
- before do
- product.master.sku = 'Something changed'
- end
+ context 'default variant' do
+ context 'when a delegated attribute changed' do
+ before { product.sku = 'Something changed' }
- it 'saves the master' do
+ it 'persists the default variant on save' do
product.save
- expect(product.master.reload.sku).to eq('Something changed')
+ expect(product.default_variant.reload.sku).to eq('Something changed')
end
end
+ end
- context 'when master default price changed', enable_legacy_default_price: true do
- before do
- allow(Spree::Config).to receive(:enable_legacy_default_price).and_return(true)
- master = product.master.reload
- master.default_price.price = 11
- master.save!
- product.master.reload.default_price.price = 12
- end
+ describe '#master_id' do
+ it 'returns the id of the default variant' do
+ expect(product.master_id).to eq(product.default_variant_id)
+ end
+ end
- it 'saves the master' do
- expect(product.master).to receive(:save!)
- product.save
- end
+ describe '#master' do
+ before { allow(Spree::Deprecation).to receive(:warn) }
- it 'saves the default price' do
- expect(product.master.default_price).to receive(:save)
- product.save
- end
+ it 'returns the default variant' do
+ expect(product.master).to eq(product.default_variant)
end
- context "when master variant and price haven't changed" do
- it 'does not save the master' do
- expect(product.master).not_to receive(:save!)
- product.save
- end
+ it 'emits a deprecation warning' do
+ product.master
+ expect(Spree::Deprecation).to have_received(:warn).with(/Spree::Product#master is deprecated/)
end
end
- describe '#master_id' do
- it 'returns the id of the master variant' do
- expect(product.master_id).to eq(product.master.id)
+ describe '#variants_including_master' do
+ before { allow(Spree::Deprecation).to receive(:warn) }
+
+ it 'returns the variants' do
+ expect(product.variants_including_master.to_a).to eq(product.variants.to_a)
end
- it 'returns nil when master is not present' do
- product_without_master = build(:product)
- product_without_master.master = nil
- expect(product_without_master.master_id).to be_nil
+ it 'emits a deprecation warning' do
+ product.variants_including_master
+ expect(Spree::Deprecation).to have_received(:warn).with(/Spree::Product#variants_including_master is deprecated/)
end
end
@@ -209,7 +192,7 @@ describe Spree::Product, type: :model do
it 'sets deleted_at value' do
product.destroy
expect(product.deleted_at).not_to be_nil
- expect(product.master.reload.deleted_at).not_to be_nil
+ expect(product.default_variant.reload.deleted_at).not_to be_nil
end
end
end
@@ -223,7 +206,7 @@ describe Spree::Product, type: :model do
it 'sets deleted_at value' do
product.destroy
expect(product.deleted_at).not_to be_nil
- expect(product.variants_including_master.all? { |v| !v.deleted_at.nil? }).to be true
+ expect(product.variants.all? { |v| !v.deleted_at.nil? }).to be true
end
end
end
@@ -245,11 +228,11 @@ describe Spree::Product, type: :model do
context 'with currency set to JPY' do
before do
- product.master.set_price('JPY', 11)
+ product.default_variant.set_price('JPY', 11)
end
it 'displays the currency in yen' do
- expect(product.master.price_in('JPY').display_amount.to_s).to eq('¥11')
+ expect(product.default_variant.price_in('JPY').display_amount.to_s).to eq('¥11')
end
end
end
@@ -278,7 +261,7 @@ describe Spree::Product, type: :model do
end
it 'is false' do
- product.variants_including_master.each { |v| v.stock_items.update_all count_on_hand: 0, backorderable: false }
+ product.variants.each { |v| v.stock_items.update_all count_on_hand: 0, backorderable: false }
expect(product.can_supply?).to be(false)
end
end
@@ -295,7 +278,7 @@ describe Spree::Product, type: :model do
end
context 'has stock movements' do
- let(:variant) { product.master }
+ let(:variant) { product.default_variant }
let(:stock_item) { variant.stock_items.first }
it 'doesnt raise ReadOnlyRecord error' do
@@ -307,7 +290,7 @@ describe Spree::Product, type: :model do
# Regression test for #3737
context 'has stock items' do
it 'can retrieve stock items' do
- expect(product.master.stock_items.first).not_to be_nil
+ expect(product.default_variant.stock_items.first).not_to be_nil
expect(product.stock_items.first).not_to be_nil
end
end
@@ -458,14 +441,6 @@ describe Spree::Product, type: :model do
create(:prototype, name: 'Size', option_types: [size])
end
- let(:option_values_hash) do
- hash = {}
- prototype.option_types.each do |i|
- hash[i.id.to_s] = i.option_value_ids
- end
- hash
- end
-
it 'creates option types based on the prototype' do
product.save
expect(product.option_type_ids.length).to eq(1)
@@ -476,45 +451,52 @@ describe Spree::Product, type: :model do
product.save
expect(product.product_option_types.pluck(:option_type_id)).to eq(prototype.option_type_ids)
end
+ end
+
+ context 'when track inventory is disabled' do
+ let(:product) { build(:product, track_inventory: false) }
- it 'creates variants from an option values hash with one option type' do
- product.option_values_hash = option_values_hash
+ it 'creates a default stock item' do
product.save
- expect(product.variants.length).to eq(3)
+ expect(product.default_variant.track_inventory?).to eq(false)
+ expect(product.default_variant.stock_items.count).to eq(1)
+ expect(product.default_variant.stock_items.first.count_on_hand).to eq(0)
+ expect(product.default_variant.stock_items.first.backorderable).to eq(false)
end
+ end
- it 'stills create variants when option_values_hash is given but prototype id is nil' do
- product.option_values_hash = option_values_hash
- product.prototype_id = nil
- product.save
- product.reload
- expect(product.option_type_ids.length).to eq(1)
- expect(product.option_type_ids).to eq(prototype.option_type_ids)
- expect(product.variants.length).to eq(3)
+ context 'a simple product (no variants supplied)' do
+ let(:product) { create(:empty_product) }
+
+ it 'auto-creates a single option-less default variant' do
+ expect(product.variants.count).to eq(1)
+ expect(product.default_variant).to eq(product.variants.first)
+ expect(product.default_variant.option_values).to be_empty
end
- it 'creates variants from an option values hash with multiple option types' do
- color = build_option_type_with_values('color', %w(Red Green Blue))
- logo = build_option_type_with_values('logo', %w(Ruby Rails Nginx))
- option_values_hash[color.id.to_s] = color.option_value_ids
- option_values_hash[logo.id.to_s] = logo.option_value_ids
- product.option_values_hash = option_values_hash
- product.save
- product.reload
- expect(product.option_type_ids.length).to eq(3)
- expect(product.variants.length).to eq(27)
+ it 'persists default_variant_id' do
+ expect(product.reload.default_variant_id).to eq(product.variants.first.id)
end
end
- context 'when track inventory is disabled' do
- let(:product) { build(:product, track_inventory: false) }
+ context 'a product supplied with nested variants' do
+ let(:product) do
+ build(:empty_product).tap do |p|
+ p.variants = [
+ { sku: 'TEE-S', options: [{ name: 'size', value: 'Small' }] },
+ { sku: 'TEE-M', options: [{ name: 'size', value: 'Medium' }] }
+ ]
+ p.save!
+ end
+ end
- it 'creates a default stock item' do
- product.save
- expect(product.master.track_inventory?).to eq(false)
- expect(product.master.stock_items.count).to eq(1)
- expect(product.master.stock_items.first.count_on_hand).to eq(0)
- expect(product.master.stock_items.first.backorderable).to eq(false)
+ it 'creates exactly the supplied variants — no phantom default' do
+ expect(product.variants.pluck(:sku)).to contain_exactly('TEE-S', 'TEE-M')
+ end
+
+ it 'uses the first supplied variant as the default' do
+ expect(product.reload.default_variant).to eq(product.variants.order(:position).first)
+ expect(product.default_variant.sku).to eq('TEE-S')
end
end
end
@@ -522,7 +504,7 @@ describe Spree::Product, type: :model do
describe '#images' do
let(:product) { create(:product) }
let(:file) { File.open(File.expand_path('../../fixtures/thinking-cat.jpg', __dir__)) }
- let(:params) { { viewable_id: product.master.id, viewable_type: 'Spree::Variant', alt: 'position 2', position: 2 } }
+ let(:params) { { viewable_id: product.default_variant.id, viewable_type: 'Spree::Variant', alt: 'position 2', position: 2 } }
before do
images = [
@@ -564,28 +546,28 @@ describe Spree::Product, type: :model do
it 'is infinite if track_inventory_levels is false' do
allow(Spree::Config).to receive(:track_inventory_levels).and_return(false)
- expect(build(:product, variants_including_master: [build(:master_variant)]).total_on_hand).to eql(Float::INFINITY)
+ expect(build(:product).total_on_hand).to eql(Float::INFINITY)
end
it 'is infinite if variant is on demand' do
allow(Spree::Config).to receive(:track_inventory_levels).and_return(true)
- expect(build(:product, variants_including_master: [build(:on_demand_master_variant)]).total_on_hand).to eql(Float::INFINITY)
+ expect(build(:product, track_inventory: false).total_on_hand).to eql(Float::INFINITY)
end
it 'returns sum of stock items count_on_hand' do
product.stock_items.first.set_count_on_hand 5
- product.variants_including_master.reload # force load association
+ product.variants.reload # force load association
expect(product.total_on_hand).to be(5)
end
- it 'returns sum of stock items count_on_hand when variants_including_master is not loaded' do
+ it 'returns sum of stock items count_on_hand when variants are not loaded' do
product.stock_items.first.set_count_on_hand 5
expect(product.reload.total_on_hand).to be(5)
end
end
# Regression spec for https://github.com/spree/spree/issues/5588
- describe '#validate_master when duplicate SKUs entered' do
+ describe 'when duplicate SKUs are entered' do
subject { second_product }
let!(:first_product) { create(:product, sku: 'a-sku') }
@@ -594,11 +576,6 @@ describe Spree::Product, type: :model do
it { is_expected.to be_invalid }
end
- it 'initializes a master variant when building a product' do
- product = store.products.new
- expect(product.master.is_master).to be true
- end
-
describe '#discontinue!' do
let(:product) { create(:product, sku: 'a-sku') }
@@ -673,7 +650,7 @@ describe Spree::Product, type: :model do
describe '#ensure_not_in_complete_orders' do
let!(:order) { create(:completed_order_with_totals) }
let(:product) { create(:product) }
- let!(:line_item) { create(:line_item, order: order, variant: product.master, product: product) }
+ let!(:line_item) { create(:line_item, order: order, variant: product.default_variant, product: product) }
it 'adds error on product destroy' do
expect(product.destroy).to eq false
@@ -684,60 +661,41 @@ describe Spree::Product, type: :model do
describe '#default_variant' do
let(:product) { create(:product) }
- context 'track inventory levels' do
- context 'product has variants' do
- let!(:variant_1) { create(:variant, product: product, position: 1) }
- let!(:variant_2) { create(:variant, product: product, position: 2) }
-
- before do
- variant_1.stock_items.first.update(backorderable: false, count_on_hand: 0)
- variant_2.stock_items.first.update(backorderable: false, count_on_hand: 0)
- end
+ it 'is the sole variant for a simple product' do
+ expect(product.reload.default_variant).to eq(product.variants.first)
+ end
- context 'in stock' do
- before { variant_2.stock_items.first.adjust_count_on_hand(1) }
+ it 'stays fixed (sticky) when other variants are added, regardless of stock' do
+ default = product.default_variant
+ create(:variant, product: product)
- it 'returns first non-master in stock variant' do
- expect(product.reload.default_variant).to eq(variant_2)
- end
- end
+ expect(product.reload.default_variant).to eq(default)
+ end
- context 'backorderable' do
- before { variant_2.stock_items.first.update(backorderable: true) }
+ context 'when the default variant is removed' do
+ let!(:other) { create(:variant, product: product) }
- it 'returns first non-master backorderable variant' do
- expect(product.reload.default_variant).to eq(variant_2)
- end
- end
+ it 'auto-promotes the next remaining variant' do
+ product.default_variant.destroy
+ product.save
- context 'product without variants in stock or backorerable' do
- it 'returns first non-master variant' do
- expect(product.reload.default_variant).to eq(variant_1)
- end
- end
+ expect(product.reload.default_variant).to eq(other)
end
+ end
- context 'without tracking inventory levels' do
- let!(:variant_1) { create(:variant, product: product, position: 1) }
- let!(:variant_2) { create(:variant, product: product, position: 2) }
-
- before do
- Spree::Config[:track_inventory_levels] = false
- variant_1.stock_items.first.update(backorderable: false, count_on_hand: 0)
- variant_2.stock_items.first.update(backorderable: false, count_on_hand: 0)
- end
-
- after { Spree::Config[:track_inventory_levels] = true }
-
- it 'returns first non-master variant' do
- expect(product.reload.default_variant).to eq(variant_1)
- end
- end
+ context 'before the product is persisted' do
+ # The FK is only set after_create, so pre-save the method falls back to the
+ # in-memory variant. This keeps every delegated setter writing to a single
+ # variant instead of building a new one per attribute.
+ it 'converges delegated setters onto a single in-memory variant' do
+ product = build(:empty_product)
+ product.sku = 'PENDING'
+ product.price = 10
+ product.weight = 2
- context 'product without variants' do
- it 'returns master variant' do
- expect(product.reload.default_variant).to eq(product.master)
- end
+ expect(product.variants.size).to eq(1)
+ expect(product.default_variant).to eq(product.variants.first)
+ expect(product.default_variant.sku).to eq('PENDING')
end
end
end
@@ -745,28 +703,18 @@ describe Spree::Product, type: :model do
describe '#default_variant_id' do
let(:product) { create(:product) }
- context 'product has variants' do
- let!(:variant) { create(:variant, product: product) }
-
- it 'returns first non-master variant ID' do
- expect(product.reload.default_variant_id).to eq(variant.id)
- end
- end
-
- context 'product without variants' do
- it 'returns master variant ID' do
- expect(product.reload.default_variant_id).to eq(product.master.id)
- end
+ it 'returns the default variant id' do
+ expect(product.reload.default_variant_id).to eq(product.variants.first.id)
end
end
describe '#primary_media' do
let(:product) { create(:product) }
- context 'when master has images' do
- let!(:image) { create(:image, viewable: product.master) }
+ context 'when default variant has images' do
+ let!(:image) { create(:image, viewable: product.default_variant) }
- it 'returns the master image' do
+ it 'returns the default variant image' do
expect(product.reload.primary_media).to eq(image)
end
@@ -774,13 +722,13 @@ describe Spree::Product, type: :model do
let!(:variant) { create(:variant, product: product) }
let!(:variant_image) { create(:image, viewable: variant) }
- it 'returns the master image (master takes priority)' do
+ it 'returns the default variant image (default variant takes priority)' do
expect(product.reload.primary_media).to eq(image)
end
end
end
- context 'when master has no images but variant does' do
+ context 'when default variant has no images but variant does' do
let!(:variant) { create(:variant, product: product) }
let!(:variant_image) { create(:image, viewable: variant) }
@@ -805,7 +753,7 @@ describe Spree::Product, type: :model do
end
it 'does not include variant images' do
- variant_image = create(:image, viewable: product.master)
+ variant_image = create(:image, viewable: product.default_variant)
expect(product.media).not_to include(variant_image)
end
@@ -821,12 +769,12 @@ describe Spree::Product, type: :model do
it 'returns product media when present' do
product_image = create(:image, viewable: product)
- create(:image, viewable: product.master)
+ create(:image, viewable: product.default_variant)
expect(product.reload.gallery_media).to include(product_image)
end
it 'falls back to variant_images when no product media' do
- variant_image = create(:image, viewable: product.master)
+ variant_image = create(:image, viewable: product.default_variant)
expect(product.reload.gallery_media).to include(variant_image)
end
end
@@ -840,7 +788,7 @@ describe Spree::Product, type: :model do
end
it 'falls back to variant images when no product media' do
- variant_image = create(:image, viewable: product.master)
+ variant_image = create(:image, viewable: product.default_variant)
product.update_thumbnail!
expect(product.reload.primary_media_id).to eq(variant_image.id)
end
@@ -855,8 +803,8 @@ describe Spree::Product, type: :model do
end
end
- context 'when master has images' do
- let!(:image) { create(:image, viewable: product.master) }
+ context 'when default variant has images' do
+ let!(:image) { create(:image, viewable: product.default_variant) }
it 'returns true' do
expect(product.reload.has_variant_images?).to be true
@@ -873,7 +821,7 @@ describe Spree::Product, type: :model do
end
context 'when variant_images are preloaded' do
- let!(:image) { create(:image, viewable: product.master) }
+ let!(:image) { create(:image, viewable: product.default_variant) }
it 'uses loaded association' do
loaded_product = Spree::Product.includes(:variant_images).find(product.id)
@@ -902,17 +850,6 @@ describe Spree::Product, type: :model do
end
end
- context 'when master has images but default_variant does not' do
- let!(:variant) { create(:variant, product: product) }
- let!(:image) { create(:image, viewable: product.master) }
-
- it 'returns true (checks all variants)' do
- product.reload
- expect(product.default_variant).to eq(variant)
- expect(product.has_images?).to be true
- end
- end
-
context 'when any variant has images' do
let!(:variant) { create(:variant, product: product) }
let!(:image) { create(:image, viewable: variant) }
@@ -932,8 +869,8 @@ describe Spree::Product, type: :model do
end
end
- context 'when master has media' do
- let!(:images) { create_list(:image, 2, viewable: product.master) }
+ context 'when default variant has media' do
+ let!(:images) { create_list(:image, 2, viewable: product.default_variant) }
it 'returns total media count' do
expect(product.reload.media_count).to eq(2)
@@ -968,31 +905,21 @@ describe Spree::Product, type: :model do
end
end
- context 'when master has images' do
- let!(:image) { create(:image, viewable: product.master) }
+ context 'when the default variant has images' do
+ let!(:image) { create(:image, viewable: product.default_variant) }
- it 'returns master' do
- expect(product.reload.variant_for_images).to eq(product.master)
- end
- end
-
- context 'when only default_variant has images' do
- let!(:variant) { create(:variant, product: product) }
- let!(:image) { create(:image, viewable: variant) }
-
- it 'returns default_variant' do
- expect(product.reload.variant_for_images).to eq(variant)
+ it 'returns the default variant' do
+ expect(product.reload.variant_for_images).to eq(product.default_variant)
end
end
context 'when only a non-default variant has images' do
- let!(:variant1) { create(:variant, product: product) }
let!(:variant2) { create(:variant, product: product) }
let!(:image) { create(:image, viewable: variant2) }
it 'returns the variant with images' do
product.reload
- expect(product.default_variant).to eq(variant1)
+ expect(product.default_variant.has_media?).to be false
expect(product.variant_for_images).to eq(variant2)
end
end
@@ -1008,7 +935,7 @@ describe Spree::Product, type: :model do
end
context 'when variant has only one image' do
- let!(:image) { create(:image, viewable: product.master) }
+ let!(:image) { create(:image, viewable: product.default_variant) }
it 'returns nil' do
expect(product.reload.secondary_image).to be_nil
@@ -1016,15 +943,15 @@ describe Spree::Product, type: :model do
end
context 'when variant has multiple images' do
- let!(:image1) { create(:image, viewable: product.master, position: 1) }
- let!(:image2) { create(:image, viewable: product.master, position: 2) }
+ let!(:image1) { create(:image, viewable: product.default_variant, position: 1) }
+ let!(:image2) { create(:image, viewable: product.default_variant, position: 2) }
it 'returns the second image' do
expect(product.reload.secondary_image).to eq(image2)
end
end
- context 'when images are on a non-master variant' do
+ context 'when images are on a option variant' do
let!(:variant) { create(:variant, product: product) }
let!(:image1) { create(:image, viewable: variant, position: 1) }
let!(:image2) { create(:image, viewable: variant, position: 2) }
@@ -1043,9 +970,8 @@ describe Spree::Product, type: :model do
let(:storefront_includes) do
[
- :prices_including_master,
- { master: [:images, :prices],
- variants: [:images, :prices, :option_values] }
+ :prices,
+ { variants: [:images, :prices, :option_values] }
]
end
@@ -1057,18 +983,10 @@ describe Spree::Product, type: :model do
expect(loaded_product.has_images?).to be true
end
- context 'when image is on non-default variant' do
- let!(:variant2) { create(:variant, product: product) }
-
- before do
- variant.stock_items.update_all(count_on_hand: 0, backorderable: false)
- variant2.stock_items.update_all(count_on_hand: 10, backorderable: true)
- end
-
- it 'returns image from non-default variant' do
+ context 'when the image is on a non-default variant' do
+ it 'still finds the image through variant_for_images' do
loaded_product = Spree::Product.includes(*storefront_includes).find(product.id)
- expect(loaded_product.default_variant).to eq(variant2)
expect(loaded_product.variant_for_images).to eq(variant)
expect(loaded_product.primary_media).to eq(image)
end
@@ -1134,11 +1052,11 @@ describe Spree::Product, type: :model do
let!(:product) { create(:product) }
let(:stock_item) { variant.stock_items.first }
- context 'when only master variant is in stock or backorderable' do
+ context 'when only default variant is in stock or backorderable' do
it { expect(subject).to eq(true) }
end
- context 'with more variants aside from the master variant' do
+ context 'with more variants aside from the default variant' do
# makes the stock items available for the before hook
let!(:variant) { create(:variant, product: product) }
@@ -1147,30 +1065,30 @@ describe Spree::Product, type: :model do
product.reload
end
- context 'with at least one non-master variant stock items count_on_hand > 0' do
+ context 'with at least one option variant stock items count_on_hand > 0' do
before do
- # make all stock items in stock, also for the master variant
+ # make all stock items in stock, also for the default variant
Spree::StockItem.all.each { |stock_item| stock_item.set_count_on_hand(1) }
end
it { expect(subject).to eq(true) }
end
- context 'when all non-master variant stock items have count_on_hand <= 0' do
+ context 'when all option variant stock items have count_on_hand <= 0' do
before { stock_item.set_count_on_hand(0) }
it { expect(subject).to eq(false) }
- context 'when all non-master variant stock items have track_inventory = false' do
+ context 'when all option variant stock items have track_inventory = false' do
before { variant.update(track_inventory: false) }
it { expect(subject).to be(true) }
end
- context 'when all non-master variant stock items have track_inventory = true' do
+ context 'when all option variant stock items have track_inventory = true' do
it { expect(subject).to eq(false) }
- context 'when all non-master variant stock items have backorderable = true' do
+ context 'when all option variant stock items have backorderable = true' do
before { stock_item.update(backorderable: true) }
it { expect(subject).to eq(true) }
@@ -1213,7 +1131,7 @@ describe Spree::Product, type: :model do
csv_line = csv_lines.first
expect(csv_line).to include(product.name)
- expect(csv_line).to include(product.master.sku)
+ expect(csv_line).to include(product.default_variant.sku)
end
end
@@ -1222,15 +1140,15 @@ describe Spree::Product, type: :model do
let!(:variant2) { create(:variant, product: product) }
before do
- product.master.update!(sku: 'test-product-master-sku')
+ product.default_variant.update!(sku: 'test-product-default-sku')
end
- it 'returns an array with CSV data for each variant including the master variant' do
+ it 'returns an array with CSV data for each variant including the default variant' do
csv_lines = product.reload.to_csv(store)
expect(csv_lines.size).to eq(3)
expect(csv_lines[0]).to include(product.name)
- expect(csv_lines[0]).to include('test-product-master-sku')
+ expect(csv_lines[0]).to include('test-product-default-sku')
expect(csv_lines[1]).not_to include(product.name)
expect(csv_lines[1]).to include(variant1.sku)
@@ -1251,7 +1169,7 @@ describe Spree::Product, type: :model do
before do
variant1.set_price('EUR', 52.99, 62.99)
- product.master.set_price('EUR', 10.99)
+ product.default_variant.set_price('EUR', 10.99)
allow(store).to receive(:supported_currencies_list).and_return(
[Money::Currency.find('USD'), Money::Currency.find('EUR')]
)
@@ -1260,7 +1178,7 @@ describe Spree::Product, type: :model do
it 'appends price-only rows for additional currencies' do
csv_lines = product.reload.to_csv(store)
- # 2 default currency rows (master + variant) + 2 EUR price-only rows
+ # 2 default currency rows (default variant + variant) + 2 EUR price-only rows
expect(csv_lines.size).to eq(4)
# First 2 rows are normal USD rows
@@ -1268,7 +1186,7 @@ describe Spree::Product, type: :model do
expect(csv_lines[1]).to include(variant1.sku)
# Last 2 rows are EUR price-only rows
- eur_master = csv_lines[2]
+ eur_default_variant = csv_lines[2]
eur_variant = csv_lines[3]
slug_idx = Spree::CSV::ProductVariantPresenter::CSV_HEADERS.index('slug')
@@ -1278,11 +1196,11 @@ describe Spree::Product, type: :model do
currency_idx = Spree::CSV::ProductVariantPresenter::CSV_HEADERS.index('currency')
name_idx = Spree::CSV::ProductVariantPresenter::CSV_HEADERS.index('name')
- expect(eur_master[slug_idx]).to eq product.slug
- expect(eur_master[sku_idx]).to eq product.master.sku
- expect(eur_master[price_idx]).to eq 10.99
- expect(eur_master[currency_idx]).to eq 'EUR'
- expect(eur_master[name_idx]).to be_nil
+ expect(eur_default_variant[slug_idx]).to eq product.slug
+ expect(eur_default_variant[sku_idx]).to eq product.default_variant.sku
+ expect(eur_default_variant[price_idx]).to eq 10.99
+ expect(eur_default_variant[currency_idx]).to eq 'EUR'
+ expect(eur_default_variant[name_idx]).to be_nil
expect(eur_variant[slug_idx]).to eq product.slug
expect(eur_variant[sku_idx]).to eq variant1.sku
@@ -1293,18 +1211,18 @@ describe Spree::Product, type: :model do
end
it 'skips variants without a price in the additional currency' do
- # variant1 has EUR price (from before block), master has EUR price too
+ # variant1 has EUR price (from before block), default variant has EUR price too
# We verify that only variants with EUR prices get EUR rows
csv_lines = product.reload.to_csv(store)
eur_lines = csv_lines.select { |row| row[Spree::CSV::ProductVariantPresenter::CSV_HEADERS.index('currency')] == 'EUR' }
usd_lines = csv_lines.select { |row| row[Spree::CSV::ProductVariantPresenter::CSV_HEADERS.index('currency')] == 'USD' }
- expect(usd_lines.size).to eq(2) # master + variant1
- expect(eur_lines.size).to eq(2) # master + variant1 (both have EUR prices)
+ expect(usd_lines.size).to eq(2) # default variant + variant1
+ expect(eur_lines.size).to eq(2) # default variant + variant1 (both have EUR prices)
- # Now remove the EUR price from master
- product.master.prices.base_prices.find_by(currency: 'EUR')&.destroy
+ # Now remove the EUR price from default variant
+ product.default_variant.prices.base_prices.find_by(currency: 'EUR')&.destroy
csv_lines = product.reload.to_csv(store)
eur_lines = csv_lines.select { |row| row[Spree::CSV::ProductVariantPresenter::CSV_HEADERS.index('currency')] == 'EUR' }
@@ -1378,7 +1296,7 @@ describe Spree::Product, type: :model do
context 'without variants' do
it 'returns the default variant' do
- expect(subject).to eq(product.master)
+ expect(subject).to eq(product.default_variant)
end
end
@@ -1410,7 +1328,7 @@ describe Spree::Product, type: :model do
end
it 'returns the first variant' do
- expect(subject).to eq(variant_1)
+ expect(subject).to eq(product.variants.first)
end
end
end
@@ -1480,17 +1398,17 @@ describe Spree::Product, type: :model do
context 'without variants' do
before do
- product.master.prices.where(currency: 'USD').delete_all
- product.master.prices.create(currency: currency, amount: 10)
+ product.default_variant.prices.where(currency: 'USD').delete_all
+ product.default_variant.prices.create(currency: currency, amount: 10)
end
- context 'when master variant is available' do
+ context 'when default variant is available' do
let(:currency) { 'USD' }
it { is_expected.to be(true) }
end
- context 'when master variant is not available' do
+ context 'when default variant is not available' do
let(:currency) { 'PLN' }
it { is_expected.to be(false) }
@@ -1667,14 +1585,14 @@ describe Spree::Product, type: :model do
let!(:product_no_price) { create(:product, name: 'No Price Product') }
before do
- product_cheap.master.prices.delete_all
- product_mid.master.prices.delete_all
- product_expensive.master.prices.delete_all
- product_no_price.master.prices.delete_all
+ product_cheap.default_variant.prices.delete_all
+ product_mid.default_variant.prices.delete_all
+ product_expensive.default_variant.prices.delete_all
+ product_no_price.default_variant.prices.delete_all
- create(:price, variant: product_cheap.master, amount: 10.00)
- create(:price, variant: product_mid.master, amount: 50.00)
- create(:price, variant: product_expensive.master, amount: 100.00)
+ create(:price, variant: product_cheap.default_variant, amount: 10.00)
+ create(:price, variant: product_mid.default_variant, amount: 50.00)
+ create(:price, variant: product_expensive.default_variant, amount: 100.00)
end
it 'orders products by minimum price ascending' do
@@ -1693,11 +1611,11 @@ describe Spree::Product, type: :model do
let!(:variant2) { create(:variant, product: product_with_variants) }
before do
- product_with_variants.master.prices.delete_all
+ product_with_variants.default_variant.prices.delete_all
variant1.prices.delete_all
variant2.prices.delete_all
- # Variant prices only (no master price)
+ # Variant prices only (no default variant price)
create(:price, variant: variant1, amount: 5.00)
create(:price, variant: variant2, amount: 15.00)
end
@@ -1717,14 +1635,14 @@ describe Spree::Product, type: :model do
let!(:product_no_price) { create(:product, name: 'No Price Product') }
before do
- product_cheap.master.prices.delete_all
- product_mid.master.prices.delete_all
- product_expensive.master.prices.delete_all
- product_no_price.master.prices.delete_all
+ product_cheap.default_variant.prices.delete_all
+ product_mid.default_variant.prices.delete_all
+ product_expensive.default_variant.prices.delete_all
+ product_no_price.default_variant.prices.delete_all
- create(:price, variant: product_cheap.master, amount: 10.00)
- create(:price, variant: product_mid.master, amount: 50.00)
- create(:price, variant: product_expensive.master, amount: 100.00)
+ create(:price, variant: product_cheap.default_variant, amount: 10.00)
+ create(:price, variant: product_mid.default_variant, amount: 50.00)
+ create(:price, variant: product_expensive.default_variant, amount: 100.00)
end
it 'orders products by maximum price descending' do
@@ -1743,11 +1661,11 @@ describe Spree::Product, type: :model do
let!(:variant2) { create(:variant, product: product_with_variants) }
before do
- product_with_variants.master.prices.delete_all
+ product_with_variants.default_variant.prices.delete_all
variant1.prices.delete_all
variant2.prices.delete_all
- # Variant prices only (no master price)
+ # Variant prices only (no default variant price)
create(:price, variant: variant1, amount: 200.00)
create(:price, variant: variant2, amount: 150.00)
end
@@ -1818,25 +1736,25 @@ describe Spree::Product, type: :model do
describe '#has_variants?' do
let(:product) { create(:product) }
- context 'without variants' do
+ context 'a simple product (only the default variant)' do
it 'returns false' do
expect(product.has_variants?).to be false
end
- it 'has variant_count of 0' do
- expect(product.variant_count).to eq 0
+ it 'has variant_count of 1' do
+ expect(product.reload.variant_count).to eq 1
end
end
- context 'with variants' do
+ context 'with additional variants' do
before { create(:variant, product: product) }
it 'returns true' do
expect(product.reload.has_variants?).to be true
end
- it 'has variant_count of 1' do
- expect(product.reload.variant_count).to eq 1
+ it 'has variant_count of 2' do
+ expect(product.reload.variant_count).to eq 2
end
end
@@ -1918,12 +1836,10 @@ describe Spree::Product, type: :model do
expect(new_product.variants.first.sku).to eq('DEF-1')
end
- it 'upserts an options-less entry onto the master rather than building a phantom non-master' do
- # Simple-product flow: the merchant edits SKU + price + weight on the
- # default variant (UI calls it "Default variant") without adding any
- # options. The payload ships a single variant with options:[]. The
- # backend must update the auto-created master and NOT create a
- # duplicate non-master variant.
+ it 'creates a single default variant from an options-less entry' do
+ # Simple-product flow: the merchant edits SKU + weight on the default
+ # variant without adding options. The payload ships a single variant
+ # with options:[] and the backend creates exactly that one variant.
new_product = Spree::Product.new(
name: 'Simple SKU',
shipping_category: shipping_category,
@@ -1932,9 +1848,9 @@ describe Spree::Product, type: :model do
)
new_product.save!
- expect(new_product.variants.count).to eq(0)
- expect(new_product.master.sku).to eq('SIMPLE-1')
- expect(new_product.master.weight).to eq(2)
+ expect(new_product.variants.count).to eq(1)
+ expect(new_product.default_variant.sku).to eq('SIMPLE-1')
+ expect(new_product.default_variant.weight).to eq(2)
end
end
@@ -1964,11 +1880,11 @@ describe Spree::Product, type: :model do
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.default_variant.sku).to eq('FV-1')
expect(new_product.price).to be_present
end
- it 'reflects an options-less master upsert in default_variant and price' do
+ it 'reflects an options-less default variant in default_variant and price' do
new_product = Spree::Product.new(
name: 'Fresh Simple',
shipping_category: shipping_category,
@@ -1977,8 +1893,8 @@ describe Spree::Product, type: :model do
)
new_product.save!
- expect(new_product.variant_count).to eq(0)
- expect(new_product.default_variant).to eq(new_product.master)
+ expect(new_product.variant_count).to eq(1)
+ expect(new_product.default_variant.sku).to eq('FS-1')
expect(new_product.price).to eq(15)
end
end
@@ -2025,6 +1941,7 @@ describe Spree::Product, type: :model do
existing.save!
variant = create(:variant, product: product)
+ product.reload # refresh the variants cache so the out-of-band variant resolves
product.media = [{ id: existing.prefixed_id, variant_ids: [variant.id] }]
diff --git a/spree/core/spec/models/spree/promotion/rules/product_spec.rb b/spree/core/spec/models/spree/promotion/rules/product_spec.rb
index 9fa1755b3a..32617b2642 100644
--- a/spree/core/spec/models/spree/promotion/rules/product_spec.rb
+++ b/spree/core/spec/models/spree/promotion/rules/product_spec.rb
@@ -96,8 +96,8 @@ describe Spree::Promotion::Rules::Product, type: :model do
let(:rule_product) { create(:product) }
let(:other_product) { create(:product) }
- let(:rule_line_item) { build(:line_item, variant: rule_product.master) }
- let(:other_line_item) { build(:line_item, variant: other_product.master) }
+ let(:rule_line_item) { build(:line_item, variant: rule_product.default_variant) }
+ let(:other_line_item) { build(:line_item, variant: other_product.default_variant) }
before do
allow(rule).to receive(:eligible_product_ids).and_return([rule_product.id])
diff --git a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
index 90e2bb9383..f92b54a4a7 100644
--- a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
@@ -235,7 +235,7 @@ module Spree
context 'and the product price is less than promo discount' do
let(:product_list) { create_list(:product, 3, tax_category: tax_category, price: 9.0) }
- before { product_list.each { |item| Spree::Cart::AddItem.call(order: order, variant: item.master) } }
+ before { product_list.each { |item| Spree::Cart::AddItem.call(order: order, variant: item.default_variant) } }
it 'successfully applies the promo' do
# 3 * (9 + 0.9)
@@ -251,7 +251,7 @@ module Spree
context 'and the product price is greater than promo discount' do
let(:product_list) { create_list(:product, 3, tax_category: tax_category, price: 11.0) }
- before { product_list.each { |item| Spree::Cart::AddItem.call(order: order, variant: item.master, quantity: 2) } }
+ before { product_list.each { |item| Spree::Cart::AddItem.call(order: order, variant: item.default_variant, quantity: 2) } }
it 'successfully applies the promo' do
# 3 * (22 + 2.2)
@@ -270,7 +270,7 @@ module Spree
before do
allow(order).to receive(:coupon_code).and_return '20off'
- product_list.each { |item| Spree::Cart::AddItem.call(order: order, variant: item.master, quantity: 2) }
+ product_list.each { |item| Spree::Cart::AddItem.call(order: order, variant: item.default_variant, quantity: 2) }
end
it 'successfully applies the promo' do
diff --git a/spree/core/spec/models/spree/reimbursement_spec.rb b/spree/core/spec/models/spree/reimbursement_spec.rb
index ce6123e729..14f2e49710 100644
--- a/spree/core/spec/models/spree/reimbursement_spec.rb
+++ b/spree/core/spec/models/spree/reimbursement_spec.rb
@@ -143,7 +143,7 @@ describe Spree::Reimbursement, type: :model do
context 'when exchange is required' do
# we need to have a variant that will pass eligibility checks
# so it needs to be a variant of the same product
- let!(:exchange_variant) { create(:variant, is_master: true, product: inventory_unit.variant.product) }
+ let!(:exchange_variant) { create(:variant, product: inventory_unit.variant.product) }
before { return_item.exchange_variant = exchange_variant }
diff --git a/spree/core/spec/models/spree/return_item/exchange_variant_eligibility/same_option_value_spec.rb b/spree/core/spec/models/spree/return_item/exchange_variant_eligibility/same_option_value_spec.rb
index fc60942de8..d38ea54834 100644
--- a/spree/core/spec/models/spree/return_item/exchange_variant_eligibility/same_option_value_spec.rb
+++ b/spree/core/spec/models/spree/return_item/exchange_variant_eligibility/same_option_value_spec.rb
@@ -55,7 +55,7 @@ module Spree
it 'returns all variants for the product' do
Spree::StockItem.update_all(count_on_hand: 10)
- expect(subject.sort).to eq [variant, same_option_values_variant, different_waist_option_value_variant, different_color_option_value_variant].sort
+ expect(subject.sort).to eq product.reload.variants.to_a.sort
end
end
end
diff --git a/spree/core/spec/models/spree/return_item/exchange_variant_eligibility/same_product_spec.rb b/spree/core/spec/models/spree/return_item/exchange_variant_eligibility/same_product_spec.rb
index 862416db8c..7f2bb74fca 100644
--- a/spree/core/spec/models/spree/return_item/exchange_variant_eligibility/same_product_spec.rb
+++ b/spree/core/spec/models/spree/return_item/exchange_variant_eligibility/same_product_spec.rb
@@ -7,11 +7,11 @@ module Spree
describe '.eligible_variants' do
context 'product has no variants' do
- it 'returns the master variant for the same product' do
+ it 'returns the default variant for the same product' do
product = create(:product)
- product.master.stock_items.first.update_column(:count_on_hand, 10)
+ product.default_variant.stock_items.first.update_column(:count_on_hand, 10)
- expect(SameProduct.eligible_variants(product.master)).to eq [product.master]
+ expect(SameProduct.eligible_variants(product.default_variant)).to eq [product.default_variant]
end
end
diff --git a/spree/core/spec/models/spree/stock/coordinator_spec.rb b/spree/core/spec/models/spree/stock/coordinator_spec.rb
index c3f95af1d0..31c6a37af7 100644
--- a/spree/core/spec/models/spree/stock/coordinator_spec.rb
+++ b/spree/core/spec/models/spree/stock/coordinator_spec.rb
@@ -41,7 +41,7 @@ module Spree
let!(:order) do
product.stock_items.map { |stock_item| stock_item.adjust_count_on_hand(1) }
- line_item = create(:line_item, product: product, variant: product.master, quantity: 2)
+ line_item = create(:line_item, product: product, variant: product.default_variant, quantity: 2)
line_item.order
end
diff --git a/spree/core/spec/models/spree/stock/package_spec.rb b/spree/core/spec/models/spree/stock/package_spec.rb
index 2e289b9da6..f72831a597 100644
--- a/spree/core/spec/models/spree/stock/package_spec.rb
+++ b/spree/core/spec/models/spree/stock/package_spec.rb
@@ -65,8 +65,8 @@ module Spree
method2 = create(:shipping_method)
method1.shipping_categories = [category1, category2]
method2.shipping_categories = [category1]
- variant1 = create(:product, shipping_category: category1).master
- variant2 = create(:product, shipping_category: category2).master
+ variant1 = create(:product, shipping_category: category1).default_variant
+ variant2 = create(:product, shipping_category: category2).default_variant
contents = [ContentItem.new(build(:inventory_unit, variant_id: variant1.id)),
ContentItem.new(build(:inventory_unit, variant_id: variant1.id)),
ContentItem.new(build(:inventory_unit, variant_id: variant2.id))]
diff --git a/spree/core/spec/models/spree/stock_item_spec.rb b/spree/core/spec/models/spree/stock_item_spec.rb
index d4ad573081..8f6e43097d 100644
--- a/spree/core/spec/models/spree/stock_item_spec.rb
+++ b/spree/core/spec/models/spree/stock_item_spec.rb
@@ -484,10 +484,10 @@ describe Spree::StockItem, type: :model do
let(:product_in_other_store) { create(:product, store: other_store) }
let!(:in_store_item) do
- create(:stock_item, variant: product_in_store.master, stock_location: stock_location)
+ create(:stock_item, variant: product_in_store.default_variant, stock_location: stock_location)
end
let!(:other_store_item) do
- create(:stock_item, variant: product_in_other_store.master, stock_location: stock_location)
+ create(:stock_item, variant: product_in_other_store.default_variant, stock_location: stock_location)
end
it 'returns stock items for variants of products owned by the store' do
diff --git a/spree/core/spec/models/spree/stock_movement/custom_events_spec.rb b/spree/core/spec/models/spree/stock_movement/custom_events_spec.rb
index 867aca79ae..067868c399 100644
--- a/spree/core/spec/models/spree/stock_movement/custom_events_spec.rb
+++ b/spree/core/spec/models/spree/stock_movement/custom_events_spec.rb
@@ -5,7 +5,7 @@ require 'spec_helper'
RSpec.describe Spree::StockMovement::CustomEvents do
let(:stock_location) { create(:stock_location) }
let(:product) { create(:product) }
- let(:variant) { product.master }
+ let(:variant) { product.default_variant }
let!(:stock_item) do
item = variant.stock_items.first || create(:stock_item, variant: variant, stock_location: stock_location)
item.update!(backorderable: false)
diff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rb
index 1753bc6529..c3a4d532f6 100644
--- a/spree/core/spec/models/spree/store_spec.rb
+++ b/spree/core/spec/models/spree/store_spec.rb
@@ -20,7 +20,7 @@ describe Spree::Store, type: :model, without_global_store: true do
let!(:variant) { create(:variant, product: product) }
let!(:variant_2) { create(:variant, product: product_2) }
- it { expect(subject.variants).to eq([product.master, variant]) }
+ it { expect(subject.variants).to eq([product.default_variant, variant]) }
describe '#stock_items' do
let!(:stock_items) { product.stock_items }
@@ -79,8 +79,8 @@ describe Spree::Store, type: :model, without_global_store: true do
describe '#inventory_units' do
let(:product) { create(:product, store: subject) }
let(:product_2) { create(:product, store: other_store) }
- let!(:inventory_unit) { create(:inventory_unit, variant: product.master, order: order) }
- let!(:inventory_unit_2) { create(:inventory_unit, variant: product_2.master, order: order_2) }
+ let!(:inventory_unit) { create(:inventory_unit, variant: product.default_variant, order: order) }
+ let!(:inventory_unit_2) { create(:inventory_unit, variant: product_2.default_variant, order: order_2) }
it { expect(subject.inventory_units).to eq([inventory_unit]) }
end
diff --git a/spree/core/spec/models/spree/tax_rate_spec.rb b/spree/core/spec/models/spree/tax_rate_spec.rb
index 7aa1a9e60b..f8ad769805 100644
--- a/spree/core/spec/models/spree/tax_rate_spec.rb
+++ b/spree/core/spec/models/spree/tax_rate_spec.rb
@@ -242,7 +242,7 @@ describe Spree::TaxRate, type: :model do
context 'a download' do
before do
- Spree::Cart::AddItem.call(order: order, variant: download.master)
+ Spree::Cart::AddItem.call(order: order, variant: download.default_variant)
end
it 'without an address costs 100 euros including tax' do
@@ -284,7 +284,7 @@ describe Spree::TaxRate, type: :model do
context 'a t-shirt' do
it 'to germany costs 100 euros including tax' do
allow(order).to receive(:tax_zone).and_return(germany_zone)
- Spree::Cart::AddItem.call(order: order, variant: tshirt.master)
+ Spree::Cart::AddItem.call(order: order, variant: tshirt.default_variant)
Spree::TaxRate.adjust(order, order.line_items)
order.update_with_updater!
expect(order.display_total).to eq(Spree::Money.new(100))
@@ -293,7 +293,7 @@ describe Spree::TaxRate, type: :model do
it 'to france costs 100 euros including tax' do
allow(order).to receive(:tax_zone).and_return(france_zone)
- Spree::Cart::AddItem.call(order: order, variant: tshirt.master)
+ Spree::Cart::AddItem.call(order: order, variant: tshirt.default_variant)
order.update_line_item_prices!
Spree::TaxRate.adjust(order, order.line_items)
order.update_with_updater!
@@ -304,7 +304,7 @@ describe Spree::TaxRate, type: :model do
it 'to somewhere else costs the net amount' do
allow(order).to receive(:tax_zone).and_return(india_zone)
- Spree::Cart::AddItem.call(order: order, variant: tshirt.master)
+ Spree::Cart::AddItem.call(order: order, variant: tshirt.default_variant)
order.update_line_item_prices!
Spree::TaxRate.adjust(order, order.line_items)
order.update_with_updater!
@@ -391,7 +391,7 @@ describe Spree::TaxRate, type: :model do
end
context 'not taxable line item ' do
- let!(:line_item) { Spree::Cart::AddItem.call(order: @order, variant: @nontaxable.master).value }
+ let!(:line_item) { Spree::Cart::AddItem.call(order: @order, variant: @nontaxable.default_variant).value }
it 'does not create a tax adjustment' do
Spree::TaxRate.adjust(@order, @order.line_items)
@@ -405,7 +405,7 @@ describe Spree::TaxRate, type: :model do
end
context 'taxable line item' do
- let!(:line_item) { Spree::Cart::AddItem.call(order: @order, variant: @taxable.master).value }
+ let!(:line_item) { Spree::Cart::AddItem.call(order: @order, variant: @taxable.default_variant).value }
context 'when price includes tax' do
before do
diff --git a/spree/core/spec/models/spree/taxon_spec.rb b/spree/core/spec/models/spree/taxon_spec.rb
index f837a0cc26..5a0814a1e1 100644
--- a/spree/core/spec/models/spree/taxon_spec.rb
+++ b/spree/core/spec/models/spree/taxon_spec.rb
@@ -824,7 +824,7 @@ describe Spree::Taxon, type: :model do
end
context 'when the rule is a sale rule' do
- let!(:product_with_master_on_sale) { create(:product, price: 10, compare_at_price: 12) }
+ let!(:product_with_default_variant_on_sale) { create(:product, price: 10, compare_at_price: 12) }
let!(:product_with_one_variant_on_sale) do
create(:product).tap do |p|
create(:variant, product: p, price: 10, compare_at_price: 12)
@@ -833,7 +833,7 @@ describe Spree::Taxon, type: :model do
end
let!(:product_on_sale_with_different_currency) do
create(:product, price: 10).tap do |p|
- p.master.prices.create(amount: 10, compare_at_amount: 12, currency: 'PLN')
+ p.default_variant.prices.create(amount: 10, compare_at_amount: 12, currency: 'PLN')
end
end
let!(:product_not_on_sale) { create(:product, price: 10) }
@@ -842,7 +842,7 @@ describe Spree::Taxon, type: :model do
it 'matches products that are on sale in store\'s currency' do
create(:sale_taxon_rule, taxon: taxon)
- expect(taxon.reload.products_matching_rules).to contain_exactly(product_with_master_on_sale, product_with_one_variant_on_sale)
+ expect(taxon.reload.products_matching_rules).to contain_exactly(product_with_default_variant_on_sale, product_with_one_variant_on_sale)
end
end
diff --git a/spree/core/spec/models/spree/variant_media_spec.rb b/spree/core/spec/models/spree/variant_media_spec.rb
index 6350ca3899..9df861f8a6 100644
--- a/spree/core/spec/models/spree/variant_media_spec.rb
+++ b/spree/core/spec/models/spree/variant_media_spec.rb
@@ -75,6 +75,10 @@ RSpec.describe Spree::Asset, type: :model do
let!(:variant_a) { create(:variant, product: product) }
let!(:variant_b) { create(:variant, product: product) }
+ # variant_a/b are created after create(:product) cached the variants
+ # association; reload so variant_ids= resolution sees them.
+ before { product.reload }
+
it 'creates links for newly-picked variants' do
expect {
product_asset.variant_ids = [variant_a.to_param]
diff --git a/spree/core/spec/models/spree/variant_spec.rb b/spree/core/spec/models/spree/variant_spec.rb
index 4fe9fdb054..6576b38b52 100644
--- a/spree/core/spec/models/spree/variant_spec.rb
+++ b/spree/core/spec/models/spree/variant_spec.rb
@@ -3,7 +3,6 @@ require 'spec_helper'
describe Spree::Variant, type: :model do
let(:store) { @default_store }
let(:variant) { create(:variant, product: create(:base_product)) }
- let(:master_variant) { create(:master_variant) }
it_behaves_like 'default_price'
it_behaves_like 'metadata'
@@ -129,24 +128,9 @@ describe Spree::Variant, type: :model do
end
end
- describe 'mark_master_out_of_stock' do
- before do
- product.master.stock_items.first.set_count_on_hand(5)
- end
-
- context 'when product is created without variants but with stock' do
- it { expect(product.master).to be_in_stock }
- end
-
- context 'when a variant is created' do
- let!(:new_variant) { create(:variant, product: product) }
-
- it { expect(product.master).not_to be_in_stock }
- end
- end
describe '#create_default_stock_item' do
- let(:new_variant) { product.variants.create(track_inventory: track_inventory, is_master: true) }
+ let(:new_variant) { product.variants.create(track_inventory: track_inventory) }
context 'when not tracking inventory' do
let(:track_inventory) { false }
@@ -163,7 +147,6 @@ describe Spree::Variant, type: :model do
let(:new_variant) do
product.variants.create(
track_inventory: track_inventory,
- is_master: true,
stock_items_attributes: {
'0' => {
stock_location_id: create(:stock_location).id,
@@ -234,57 +217,14 @@ describe Spree::Variant, type: :model do
end
end
- describe 'after_commit :remove_prices_from_master_variant' do
- let(:variant) { build(:variant, product: product) }
- let(:product) { create(:product) }
-
- let(:master) { product.master }
-
- it 'removes prices from master when variant with price is created' do
- expect(product.master.prices.count).to eq(1)
- variant.save!
- variant.set_price(store.default_currency, 19.99)
- expect(product.master.prices.reload.count).to eq(0)
- end
- end
-
- describe 'after_commit :remove_stock_items_from_master_variant' do
- let(:variant) { build(:variant, product: product) }
- let(:product) { create(:product) }
-
- let(:master) { product.master }
-
- before do
- master.stock_items << create(:stock_item, variant: master)
- expect(master.stock_items.reload.count).to be >= 1
- end
-
- it 'removes stock items from master when variant is created' do
- variant.save!
- expect(product.master.stock_items.reload.count).to eq(0)
- end
- end
-
describe 'scope' do
describe '.eligible' do
- context 'when only master variants' do
- let!(:product_1) { create(:product) }
- let!(:product_2) { create(:product) }
-
- it 'returns all of them' do
- expect(Spree::Variant.eligible).to include(product_1.master)
- expect(Spree::Variant.eligible).to include(product_2.master)
- end
- end
-
- context 'when product has more than 1 variant' do
- let!(:product) { create(:product) }
- let!(:variant) { create(:variant, product: product) }
+ it 'returns every variant' do
+ product_1 = create(:product)
+ product_2 = create(:product)
+ variant = create(:variant, product: product_1)
- it 'filters master variant out' do
- expect(Spree::Variant.eligible).to include(variant)
- expect(Spree::Variant.eligible).not_to include(product.master)
- end
+ expect(Spree::Variant.eligible).to include(product_1.default_variant, product_2.default_variant, variant)
end
end
@@ -888,47 +828,22 @@ describe Spree::Variant, type: :model do
end
describe 'exchange_name' do
+ let!(:no_options_variant) { build(:variant, option_values: []) }
let!(:variant) { build(:variant, option_values: []) }
- let!(:master) { create(:master_variant) }
before do
- variant.option_values << create(:option_value, name: 'Foo',
- presentation: 'Foo',
- option_type: create(:option_type, position: 2, name: 'Foo Type', presentation: 'Foo Type'))
+ variant.option_values << create(:option_value, name: 'Foo', presentation: 'Foo',
+ option_type: create(:option_type, position: 2, name: 'Foo Type', presentation: 'Foo Type'))
variant.save
end
- context 'master variant' do
+ context 'without option values' do
it 'returns name' do
- expect(master.exchange_name).to eql master.name
+ expect(no_options_variant.exchange_name).to eql no_options_variant.name
end
end
- context 'variant' do
- it 'returns options text' do
- expect(variant.exchange_name).to eql 'Foo Type: Foo'
- end
- end
- end
-
- describe 'exchange_name' do
- let!(:variant) { build(:variant, option_values: []) }
- let!(:master) { create(:master_variant) }
-
- before do
- variant.option_values << create(:option_value, name: 'Foo',
- presentation: 'Foo',
- option_type: create(:option_type, position: 2, name: 'Foo Type', presentation: 'Foo Type'))
- variant.save
- end
-
- context 'master variant' do
- it 'returns name' do
- expect(master.exchange_name).to eql master.name
- end
- end
-
- context 'variant' do
+ context 'with option values' do
it 'returns options text' do
expect(variant.exchange_name).to eql 'Foo Type: Foo'
end
@@ -936,23 +851,22 @@ describe Spree::Variant, type: :model do
end
describe 'descriptive_name' do
+ let!(:no_options_variant) { build(:variant, option_values: []) }
let!(:variant) { build(:variant, option_values: []) }
- let!(:master) { create(:master_variant) }
before do
- variant.option_values << create(:option_value, name: 'Foo',
- presentation: 'Foo',
- option_type: create(:option_type, position: 2, name: 'Foo Type', presentation: 'Foo Type'))
+ variant.option_values << create(:option_value, name: 'Foo', presentation: 'Foo',
+ option_type: create(:option_type, position: 2, name: 'Foo Type', presentation: 'Foo Type'))
variant.save
end
- context 'master variant' do
- it 'returns name with Master identifier' do
- expect(master.descriptive_name).to eql master.name + ' - Master'
+ context 'without option values' do
+ it 'returns name' do
+ expect(no_options_variant.descriptive_name).to eql no_options_variant.name
end
end
- context 'variant' do
+ context 'with option values' do
it 'returns options text with name' do
expect(variant.descriptive_name).to eql variant.name + ' - Foo Type: Foo'
end
@@ -1376,7 +1290,7 @@ describe Spree::Variant, type: :model do
it 'adds an error' do
expect(subject).to be(false)
expect(variant.errors[:base]).to contain_exactly(
- I18n.t('activerecord.errors.models.spree/variant.attributes.base.no_master_variant_found_to_infer_price')
+ I18n.t('activerecord.errors.models.spree/variant.attributes.base.no_default_variant_found_to_infer_price')
)
end
end
@@ -1399,7 +1313,7 @@ describe Spree::Variant, type: :model do
it 'adds an error' do
expect(subject).to be(false)
expect(variant.errors[:base]).to contain_exactly(
- I18n.t('activerecord.errors.models.spree/variant.attributes.base.no_master_variant_found_to_infer_price')
+ I18n.t('activerecord.errors.models.spree/variant.attributes.base.no_default_variant_found_to_infer_price')
)
end
end
@@ -1574,27 +1488,26 @@ describe Spree::Variant, type: :model do
let(:product) { create(:product) }
describe 'variant_count on product' do
+ it 'counts the default variant' do
+ expect(product.reload.variant_count).to eq(1)
+ end
+
it 'increments when a variant is created' do
expect {
create(:variant, product: product)
- }.to change { product.reload.variant_count }.from(0).to(1)
+ }.to change { product.reload.variant_count }.from(1).to(2)
end
it 'decrements when a variant is destroyed' do
variant = create(:variant, product: product)
expect {
variant.destroy
- }.to change { product.reload.variant_count }.from(1).to(0)
- end
-
- it 'does not count master variant' do
- expect(product.variant_count).to eq(0)
- expect(product.master).to be_present
+ }.to change { product.reload.variant_count }.from(2).to(1)
end
it 'correctly counts multiple variants' do
create_list(:variant, 3, product: product)
- expect(product.reload.variant_count).to eq(3)
+ expect(product.reload.variant_count).to eq(4)
end
end
end
diff --git a/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb
index 32e6e6d1c9..f4fa02ad23 100644
--- a/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb
@@ -3,7 +3,7 @@ require 'spec_helper'
RSpec.describe Spree::CSV::ProductVariantPresenter do
let(:store) { @default_store }
let(:product) { create(:product, width: 10, height: 15, depth: 20, dimensions_unit: 'in', weight_unit: 'lb') }
- let(:variant) { product.master }
+ let(:variant) { product.default_variant }
let(:properties) { [] }
let(:taxons) { [] }
let(:metafields) { [] }
diff --git a/spree/core/spec/presenters/spree/data_feeds/google_presenter_spec.rb b/spree/core/spec/presenters/spree/data_feeds/google_presenter_spec.rb
index 206093fb36..07e343c341 100644
--- a/spree/core/spec/presenters/spree/data_feeds/google_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/data_feeds/google_presenter_spec.rb
@@ -87,16 +87,16 @@ RSpec.describe Spree::DataFeeds::GooglePresenter do
end
end
- context 'product with only master variant' do
+ context 'product with only default variant' do
let(:product) { create(:product) }
let!(:variant) { nil }
before do
- product.master.images << create(:image)
+ product.default_variant.images << create(:image)
end
- it 'includes master variant in feed' do
- expect(xml).to include("<g:id>#{product.master.id}</g:id>")
+ it 'includes default variant in feed' do
+ expect(xml).to include("<g:id>#{product.default_variant.id}</g:id>")
end
it 'includes product name as title' do
diff --git a/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb b/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb
index 3ff3a630c8..dab647b73f 100644
--- a/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb
@@ -89,7 +89,7 @@ module Spree
# Product with prices in both currencies
let(:product) do
p = create(:product, name: 'Test Shirt')
- create(:price, variant: p.master, amount: 29.99, currency: 'EUR')
+ create(:price, variant: p.default_variant, amount: 29.99, currency: 'EUR')
p
end
@@ -162,7 +162,7 @@ module Spree
let(:product) do
p = create(:product, name: 'English Name')
- create(:price, variant: p.master, amount: 19.99, currency: 'EUR')
+ create(:price, variant: p.default_variant, amount: 19.99, currency: 'EUR')
p
end
diff --git a/spree/core/spec/presenters/spree/variants/option_types_presenter_spec.rb b/spree/core/spec/presenters/spree/variants/option_types_presenter_spec.rb
index 5a99559a70..2ef3c049d3 100644
--- a/spree/core/spec/presenters/spree/variants/option_types_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/variants/option_types_presenter_spec.rb
@@ -33,6 +33,11 @@ describe Spree::Variants::OptionTypesPresenter do
before { variant_0.stock_items.first.update(backorderable: false, count_on_hand: 0) }
context 'default variant of product' do
+ before do
+ product.variants.where.missing(:option_value_variants).destroy_all
+ product.update_column(:default_variant_id, variant_0.id)
+ end
+
context 'backorderable' do
before { variant_0.stock_items.first.update(backorderable: true) }
@@ -89,6 +94,11 @@ describe Spree::Variants::OptionTypesPresenter do
describe '#options' do
subject(:options) { described_class.new(option_types, variants, product).options }
+ before do
+ product.variants.where.missing(:option_value_variants).destroy_all
+ product.update_column(:default_variant_id, variant_0.id)
+ end
+
it 'returns serialized options for Option Types and Option Values' do
expect(options).to eq(
[
diff --git a/spree/core/spec/services/spree/checkout/select_shipping_method_spec.rb b/spree/core/spec/services/spree/checkout/select_shipping_method_spec.rb
index dce99877f4..32fc7379a8 100644
--- a/spree/core/spec/services/spree/checkout/select_shipping_method_spec.rb
+++ b/spree/core/spec/services/spree/checkout/select_shipping_method_spec.rb
@@ -76,7 +76,7 @@ module Spree
context 'multiple shipments' do
let(:product_2) { create(:product_in_stock, shipping_category: shipping_category) }
- let!(:line_item) { create(:line_item, variant: product_2.master, order: order) }
+ let!(:line_item) { create(:line_item, variant: product_2.default_variant, order: order) }
let(:shipment) { order.shipments.first }
let(:shipment_2) { order.shipments.last }
diff --git a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
index ddf7386136..de687fb6e7 100644
--- a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
+++ b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
@@ -21,7 +21,9 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
csv_row_headers.index_with { |header| attrs[header] }
end
- context 'when importing a master variant product row' do
+ context 'when importing a product row' do
+ let(:product) { subject.process! }
+
let(:row_data) do
csv_row_hash(
'slug' => 'denim-shirt',
@@ -38,7 +40,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'creates a product and sets correct attributes' do
- product = variant.product
+ default_variant = product.default_variant
expect(product).to be_persisted
expect(product.slug).to eq 'denim-shirt'
@@ -46,13 +48,12 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
expect(product.status).to eq 'draft'
expect(product.description).to eq row_data['description']
expect(product.store).to eq(store)
- expect(product.master).to eq variant
- expect(variant.sku).to be_blank
- expect(variant.price_in('USD').amount.to_f).to eq 62.99
- expect(variant.weight.to_f).to eq 0.0
- expect(variant.stock_items.first.count_on_hand).to eq 100
- expect(variant.stock_items.first.backorderable).to eq true
- expect(variant.stock_items.first.stock_location).to eq store.default_stock_location
+ expect(default_variant.sku).to be_blank
+ expect(default_variant.price_in('USD').amount.to_f).to eq 62.99
+ expect(default_variant.weight.to_f).to eq 0.0
+ expect(default_variant.stock_items.first.count_on_hand).to eq 100
+ expect(default_variant.stock_items.first.backorderable).to eq true
+ expect(default_variant.stock_items.first.stock_location).to eq store.default_stock_location
end
it 'enqueues AssignTagsJob' do
@@ -64,8 +65,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'publishes the product to the store default channel' do
- product = variant.product
-
expect(product.channels).to contain_exactly(store.default_channel)
end
@@ -75,25 +74,23 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
before { store.channels.delete_all }
it 'imports the product without publishing it to any channel' do
- product = variant.product
-
expect(product).to be_persisted
expect(product.channels).to be_empty
end
end
- context 'when updating an existing master variant' do
+ context 'when updating an existing product' do
let!(:existing_product) { create(:product, slug: 'denim-shirt', name: 'Old Name') }
before do
- stock_item = existing_product.master.stock_items.find_or_initialize_by(stock_location: store.default_stock_location)
+ stock_item = existing_product.default_variant.stock_items.find_or_initialize_by(stock_location: store.default_stock_location)
stock_item.count_on_hand = 50
stock_item.backorderable = false
stock_item.save!
end
it 'updates inventory_count and inventory_backorderable' do
- stock_item = existing_product.master.stock_items.find_by(stock_location: store.default_stock_location)
+ stock_item = existing_product.default_variant.stock_items.find_by(stock_location: store.default_stock_location)
expect(stock_item.count_on_hand).to eq 50
expect(stock_item.backorderable).to eq false
@@ -389,7 +386,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
end
- context 'with images on a master variant row (no options)' do
+ context 'with images on a product row (no options)' do
let!(:product) do
create(:product, slug: 'denim-shirt', name: 'Denim Shirt')
end
@@ -412,7 +409,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
end
- context 'with images on a non-master variant row' do
+ context 'with images on a variant row' do
let!(:product) do
create(:product, slug: 'denim-shirt', name: 'Denim Shirt')
end
@@ -436,7 +433,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
.to have_enqueued_job(Spree::Images::SaveFromUrlJob).exactly(1).times
created_variant = result
- expect(created_variant).not_to be_is_master
+ expect(created_variant.option_values.map(&:presentation)).to contain_exactly('Blue')
expect(Spree::Images::SaveFromUrlJob).to have_been_enqueued
.with(product.id, 'Spree::Product', row_data['image1_src'], nil, nil, created_variant.id)
end
@@ -507,7 +504,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
context 'when importing a variant with all option columns empty' do
let!(:product) do
- create(:product, slug: 'denim-shirt', name: 'Denim Shirt')
+ create(:product, slug: 'denim-shirt', name: 'Denim Shirt', sku: 'DENIM-SHIRT-PLAIN')
end
let(:row_data) do
@@ -519,8 +516,25 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
)
end
- it 'does not create a variant' do
- expect { subject.process! }.to raise_error(ActiveRecord::RecordInvalid)
+ it 'updates the default variant instead of creating a new one' do
+ expect { subject.process! }.not_to change { product.reload.variants.count }
+ expect(product.default_variant.price_in('USD').amount).to eq(62.99)
+ end
+ end
+
+ context 'when importing a row with no sku and no options' do
+ let!(:product) { create(:product, slug: 'plain-tee', name: 'Plain Tee') }
+
+ let(:row_data) do
+ csv_row_hash(
+ 'slug' => 'plain-tee',
+ 'weight' => '2.5'
+ )
+ end
+
+ it 'updates the default variant without creating a new one' do
+ expect { subject.process! }.not_to change { product.reload.variants.count }
+ expect(product.default_variant.reload.weight).to eq(2.5)
end
end
@@ -574,14 +588,12 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
)
end
- it 'creates a new product and assigns the variant as its master if no option1_name given' do
- variant = subject.process!
- product = variant.product
+ it 'creates a new product and assigns the SKU to its default variant if no option1_name given' do
+ product = subject.process!
expect(product).to be_persisted
expect(product.slug).to eq 'new-missing-shirt'
- expect(product.master).to eq variant
- expect(variant.sku).to eq 'NEW-MISSING-SHIRT-SKU'
+ expect(product.default_variant.sku).to eq 'NEW-MISSING-SHIRT-SKU'
end
end
@@ -624,6 +636,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
import.create_mappings
end
+ let(:product) { subject.process! }
+
it 'creates mappings for metafields automatically' do
expect(import.mappings.where(schema_field: 'metafield.custom.brand').exists?).to be true
expect(import.mappings.where(schema_field: 'metafield.custom.material').exists?).to be true
@@ -643,8 +657,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'sets metafields on the product' do
- product = variant.product
-
expect(product).to be_persisted
expect(product.has_metafield?('custom.brand')).to be true
expect(product.has_metafield?('custom.material')).to be true
@@ -661,8 +673,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'updates existing metafields' do
- product = variant.product
-
expect(product.id).to eq existing_product.id
expect(product.get_metafield('custom.brand').value).to eq 'Awesome Brand'
expect(product.get_metafield('custom.material').value).to eq 'Cotton'
@@ -685,8 +695,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'skips blank metafield values' do
- product = variant.product
-
expect(product.has_metafield?('custom.brand')).to be true
expect(product.get_metafield('custom.brand').value).to eq 'Awesome Brand'
expect(product.has_metafield?('custom.material')).to be false
@@ -718,8 +726,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
it 'removes existing metafield when empty value is uploaded' do
expect(existing_product.metafields.count).to eq 2
- product = variant.product
-
expect(product.id).to eq existing_product.id
expect(product.has_metafield?('custom.brand')).to be true
expect(product.get_metafield('custom.brand').value).to eq 'New Brand'
@@ -745,8 +751,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
it 'removes all existing metafields' do
expect(existing_product.metafields.count).to eq 2
- product = variant.product
-
expect(product.id).to eq existing_product.id
expect(product.has_metafield?('custom.brand')).to be false
expect(product.has_metafield?('custom.material')).to be false
@@ -755,7 +759,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
end
- context 'when processing a non-master variant row' do
+ context 'when processing a variant row' do
let!(:existing_product) do
p = create(:product, slug: 'denim-shirt', name: 'Denim Shirt')
p.set_metafield('custom.brand', 'Awesome Brand')
@@ -794,6 +798,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
context 'when importing with shipping_category' do
+ let(:product) { subject.process! }
+
context 'when shipping_category exists' do
let!(:digital_category) { create(:shipping_category, name: 'Digital') }
@@ -809,7 +815,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'assigns the shipping category to the product' do
- product = variant.product
expect(product.shipping_category).to eq digital_category
end
end
@@ -827,7 +832,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'assigns the default shipping category' do
- product = variant.product
expect(product.shipping_category).to be_present
expect(product.shipping_category.name).to eq 'Default'
end
@@ -852,8 +856,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'updates the shipping category' do
- product = variant.product
-
expect(product.id).to eq existing_product.id
expect(product.shipping_category).to eq digital_category
end
@@ -871,8 +873,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'assigns the default shipping category' do
- product = variant.product
-
expect(product.shipping_category).to be_present
expect(product.shipping_category.name).to eq 'Default'
end
@@ -880,6 +880,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
context 'when importing with tax_category' do
+ let(:product) { subject.process! }
+
context 'when tax_category exists' do
let!(:clothing_tax) { create(:tax_category, name: 'Clothing') }
@@ -894,8 +896,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
)
end
- it 'assigns the tax category to the variant' do
- expect(variant.tax_category).to eq clothing_tax
+ it 'assigns the tax category to the default variant' do
+ expect(product.default_variant.tax_category).to eq clothing_tax
end
end
@@ -912,7 +914,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'does not assign a tax category' do
- expect(variant.tax_category).to be_nil
+ expect(product.default_variant.tax_category).to be_nil
end
end
@@ -921,7 +923,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
let!(:clothing_tax) { create(:tax_category, name: 'Clothing') }
let!(:existing_product) do
p = create(:product, slug: 'product-to-update', name: 'Product')
- p.master.update(tax_category: standard_tax)
+ p.default_variant.update(tax_category: standard_tax)
p
end
@@ -937,10 +939,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'updates the tax category' do
- product = variant.product
-
expect(product.id).to eq existing_product.id
- expect(variant.tax_category).to eq clothing_tax
+ expect(product.default_variant.tax_category).to eq clothing_tax
end
end
@@ -956,11 +956,11 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
it 'does not assign a tax category' do
- expect(variant.tax_category).to be_nil
+ expect(product.default_variant.tax_category).to be_nil
end
end
- context 'when importing a non-master variant with tax_category' do
+ context 'when importing an option variant with tax_category' do
let!(:clothing_tax) { create(:tax_category, name: 'Clothing') }
let!(:product) do
p = create(:product, slug: 'denim-shirt', name: 'Denim Shirt')
@@ -981,8 +981,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
)
end
- it 'assigns tax category to the non-master variant' do
- expect(variant.is_master?).to be false
+ it 'assigns the tax category to the option variant' do
+ expect(variant.option_values.map(&:presentation)).to contain_exactly('Blue')
expect(variant.tax_category).to eq clothing_tax
end
end
diff --git a/spree/core/spec/services/spree/orders/create_spec.rb b/spree/core/spec/services/spree/orders/create_spec.rb
index 535c0e5cbc..314a829e91 100644
--- a/spree/core/spec/services/spree/orders/create_spec.rb
+++ b/spree/core/spec/services/spree/orders/create_spec.rb
@@ -206,7 +206,7 @@ module Spree
# fires and UpsertItems returns a failing line_item.
let(:out_of_stock_product) do
create(:product).tap do |p|
- p.master.stock_items.update_all(count_on_hand: 0, backorderable: false)
+ p.default_variant.stock_items.update_all(count_on_hand: 0, backorderable: false)
end
end
let(:params) do
diff --git a/spree/core/spec/services/spree/products/duplicator_spec.rb b/spree/core/spec/services/spree/products/duplicator_spec.rb
index c37cb4cc7d..2d786c7b0f 100644
--- a/spree/core/spec/services/spree/products/duplicator_spec.rb
+++ b/spree/core/spec/services/spree/products/duplicator_spec.rb
@@ -8,9 +8,9 @@ RSpec.describe Spree::Products::Duplicator do
let!(:product) { create(:product, tag_list: ['tag1', 'tag2'], status: :active) }
let(:filepath) { File.expand_path('../../../fixtures/thinking-cat.jpg', __dir__) }
- let(:master_image_params) do
+ let(:default_variant_image_params) do
{
- viewable_id: product.master.id,
+ viewable_id: product.default_variant.id,
viewable_type: 'Spree::Variant',
alt: 'position 1',
position: 1
@@ -19,12 +19,12 @@ RSpec.describe Spree::Products::Duplicator do
before do
file = File.open(filepath)
- new_image = Spree::Image.new(master_image_params)
+ new_image = Spree::Image.new(default_variant_image_params)
new_image.attachment.attach(io: file, filename: File.basename(file))
new_image.save!
- product.master.update!(barcode: '1234567890')
- product.master.stock_items.last.update!(count_on_hand: 100, backorderable: true)
+ product.default_variant.update!(barcode: '1234567890')
+ product.default_variant.stock_items.last.update!(count_on_hand: 100, backorderable: true)
end
it { is_expected.to be_success }
@@ -77,8 +77,8 @@ RSpec.describe Spree::Products::Duplicator do
end
it 'clones backorderable and sets stock to 0' do
- expect(new_product.master).to be_backorderable
- expect(new_product.master.total_on_hand).to eq(0)
+ expect(new_product.default_variant).to be_backorderable
+ expect(new_product.default_variant.total_on_hand).to eq(0)
end
end
@@ -86,18 +86,18 @@ RSpec.describe Spree::Products::Duplicator do
let(:new_product) { duplicate.value }
before do
- product.master.set_price('USD', 10.99, 11.99)
- product.master.set_price('GBP', 8.99, 9.99)
+ product.default_variant.set_price('USD', 10.99, 11.99)
+ product.default_variant.set_price('GBP', 8.99, 9.99)
end
it 'clones prices' do
expect(duplicate).to be_success
- usd_price = new_product.master.price_in('USD')
+ usd_price = new_product.default_variant.price_in('USD')
expect(usd_price.amount).to eq(10.99)
expect(usd_price.compare_at_amount).to eq(11.99)
- gbp_price = new_product.master.price_in('GBP')
+ gbp_price = new_product.default_variant.price_in('GBP')
expect(gbp_price.amount).to eq(8.99)
expect(gbp_price.compare_at_amount).to eq(9.99)
end
@@ -125,7 +125,7 @@ RSpec.describe Spree::Products::Duplicator do
end
it 'duplicates the variants' do
- # will change the count by 3, since there will be a master variant as well
+ # will change the count by 3, since there will be a default variant as well
expect { duplicate }.to change { Spree::Variant.count }.by(3)
end
@@ -134,7 +134,7 @@ RSpec.describe Spree::Products::Duplicator do
end
it 'clones barcodes' do
- expect(new_product.variants.pluck(:barcode)).to contain_exactly('v1-123', 'v2-456')
+ expect(new_product.variants.pluck(:barcode)).to contain_exactly('1234567890', 'v1-123', 'v2-456')
end
it 'clones backorderable and sets stock to 0' do
diff --git a/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb b/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb
index 09e68e5c0b..67befa56a1 100644
--- a/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb
+++ b/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb
@@ -1,7 +1,7 @@
require 'spec_helper'
RSpec.describe Spree::Products::PrepareNestedAttributes do
- let(:service) { described_class.new(product, store, params, ability) }
+ let(:service) { described_class.new(product.persisted? ? product.reload : product, store, params, ability) }
subject(:prepared_params) { service.call }
let(:ability) { Spree::Ability.new(nil) }
@@ -42,7 +42,7 @@ RSpec.describe Spree::Products::PrepareNestedAttributes do
end
describe 'prices_attributes handling' do
- let(:variant) { product.master }
+ let(:variant) { product.default_variant }
context 'when user cannot update prices' do
before do
@@ -67,22 +67,6 @@ RSpec.describe Spree::Products::PrepareNestedAttributes do
expect(prepared_params[:variants_attributes]['0']).not_to have_key(:prices_attributes)
end
end
-
- context 'with master_attributes' do
- let(:raw_params) do
- {
- master_attributes: {
- prices_attributes: {
- '0' => { amount: '10.00' }
- }
- }
- }
- end
-
- it 'removes prices_attributes from master' do
- expect(prepared_params[:master_attributes]).not_to have_key(:prices_attributes)
- end
- end
end
context 'when user can update prices' do
@@ -270,7 +254,7 @@ RSpec.describe Spree::Products::PrepareNestedAttributes do
end
describe 'stock_items_attributes handling' do
- let(:variant) { product.master }
+ let(:variant) { product.default_variant }
context 'when user cannot update stock items' do
before do
@@ -295,22 +279,6 @@ RSpec.describe Spree::Products::PrepareNestedAttributes do
expect(prepared_params[:variants_attributes]['0']).not_to have_key(:stock_items_attributes)
end
end
-
- context 'with master_attributes' do
- let(:raw_params) do
- {
- master_attributes: {
- stock_items_attributes: {
- '0' => { count_on_hand: 10 }
- }
- }
- }
- end
-
- it 'removes stock_items_attributes from master' do
- expect(prepared_params[:master_attributes]).not_to have_key(:stock_items_attributes)
- end
- end
end
end
end
diff --git a/spree/core/spec/services/spree/sample_data/loader_spec.rb b/spree/core/spec/services/spree/sample_data/loader_spec.rb
index ef0d943daa..4e8d7bb022 100644
--- a/spree/core/spec/services/spree/sample_data/loader_spec.rb
+++ b/spree/core/spec/services/spree/sample_data/loader_spec.rb
@@ -15,7 +15,7 @@ RSpec.describe Spree::SampleData::Loader, type: :service, without_global_store:
end
it 'creates variants' do
- expect(Spree::Variant.count).to be > 100
+ expect(Spree::Variant.count).to be > 80
end
it 'creates customers' do
diff --git a/spree/core/spec/services/spree/shipments/add_item_spec.rb b/spree/core/spec/services/spree/shipments/add_item_spec.rb
index 9ef8764449..07d0d9a0ac 100644
--- a/spree/core/spec/services/spree/shipments/add_item_spec.rb
+++ b/spree/core/spec/services/spree/shipments/add_item_spec.rb
@@ -7,7 +7,7 @@ module Spree
let(:store) { @default_store }
let(:order) { create(:order_with_totals, store: store, user: nil, email: '[email protected]') }
let(:product) { create(:product_in_stock) }
- let(:variant) { product.master }
+ let(:variant) { product.default_variant }
let(:execute) { subject.call(params) }
let(:value) { execute.value }
diff --git a/spree/core/spec/services/spree/shipments/create_spec.rb b/spree/core/spec/services/spree/shipments/create_spec.rb
index 460dcfd853..4fa7597007 100644
--- a/spree/core/spec/services/spree/shipments/create_spec.rb
+++ b/spree/core/spec/services/spree/shipments/create_spec.rb
@@ -7,7 +7,7 @@ module Spree
let(:store) { @default_store }
let(:order) { create(:order_with_totals, store: store, user: nil, email: '[email protected]') }
let(:product) { create(:product_in_stock) }
- let(:variant) { product.master }
+ let(:variant) { product.default_variant }
let(:stock_location) { product.stock_items.first.stock_location }
let(:execute) { subject.call(store: store, shipment_attributes: shipment_attributes) }
diff --git a/spree/core/spec/services/spree/stock_locations/stock_items/create_spec.rb b/spree/core/spec/services/spree/stock_locations/stock_items/create_spec.rb
index d8272a8e0c..dfd19154c9 100644
--- a/spree/core/spec/services/spree/stock_locations/stock_items/create_spec.rb
+++ b/spree/core/spec/services/spree/stock_locations/stock_items/create_spec.rb
@@ -17,10 +17,8 @@ module Spree
before { Spree::StockItem.find(Spree::StockItem.ids.sample).delete }
it 'inserts stock items without duplicates' do
- total_stock_items = Spree::StockItem.count
- expect { result }.to change {
- stock_location.stock_items.count
- }.from(total_stock_items).to(total_stock_items + 2)
+ expect { result }.to change { stock_location.stock_items.count }.by(1)
+ expect(stock_location.stock_items.count).to eq(Spree::Variant.count)
end
end
diff --git a/spree/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb b/spree/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb
index 648ae4286e..b5f14b2908 100644
--- a/spree/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb
+++ b/spree/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb
@@ -25,8 +25,8 @@ RSpec.describe Spree::ProductMetricsSubscriber do
let(:order) do
create(:completed_order_with_totals, store: store).tap do |o|
- o.line_items.first.update!(product: product_1, variant: product_1.master)
- create(:line_item, order: o, product: product_2, variant: product_2.master)
+ o.line_items.first.update!(product: product_1, variant: product_1.default_variant)
+ create(:line_item, order: o, product: product_2, variant: product_2.default_variant)
end
end
@@ -100,8 +100,8 @@ RSpec.describe Spree::ProductMetricsSubscriber do
context 'when order has duplicate products' do
let(:order_with_duplicates) do
create(:completed_order_with_totals, store: store).tap do |o|
- o.line_items.first.update!(product: product_1, variant: product_1.master)
- create(:line_item, order: o, product: product_1, variant: product_1.master)
+ o.line_items.first.update!(product: product_1, variant: product_1.default_variant)
+ create(:line_item, order: o, product: product_1, variant: product_1.default_variant)
end
end