Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
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.mdindex 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-create9. Update `eligible` scope (no `is_master` filter needed)10. Update factories: product factory creates one variant instead of master11. 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 updatesdiff --git a/spree/admin/app/helpers/spree/admin/products_helper.rb b/spree/admin/app/helpers/spree/admin/products_helper.rbindex 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 Spreeenddef 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)enddiff --git a/spree/core/app/finders/spree/products/find.rb b/spree/core/app/finders/spree/products/find.rbindex 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 Spreedef 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 })enddef by_price(products)@@ -302,7 +302,7 @@ module Spreedef 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.rbindex 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 Spreedef 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?endvariants.map(&:images).flatten@@ -112,7 +110,7 @@ module Spreewhere(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.rbindex 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 Spreeimage.persisted? && image.attachment.attached? && image.external_url.present? && external_url == image.external_urlend- # `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.imagesenddiff --git a/spree/core/app/jobs/spree/media/migrate_product_assets_job.rb b/spree/core/app/jobs/spree/media/migrate_product_assets_job.rbindex 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 Spreequeue_as Spree.queues.imagesdef 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.masterreturn 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&.idtouched_variants = []product.variants.each do |variant|@@ -29,15 +27,12 @@ module Spreenext 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_idtouched_variants << variantend- 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.rbindex 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 Spreereturn unless productcompleted_order_ids = product.completed_orders.select(:id)- variant_ids = product.variants_including_master.ids+ variant_ids = product.variants.idsline_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.rbindex 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 Spreescope :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 Spreewhere(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 Spreeenddef 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 Spreeorder(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 namedef 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.rbindex 7266e8e5f7..7f6c587866 100644--- a/spree/core/app/models/spree/asset.rb+++ b/spree/core/app/models/spree/asset.rb@@ -161,14 +161,9 @@ module Spreedef 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)enddef increment_viewable_media_countdiff --git a/spree/core/app/models/spree/exports/products.rb b/spree/core/app/models/spree/exports/products.rbindex 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 Spreeclass Products < Spree::Export# to avoid N+1 queriesdef 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 }includesenddiff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rbindex 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 Spreebelongs_to :shipping_category, class_name: 'Spree::ShippingCategory', inverse_of: :productshas_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: :variantshas_many :orders, through: :line_itemshas_many :completed_orders, -> { reorder(nil).distinct.complete }, through: :line_items, source: :orderhas_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: :variantsbelongs_to :primary_media, class_name: 'Spree::Asset', optional: true, foreign_key: :primary_media_idhas_many :option_value_variants, class_name: 'Spree::OptionValueVariant', through: :variantshas_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_masterafter_initialize :assign_default_tax_category- before_validation :validate_masterbefore_validation :ensure_default_shipping_categoryafter_create :add_associations_from_prototype- after_create :build_variants_from_option_values_hash, if: :option_values_hashafter_create :apply_pending_variants, if: :pending_variants?+ after_create :ensure_default_variant+ after_create :set_default_variantafter_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_taxonsafter_commit :auto_match_taxons, if: :eligible_for_taxon_matching?@@ -161,7 +144,8 @@ module Spreescope :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 Spreescope :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 Spreev[:option_value_variants_attributes].blank? && v[:stock_items_attributes].blank? && v[:prices_attributes].blank?end)- accepts_nested_attributes_for :master, reject_if: :all_blankaccepts_nested_attributes_for(:product_option_types,allow_destroy: true,@@ -205,10 +186,10 @@ module Spreeself.tag_list = tagsend- # 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_paramsend# Maps 6.0 API name (category_ids) to model column (taxon_ids).@@ -266,7 +247,7 @@ module Spreeendself.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 labelsshipping_category classifications option_types]self.whitelisted_ransackable_scopes = %w[not_discontinued search_by_name in_taxon in_category in_categories price_betweenprice_lte price_gte@@ -274,26 +255,19 @@ module Spreeascend_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_variantenddelegate :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_variantstate_machine :status, initial: :draft doevent :activate do@@ -326,57 +300,44 @@ module Spree# Can't use short form block syntax due to https://github.com/Netflix/fast_jsonapi/issues/259def 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/259def 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/259def backorderable?- default_variant.backorderable? || variants.any?(&:backorderable?)+ variants.any?(&:backorderable?)enddef 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.firstend- # 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.buildend- # 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 > 1end+ # @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 Spreealias 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 Spreeenddef 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 > 1enddef 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 querydef 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.currentend- # determine if any variant (including master) can be supplied+ # determine if any variant can be supplieddef 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 backorderabledef backordered?- variants_including_master.any?(&:backordered?)+ variants.any?(&:backordered?)enddef self.like_any(fields, values)@@ -583,19 +528,29 @@ module Spree@total_on_hand ||= if any_variants_not_track_inventory?BigDecimal::INFINITYelse- if variants_including_master.loaded?- variants_including_master.sum(&:total_on_hand)+ if variants.loaded?+ variants.sum(&:total_on_hand)elsestock_items.loaded? ? stock_items.sum(&:count_on_hand) : stock_items.sum(:count_on_hand)endendend- # 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_idend# Returns the brand taxon for the product@@ -634,9 +589,9 @@ module Spreedef 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?endend@@ -676,7 +631,7 @@ module Spreetaxons_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_adefault_currency = store.default_currencyadditional_currencies = store.supported_currencies_list.map(&:iso_code) - [default_currency]@@ -713,10 +668,9 @@ module Spreeprivate# Determines which variant should be used for displaying media.- # Priority: master > default_variant > first variant with media+ # Priority: default_variant > first variant with mediadef 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 Spreedef apply_variants(variants_params)variant_ids_in_payload = []- master_touched = falsemutated = falsevariants_params.each do |variant_data|variant_data = variant_data.to_h.with_indifferent_accessvariant_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 = trueelsevariant = variants.buildvariant.assign_attributes(variant_data)variant.save!- variant_ids_in_payload << variant.id- mutated = trueend++ variant_ids_in_payload << variant.id+ mutated = trueend- # 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_allmutated ||= removed.any?end@@ -826,24 +763,16 @@ module Spreeend# 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).resetenddef add_associations_from_prototype@@ -856,91 +785,40 @@ module Spreedef 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?endend- # 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_variantend- 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_idenddef assign_default_tax_categoryself.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_categoryreturn if shipping_category.present?@@ -987,7 +865,7 @@ module Spreeenddef requires_price?- Spree::Config[:require_master_price]+ Spree::Config[:require_default_variant_price]enddef requires_shipping_category?diff --git a/spree/core/app/models/spree/reports/products_performance.rb b/spree/core/app/models/spree/reports/products_performance.rbindex 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 Spreeproduct_scope = store.productsproduct_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.rbindex 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 Spreemodule ReturnItem::ExchangeVariantEligibilityclass SameProductdef 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_backorderableendendenddiff --git a/spree/core/app/models/spree/stock/package.rb b/spree/core/app/models/spree/stock/package.rbindex 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 Spreeenddef shipping_categories- Spree::ShippingCategory.joins(products: :variants_including_master).+ Spree::ShippingCategory.joins(products: :variants).where(spree_variants: { id: variant_ids }).distinctenddiff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 6d858992e6..bc33e06691 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -84,7 +84,7 @@ module Spreehas_many :products, class_name: 'Spree::Product', dependent: :nullifyhas_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: :variantshas_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: :storediff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex 1a01bbc2f1..e77d4bc0d5 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -77,8 +77,6 @@ module Spreevalidate :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 Spreevalidates :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: :updateafter_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_countscope :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_inventorydeleted_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 variantdef exchange_name- is_master? ? name : options_text+ option_values.any? ? options_text : nameend# Returns the descriptive name of the variant.# @return [String] the descriptive name of the variantdef descriptive_name- is_master? ? name + ' - Master' : name + ' - ' + options_text+ option_values.any? ? "#{name} - #{options_text}" : nameend# 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_nameo.save!@@ -754,14 +740,7 @@ module SpreeSpree::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 supplieddef check_pricereturn if prices.any?@@ -773,9 +752,9 @@ module Spreecurrent_price = price_in(default_currency).amountif 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).amountset_price(default_currency, inferred_price) if inferred_price.present?end@@ -812,14 +791,6 @@ module Spreestock_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_countSpree::Product.increment_counter(:variant_count, product_id)enddiff --git a/spree/core/app/presenters/spree/data_feeds/google_presenter.rb b/spree/core/app/presenters/spree/data_feeds/google_presenter.rbindex 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 Spreeenddef 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)endenddiff --git a/spree/core/app/presenters/spree/search_provider/product_presenter.rb b/spree/core/app/presenters/spree/search_provider/product_presenter.rbindex 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 Spreevariant_option_values_data.map(&:prefixed_id).uniqend- # Use variants_including_master (matches reindex preload) instead of variants.includes+ # Use variants (matches reindex preload) instead of variants.includesdef 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).uniqendendenddiff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rbindex 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 Spreeattr_reader :product, :storedef 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.newelsif options.empty?- product.master+ product.default_variantelseproduct.variants.newend@@ -52,14 +50,32 @@ module Spreehandle_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 : productendprivate+ # 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_existsif options.empty?- # For master variants, create or update the product+ # For product/header rows (no options), create or update the productproduct = Spree::Product.newif attributes['slug'].present?existing_product = product_scope.find_by(slug: attributes['slug'].strip.downcase)@@ -80,7 +96,7 @@ module Spreeproductelse- # For non-master variants, only look up the product+ # For variant rows (with options), only look up the productif attributes['slug'].present?product_scope.find_by!(slug: attributes['slug'].strip.downcase)else@@ -94,7 +110,7 @@ module Spreeenddef 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 oneif product.new_record?product.slug = attributes['slug']product.sku = attributes['sku'] if attributes['sku'].present? && options.empty?@@ -210,9 +226,10 @@ module Spreereturn 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.idimage_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.rbindex 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.rbindex 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 Spreenew_product.deleted_at = nilnew_product.updated_at = nilnew_product.tag_list = product.tag_list- new_product.master = duplicate_master(product.master, include_images)+ new_product.default_variant_id = nilnew_product.variants = product.variants.map { |variant| duplicate_variant(variant, include_images) }endend- 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.dupnew_variant.sku = sku_generator(new_variant.sku)@@ -96,7 +85,6 @@ module Spreedef duplicate_error_message(new_product)errors = []errors << new_product.errors.full_messages- errors << new_product.master.errors.full_messagesnew_product.variants.each do |variant|errors << variant.errors.full_messagesdiff --git a/spree/core/app/services/spree/products/prepare_nested_attributes.rb b/spree/core/app/services/spree/products/prepare_nested_attributes.rbindex 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 Spreeparams[: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)- endendparams.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.rbindex 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 Spreedef 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.rbindex 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 Spreedef 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]}")enddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 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 pricespree/webhook_endpoint:attributes:url:diff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rbindex c8fe2847ff..47565ca648 100644--- a/spree/core/lib/spree/core/configuration.rb+++ b/spree/core/lib/spree/core/configuration.rb@@ -89,7 +89,7 @@ module Spreepreference :max_level_in_taxons_menu, :integer, deprecated: truepreference :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: falsepreference :restock_inventory, :boolean, default: true # Determines if a return item is restocked automatically once it has been receivedpreference :return_eligibility_number_of_days, :integer, default: 365preference :reserve_stock_on, :string, default: 'checkout' # 'checkout' (default) or 'cart' — landing in 6.0 alongside Cart/Order splitdiff --git a/spree/core/lib/spree/core/controller_helpers/order.rb b/spree/core/lib/spree/core/controller_helpers/order.rbindex 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_pricediff --git a/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb b/spree/core/lib/spree/core/controller_helpers/strong_parameters.rbindex 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 Spreedef permitted_product_attributespermitted_attributes.product_attributes + [- variants_attributes: permitted_variant_attributes + ['id', :_destroy],- master_attributes: permitted_variant_attributes + ['id']+ variants_attributes: permitted_variant_attributes + ['id', :_destroy]]enddiff --git a/spree/core/lib/spree/permitted_attributes.rb b/spree/core/lib/spree/permitted_attributes.rbindex 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.rbindex 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 dosequence(:name) { |n| "Product #{n}#{Kernel.rand(9999)}" }description { generate(:random_description) }@@ -19,14 +46,14 @@ FactoryBot.define docreate(:stock_location) unless Spree::StockLocation.any?endafter(: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)endif 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 dofactory :product_in_stock doafter :create do |product|- product.master.stock_items.first.adjust_count_on_hand(10)+ product.default_variant.stock_items.first.adjust_count_on_hand(10)endtrait :without_backorder doafter :create do |product|- product.master.stock_items.update_all(backorderable: false)+ product.default_variant.stock_items.update_all(backorderable: false)endendenddiff --git a/spree/core/lib/spree/testing_support/factories/stock_location_factory.rb b/spree/core/lib/spree/testing_support/factories/stock_location_factory.rbindex 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 dofactory :stock_location_with_items doafter(: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 variantstore = 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)endendenddiff --git a/spree/core/spec/helpers/products_helper_spec.rb b/spree/core/spec/helpers/products_helper_spec.rbindex 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 Spreeallow(@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' doit { is_expected.to be_nil }end- context 'when the master has no price' do+ context 'when the default variant has no price' dolet(:product_price) { nil }it { is_expected.to be_nil }endcontext 'when currency is default' do- context 'when variant is more than master' do+ context 'when variant is more than the default variant' dolet(:variant_price) { 15 }it { is_expected.to eq('(Add: $5.00)') }@@ -46,7 +46,7 @@ module Spreeit { is_expected.to be_html_safe }end- context 'when variant is less than master' do+ context 'when variant is less than the default variant' dolet(:product_price) { 15 }it { is_expected.to eq('(Subtract: $5.00)') }@@ -58,13 +58,13 @@ module Spreelet(:product_price) { 100 }let(:currency) { 'JPY' }- context 'when variant is more than master' do+ context 'when variant is more than the default variant' dolet(: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' dolet(:product_price) { 150 }it { is_expected.to eq("(Subtract: \u00A550)") }@@ -80,7 +80,7 @@ module Spreeendcontext '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' doproduct.price = 10@variant1.price = 15@variant2.price = 20@@ -101,7 +101,7 @@ module Spreeendend- 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' doproduct.price = 100@variant1.price = 150expect(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.rbindex 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 dorow.reloadexpect(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 doexpect(row.reload.status).to eq('completed')expect(variant_row.reload.status).to eq('completed')- product = row.item.product+ product = row.itemexpect(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 dorow.reloadexpect(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 doexpect {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.reloadvariant_row.reloadexpect(row.status).to eq('completed')expect(variant_row.status).to eq('completed')- product = row.item.product+ product = row.itemexpect(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.rbindex 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 dodescribe '#perform' docontext 'with master-pinned assets' dolet!(: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' doexpect { subject }@@ -71,7 +71,7 @@ RSpec.describe Spree::Media::MigrateProductAssetsJob, type: :job docontext 'with mixed master + non-master assets' dolet!(: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' dodiff --git a/spree/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb b/spree/core/spec/jobs/spree/products/refresh_metrics_job_spec.rbindex 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 dosubject { 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' dosubjectdiff --git a/spree/core/spec/lib/tasks/media_spec.rb b/spree/core/spec/lib/tasks/media_spec.rbindex 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' dolet!(: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' dodiff --git a/spree/core/spec/models/concerns/spree/default_price_spec.rb b/spree/core/spec/models/concerns/spree/default_price_spec.rbindex 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 dolet(: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)' dobefore do@@ -80,9 +80,9 @@ RSpec.describe Spree::DefaultPrice dodescribe 'variant save without price' doit 'allows saving a variant without any price' donew_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_errorendenddiff --git a/spree/core/spec/models/spree/image_spec.rb b/spree/core/spec/models/spree/image_spec.rbindex 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 dolet(: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.reloadexpect(image).to receive(:touch_product_variants)image.set_list_position(2)end@@ -88,8 +88,8 @@ describe Spree::Image, type: :model dolet(: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)endit 'increments media_count when image is created on variant' do@@ -103,7 +103,7 @@ describe Spree::Image, type: :model doit 'tracks media across all variants correctly' doexpect(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 dodescribe 'primary_media_id updates' dolet(:product) { create(:product) }- let(:variant) { product.master }+ let(:variant) { product.default_variant }it 'sets variant primary_media_id when first image is created' doexpect(variant.primary_media_id).to be_nildiff --git a/spree/core/spec/models/spree/line_item_spec.rb b/spree/core/spec/models/spree/line_item_spec.rbindex 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 dolet(: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' doline_item.price = 10diff --git a/spree/core/spec/models/spree/price_list_spec.rb b/spree/core/spec/models/spree/price_list_spec.rbindex 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 doit 'creates prices for all supported currencies' doprice_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 doendit '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 doit 'enqueues a job to touch affected variants' doexpect {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])endit 'touches the price list to bust cache' do@@ -291,13 +291,13 @@ describe Spree::PriceList, type: :model docontext 'when price already has amount set' dobefore 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)endit 'does not overwrite existing price with amount' doprice_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 doit 'enqueues a job to touch affected variants' doexpect {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])endit 'touches the price list to bust cache' do@@ -400,7 +400,7 @@ describe Spree::PriceList, type: :model doit 'allows re-adding a product that had prices with amounts set' do# Add product and set some pricesprice_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])endendend@@ -421,8 +421,8 @@ describe Spree::PriceList, type: :model dolet(: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' doprices_attributes = [diff --git a/spree/core/spec/models/spree/product/scopes_spec.rb b/spree/core/spec/models/spree/product/scopes_spec.rbindex 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 doendcontext '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 doend# 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' doexpect { Spree::Product.in_stock.descend_by_price.to_a }.not_to raise_errorexpect { Spree::Product.in_stock.ascend_by_price.to_a }.not_to raise_error@@ -281,13 +281,13 @@ describe 'Product scopes', type: :model docontext 'with completed orders' dobefore 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 docontext 'with incomplete orders' dobefore 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 dobefore 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 dobefore 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 dobefore 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 docontext 'with products having only pending orders (no completed_at)' dobefore 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 alldiff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rbindex 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 dolet(: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 falseend- 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 trueendendend@@ -123,7 +115,7 @@ describe Spree::Product, type: :model doclone = duplicate_result.valueexpect(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 doendend- 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' doproduct.save- expect(product.master.reload.sku).to eq('Something changed')+ expect(product.default_variant.reload.sku).to eq('Something changed')endend+ 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/)endend- 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/)endend@@ -209,7 +192,7 @@ describe Spree::Product, type: :model doit 'sets deleted_at value' doproduct.destroyexpect(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_nilendendend@@ -223,7 +206,7 @@ describe Spree::Product, type: :model doit 'sets deleted_at value' doproduct.destroyexpect(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 trueendendend@@ -245,11 +228,11 @@ describe Spree::Product, type: :model docontext 'with currency set to JPY' dobefore do- product.master.set_price('JPY', 11)+ product.default_variant.set_price('JPY', 11)endit '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')endendend@@ -278,7 +261,7 @@ describe Spree::Product, type: :model doendit '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)endend@@ -295,7 +278,7 @@ describe Spree::Product, type: :model doendcontext '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 #3737context 'has stock items' doit '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_nilexpect(product.stock_items.first).not_to be_nilendend@@ -458,14 +441,6 @@ describe Spree::Product, type: :model docreate(: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' doproduct.saveexpect(product.option_type_ids.length).to eq(1)@@ -476,45 +451,52 @@ describe Spree::Product, type: :model doproduct.saveexpect(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' doproduct.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_emptyend- 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)endend- 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')endendend@@ -522,7 +504,7 @@ describe Spree::Product, type: :model dodescribe '#images' dolet(: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 doimages = [@@ -564,28 +546,28 @@ describe Spree::Product, type: :model doit 'is infinite if track_inventory_levels is false' doallow(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)endit 'is infinite if variant is on demand' doallow(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)endit 'returns sum of stock items count_on_hand' doproduct.stock_items.first.set_count_on_hand 5- product.variants_including_master.reload # force load association+ product.variants.reload # force load associationexpect(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' doproduct.stock_items.first.set_count_on_hand 5expect(product.reload.total_on_hand).to be(5)endend# Regression spec for https://github.com/spree/spree/issues/5588- describe '#validate_master when duplicate SKUs entered' do+ describe 'when duplicate SKUs are entered' dosubject { second_product }let!(:first_product) { create(:product, sku: 'a-sku') }@@ -594,11 +576,6 @@ describe Spree::Product, type: :model doit { 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!' dolet(:product) { create(:product, sku: 'a-sku') }@@ -673,7 +650,7 @@ describe Spree::Product, type: :model dodescribe '#ensure_not_in_complete_orders' dolet!(: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' doexpect(product.destroy).to eq false@@ -684,60 +661,41 @@ describe Spree::Product, type: :model dodescribe '#default_variant' dolet(: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')endendend@@ -745,28 +703,18 @@ describe Spree::Product, type: :model dodescribe '#default_variant_id' dolet(: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)endenddescribe '#primary_media' dolet(: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' doexpect(product.reload.primary_media).to eq(image)end@@ -774,13 +722,13 @@ describe Spree::Product, type: :model dolet!(: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)' doexpect(product.reload.primary_media).to eq(image)endendend- context 'when master has no images but variant does' do+ context 'when default variant has no images but variant does' dolet!(:variant) { create(:variant, product: product) }let!(:variant_image) { create(:image, viewable: variant) }@@ -805,7 +753,7 @@ describe Spree::Product, type: :model doendit '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 doit 'returns product media when present' doproduct_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)endit '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)endend@@ -840,7 +788,7 @@ describe Spree::Product, type: :model doendit '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 doendend- 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' doexpect(product.reload.has_variant_images?).to be true@@ -873,7 +821,7 @@ describe Spree::Product, type: :model doendcontext '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' doloaded_product = Spree::Product.includes(:variant_images).find(product.id)@@ -902,17 +850,6 @@ describe Spree::Product, type: :model doendend- 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' dolet!(:variant) { create(:variant, product: product) }let!(:image) { create(:image, viewable: variant) }@@ -932,8 +869,8 @@ describe Spree::Product, type: :model doendend- 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' doexpect(product.reload.media_count).to eq(2)@@ -968,31 +905,21 @@ describe Spree::Product, type: :model doendend- 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)endendcontext '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' doproduct.reload- expect(product.default_variant).to eq(variant1)+ expect(product.default_variant.has_media?).to be falseexpect(product.variant_for_images).to eq(variant2)endend@@ -1008,7 +935,7 @@ describe Spree::Product, type: :model doendcontext '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' doexpect(product.reload.secondary_image).to be_nil@@ -1016,15 +943,15 @@ describe Spree::Product, type: :model doendcontext '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' doexpect(product.reload.secondary_image).to eq(image2)endend- context 'when images are on a non-master variant' do+ context 'when images are on a option variant' dolet!(: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 dolet(: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 doexpect(loaded_product.has_images?).to be trueend- 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' doloaded_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 dolet!(: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' doit { 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 hooklet!(:variant) { create(:variant, product: product) }@@ -1147,30 +1065,30 @@ describe Spree::Product, type: :model doproduct.reloadend- 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' dobefore do- # make all stock items in stock, also for the master variant+ # make all stock items in stock, also for the default variantSpree::StockItem.all.each { |stock_item| stock_item.set_count_on_hand(1) }endit { 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' dobefore { 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' dobefore { 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' doit { 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' dobefore { stock_item.update(backorderable: true) }it { expect(subject).to eq(true) }@@ -1213,7 +1131,7 @@ describe Spree::Product, type: :model docsv_line = csv_lines.firstexpect(csv_line).to include(product.name)- expect(csv_line).to include(product.master.sku)+ expect(csv_line).to include(product.default_variant.sku)endend@@ -1222,15 +1140,15 @@ describe Spree::Product, type: :model dolet!(: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' docsv_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 dobefore dovariant1.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 doit 'appends price-only rows for additional currencies' docsv_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 rowsexpect(csv_lines.size).to eq(4)# First 2 rows are normal USD rows@@ -1268,7 +1186,7 @@ describe Spree::Product, type: :model doexpect(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 docurrency_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_nilexpect(eur_variant[slug_idx]).to eq product.slugexpect(eur_variant[sku_idx]).to eq variant1.sku@@ -1293,18 +1211,18 @@ describe Spree::Product, type: :model doendit '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 rowscsv_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')&.destroycsv_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 docontext 'without variants' doit 'returns the default variant' do- expect(subject).to eq(product.master)+ expect(subject).to eq(product.default_variant)endend@@ -1410,7 +1328,7 @@ describe Spree::Product, type: :model doendit 'returns the first variant' do- expect(subject).to eq(variant_1)+ expect(subject).to eq(product.variants.first)endendend@@ -1480,17 +1398,17 @@ describe Spree::Product, type: :model docontext 'without variants' dobefore 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' dolet(:currency) { 'USD' }it { is_expected.to be(true) }end- context 'when master variant is not available' do+ context 'when default variant is not available' dolet(:currency) { 'PLN' }it { is_expected.to be(false) }@@ -1667,14 +1585,14 @@ describe Spree::Product, type: :model dolet!(: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)endit 'orders products by minimum price ascending' do@@ -1693,11 +1611,11 @@ describe Spree::Product, type: :model dolet!(:variant2) { create(:variant, product: product_with_variants) }before do- product_with_variants.master.prices.delete_all+ product_with_variants.default_variant.prices.delete_allvariant1.prices.delete_allvariant2.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 dolet!(: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)endit 'orders products by maximum price descending' do@@ -1743,11 +1661,11 @@ describe Spree::Product, type: :model dolet!(:variant2) { create(:variant, product: product_with_variants) }before do- product_with_variants.master.prices.delete_all+ product_with_variants.default_variant.prices.delete_allvariant1.prices.delete_allvariant2.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 dodescribe '#has_variants?' dolet(:product) { create(:product) }- context 'without variants' do+ context 'a simple product (only the default variant)' doit 'returns false' doexpect(product.has_variants?).to be falseend- 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 1endend- context 'with variants' do+ context 'with additional variants' dobefore { create(:variant, product: product) }it 'returns true' doexpect(product.reload.has_variants?).to be trueend- 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 2endend@@ -1918,12 +1836,10 @@ describe Spree::Product, type: :model doexpect(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)endend@@ -1964,11 +1880,11 @@ describe Spree::Product, type: :model donew_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_presentend- 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' donew_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)endend@@ -2025,6 +1941,7 @@ describe Spree::Product, type: :model doexisting.save!variant = create(:variant, product: product)+ product.reload # refresh the variants cache so the out-of-band variant resolvesproduct.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.rbindex 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 dolet(: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 doallow(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.rbindex 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 Spreecontext 'and the product price is less than promo discount' dolet(: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 Spreecontext 'and the product price is greater than promo discount' dolet(: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 Spreebefore doallow(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) }endit 'successfully applies the promo' dodiff --git a/spree/core/spec/models/spree/reimbursement_spec.rb b/spree/core/spec/models/spree/reimbursement_spec.rbindex 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 docontext '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.rbindex 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 Spreeit 'returns all variants for the product' doSpree::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.sortendendenddiff --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.rbindex 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 Spreedescribe '.eligible_variants' docontext 'product has no variants' do- it 'returns the master variant for the same product' do+ it 'returns the default variant for the same product' doproduct = 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]endenddiff --git a/spree/core/spec/models/spree/stock/coordinator_spec.rb b/spree/core/spec/models/spree/stock/coordinator_spec.rbindex 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 Spreelet!(:order) doproduct.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.orderenddiff --git a/spree/core/spec/models/spree/stock/package_spec.rb b/spree/core/spec/models/spree/stock/package_spec.rbindex 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 Spreemethod2 = 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_variantcontents = [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.rbindex 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 dolet(: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)endlet!(: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)endit 'returns stock items for variants of products owned by the store' dodiff --git a/spree/core/spec/models/spree/stock_movement/custom_events_spec.rb b/spree/core/spec/models/spree/stock_movement/custom_events_spec.rbindex 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 dolet(:stock_location) { create(:stock_location) }let(:product) { create(:product) }- let(:variant) { product.master }+ let(:variant) { product.default_variant }let!(:stock_item) doitem = 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.rbindex 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 dolet!(: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' dolet!(:stock_items) { product.stock_items }@@ -79,8 +79,8 @@ describe Spree::Store, type: :model, without_global_store: true dodescribe '#inventory_units' dolet(: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]) }enddiff --git a/spree/core/spec/models/spree/tax_rate_spec.rb b/spree/core/spec/models/spree/tax_rate_spec.rbindex 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 docontext 'a download' dobefore do- Spree::Cart::AddItem.call(order: order, variant: download.master)+ Spree::Cart::AddItem.call(order: order, variant: download.default_variant)endit 'without an address costs 100 euros including tax' do@@ -284,7 +284,7 @@ describe Spree::TaxRate, type: :model docontext 'a t-shirt' doit 'to germany costs 100 euros including tax' doallow(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 doit 'to france costs 100 euros including tax' doallow(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 doit 'to somewhere else costs the net amount' doallow(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 doendcontext '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' doSpree::TaxRate.adjust(@order, @order.line_items)@@ -405,7 +405,7 @@ describe Spree::TaxRate, type: :model doendcontext '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' dobefore dodiff --git a/spree/core/spec/models/spree/taxon_spec.rb b/spree/core/spec/models/spree/taxon_spec.rbindex 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 doendcontext '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) docreate(:product).tap do |p|create(:variant, product: p, price: 10, compare_at_price: 12)@@ -833,7 +833,7 @@ describe Spree::Taxon, type: :model doendlet!(:product_on_sale_with_different_currency) docreate(: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')endendlet!(:product_not_on_sale) { create(:product, price: 10) }@@ -842,7 +842,7 @@ describe Spree::Taxon, type: :model doit 'matches products that are on sale in store\'s currency' docreate(: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)endenddiff --git a/spree/core/spec/models/spree/variant_media_spec.rb b/spree/core/spec/models/spree/variant_media_spec.rbindex 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 dolet!(: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' doexpect {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.rbindex 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 dolet(: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 doendend- 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- enddescribe '#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' dolet(:track_inventory) { false }@@ -163,7 +147,6 @@ describe Spree::Variant, type: :model dolet(:new_variant) doproduct.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 doendend- 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' dodescribe '.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)endend@@ -888,47 +828,22 @@ describe Spree::Variant, type: :model doenddescribe '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.saveend- context 'master variant' do+ context 'without option values' doit 'returns name' do- expect(master.exchange_name).to eql master.name+ expect(no_options_variant.exchange_name).to eql no_options_variant.nameendend- 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' doit 'returns options text' doexpect(variant.exchange_name).to eql 'Foo Type: Foo'end@@ -936,23 +851,22 @@ describe Spree::Variant, type: :model doenddescribe '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.saveend- 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.nameendend- context 'variant' do+ context 'with option values' doit 'returns options text with name' doexpect(variant.descriptive_name).to eql variant.name + ' - Foo Type: Foo'end@@ -1376,7 +1290,7 @@ describe Spree::Variant, type: :model doit 'adds an error' doexpect(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'))endend@@ -1399,7 +1313,7 @@ describe Spree::Variant, type: :model doit 'adds an error' doexpect(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'))endend@@ -1574,27 +1488,26 @@ describe Spree::Variant, type: :model dolet(: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' doexpect {create(:variant, product: product)- }.to change { product.reload.variant_count }.from(0).to(1)+ }.to change { product.reload.variant_count }.from(1).to(2)endit 'decrements when a variant is destroyed' dovariant = 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)endit 'correctly counts multiple variants' docreate_list(:variant, 3, product: product)- expect(product.reload.variant_count).to eq(3)+ expect(product.reload.variant_count).to eq(4)endendenddiff --git a/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rbindex 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 dolet(: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.rbindex 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 doendend- context 'product with only master variant' do+ context 'product with only default variant' dolet(: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>")endit 'includes product name as title' dodiff --git a/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb b/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rbindex 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 currencieslet(:product) dop = 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')pend@@ -162,7 +162,7 @@ module Spreelet(:product) dop = 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')penddiff --git a/spree/core/spec/presenters/spree/variants/option_types_presenter_spec.rb b/spree/core/spec/presenters/spree/variants/option_types_presenter_spec.rbindex 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 dobefore { 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' dobefore { variant_0.stock_items.first.update(backorderable: true) }@@ -89,6 +94,11 @@ describe Spree::Variants::OptionTypesPresenter dodescribe '#options' dosubject(: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' doexpect(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.rbindex 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 Spreecontext 'multiple shipments' dolet(: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.rbindex 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 docsv_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) docsv_row_hash('slug' => 'denim-shirt',@@ -38,7 +40,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendit 'creates a product and sets correct attributes' do- product = variant.product+ default_variant = product.default_variantexpect(product).to be_persistedexpect(product.slug).to eq 'denim-shirt'@@ -46,13 +48,12 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doexpect(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_locationendit 'enqueues AssignTagsJob' do@@ -64,8 +65,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendit '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 dobefore { store.channels.delete_all }it 'imports the product without publishing it to any channel' do- product = variant.product-expect(product).to be_persistedexpect(product.channels).to be_emptyendend- context 'when updating an existing master variant' do+ context 'when updating an existing product' dolet!(: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 = 50stock_item.backorderable = falsestock_item.save!endit '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 50expect(stock_item.backorderable).to eq false@@ -389,7 +386,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendend- context 'with images on a master variant row (no options)' do+ context 'with images on a product row (no options)' dolet!(:product) docreate(:product, slug: 'denim-shirt', name: 'Denim Shirt')end@@ -412,7 +409,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendend- context 'with images on a non-master variant row' do+ context 'with images on a variant row' dolet!(:product) docreate(: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).timescreated_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 docontext 'when importing a variant with all option columns empty' dolet!(:product) do- create(:product, slug: 'denim-shirt', name: 'Denim Shirt')+ create(:product, slug: 'denim-shirt', name: 'Denim Shirt', sku: 'DENIM-SHIRT-PLAIN')endlet(: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)endend@@ -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_persistedexpect(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'endend@@ -624,6 +636,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doimport.create_mappingsend+ let(:product) { subject.process! }+it 'creates mappings for metafields automatically' doexpect(import.mappings.where(schema_field: 'metafield.custom.brand').exists?).to be trueexpect(import.mappings.where(schema_field: 'metafield.custom.material').exists?).to be true@@ -643,8 +657,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendit 'sets metafields on the product' do- product = variant.product-expect(product).to be_persistedexpect(product.has_metafield?('custom.brand')).to be trueexpect(product.has_metafield?('custom.material')).to be true@@ -661,8 +673,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendit 'updates existing metafields' do- product = variant.product-expect(product.id).to eq existing_product.idexpect(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 doendit 'skips blank metafield values' do- product = variant.product-expect(product.has_metafield?('custom.brand')).to be trueexpect(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 doit 'removes existing metafield when empty value is uploaded' doexpect(existing_product.metafields.count).to eq 2- product = variant.product-expect(product.id).to eq existing_product.idexpect(product.has_metafield?('custom.brand')).to be trueexpect(product.get_metafield('custom.brand').value).to eq 'New Brand'@@ -745,8 +751,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doit 'removes all existing metafields' doexpect(existing_product.metafields.count).to eq 2- product = variant.product-expect(product.id).to eq existing_product.idexpect(product.has_metafield?('custom.brand')).to be falseexpect(product.has_metafield?('custom.material')).to be false@@ -755,7 +759,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendend- context 'when processing a non-master variant row' do+ context 'when processing a variant row' dolet!(:existing_product) dop = 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 doendcontext 'when importing with shipping_category' do+ let(:product) { subject.process! }+context 'when shipping_category exists' dolet!(:digital_category) { create(:shipping_category, name: 'Digital') }@@ -809,7 +815,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendit 'assigns the shipping category to the product' do- product = variant.productexpect(product.shipping_category).to eq digital_categoryendend@@ -827,7 +832,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendit 'assigns the default shipping category' do- product = variant.productexpect(product.shipping_category).to be_presentexpect(product.shipping_category.name).to eq 'Default'end@@ -852,8 +856,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendit 'updates the shipping category' do- product = variant.product-expect(product.id).to eq existing_product.idexpect(product.shipping_category).to eq digital_categoryend@@ -871,8 +873,6 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendit 'assigns the default shipping category' do- product = variant.product-expect(product.shipping_category).to be_presentexpect(product.shipping_category.name).to eq 'Default'end@@ -880,6 +880,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendcontext 'when importing with tax_category' do+ let(:product) { subject.process! }+context 'when tax_category exists' dolet!(: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_taxendend@@ -912,7 +914,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendit 'does not assign a tax category' do- expect(variant.tax_category).to be_nil+ expect(product.default_variant.tax_category).to be_nilendend@@ -921,7 +923,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service dolet!(:clothing_tax) { create(:tax_category, name: 'Clothing') }let!(:existing_product) dop = create(:product, slug: 'product-to-update', name: 'Product')- p.master.update(tax_category: standard_tax)+ p.default_variant.update(tax_category: standard_tax)pend@@ -937,10 +939,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendit '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_taxendend@@ -956,11 +956,11 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendit 'does not assign a tax category' do- expect(variant.tax_category).to be_nil+ expect(product.default_variant.tax_category).to be_nilendend- context 'when importing a non-master variant with tax_category' do+ context 'when importing an option variant with tax_category' dolet!(:clothing_tax) { create(:tax_category, name: 'Clothing') }let!(:product) dop = 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_taxendenddiff --git a/spree/core/spec/services/spree/orders/create_spec.rb b/spree/core/spec/services/spree/orders/create_spec.rbindex 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) docreate(: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)endendlet(:params) dodiff --git a/spree/core/spec/services/spree/products/duplicator_spec.rb b/spree/core/spec/services/spree/products/duplicator_spec.rbindex 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 dolet!(: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 dobefore dofile = 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)endit { is_expected.to be_success }@@ -77,8 +77,8 @@ RSpec.describe Spree::Products::Duplicator doendit '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)endend@@ -86,18 +86,18 @@ RSpec.describe Spree::Products::Duplicator dolet(: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)endit 'clones prices' doexpect(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 doendit '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 wellexpect { duplicate }.to change { Spree::Variant.count }.by(3)end@@ -134,7 +134,7 @@ RSpec.describe Spree::Products::Duplicator doendit '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')endit 'clones backorderable and sets stock to 0' dodiff --git a/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb b/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rbindex 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 doenddescribe 'prices_attributes handling' do- let(:variant) { product.master }+ let(:variant) { product.default_variant }context 'when user cannot update prices' dobefore do@@ -67,22 +67,6 @@ RSpec.describe Spree::Products::PrepareNestedAttributes doexpect(prepared_params[:variants_attributes]['0']).not_to have_key(:prices_attributes)endend-- 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- endendcontext 'when user can update prices' do@@ -270,7 +254,7 @@ RSpec.describe Spree::Products::PrepareNestedAttributes doenddescribe 'stock_items_attributes handling' do- let(:variant) { product.master }+ let(:variant) { product.default_variant }context 'when user cannot update stock items' dobefore do@@ -295,22 +279,6 @@ RSpec.describe Spree::Products::PrepareNestedAttributes doexpect(prepared_params[:variants_attributes]['0']).not_to have_key(:stock_items_attributes)endend-- 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- endendendenddiff --git a/spree/core/spec/services/spree/sample_data/loader_spec.rb b/spree/core/spec/services/spree/sample_data/loader_spec.rbindex 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:endit 'creates variants' do- expect(Spree::Variant.count).to be > 100+ expect(Spree::Variant.count).to be > 80endit 'creates customers' dodiff --git a/spree/core/spec/services/spree/shipments/add_item_spec.rb b/spree/core/spec/services/spree/shipments/add_item_spec.rbindex 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 Spreelet(: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.rbindex 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 Spreelet(: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.rbindex 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 Spreebefore { 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)endenddiff --git a/spree/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb b/spree/core/spec/subscribers/spree/product_metrics_subscriber_spec.rbindex 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 dolet(:order) docreate(: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)endend@@ -100,8 +100,8 @@ RSpec.describe Spree::ProductMetricsSubscriber docontext 'when order has duplicate products' dolet(:order_with_duplicates) docreate(: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)endend