Class: Spree::Variant
- Inherits:
-
Object
- Object
- Spree::Variant
- Includes:
- CanonicalDecimals, HasCustomFields, HasExternalReferences, MemoizedData, Metadata, Searchable, StorePreferences
- Defined in:
- app/models/spree/variant.rb
Constant Summary collapse
- MEMOIZED_METHODS =
%w(in_stock on_sale backorderable tax_category tax_category_id options_text compare_at_price)
- DIMENSION_UNITS =
%w[mm cm in ft]
- WEIGHT_UNITS =
%w[g kg lb oz]
- PURCHASE_UNITS =
What a buyer is quoted in. Stored quantities are units at every level; this only changes the vocabulary a storefront presents.
%w[unit carton]
Class Method Summary collapse
-
.for_option_filters(currency = nil, in_stock: false, store: Spree::Current.store) ⇒ ActiveRecord::Relation<Spree::Variant>
The variants a storefront option filter matches and counts.
- .product_name_or_sku_cont(query) ⇒ Object
-
.search(query) ⇒ Object
Free-text variant search: SKU, parent product name, and any option-value presentation (e.g. "Red", "XL").
- .search_by_product_name_or_sku(query) ⇒ Object
- .store_dimensions_unit(store) ⇒ String
Instance Method Summary collapse
-
#additional_images ⇒ Array<Spree::Media>
deprecated
Deprecated.
Read #gallery_media directly; removed in 6.3. Nothing in Spree calls this, and which images to show beside the main one is a storefront presentation choice.
-
#amount_in(currency) ⇒ BigDecimal
Returns the amount for the given currency.
-
#available? ⇒ Boolean
Returns true if the variant is available.
-
#backorderable? ⇒ Boolean
(also: #is_backorderable?)
Returns true if the variant is backorderable.
- #backordered? ⇒ Boolean
-
#carton_volume ⇒ BigDecimal?
The cubic meters one packed carton of this variant occupies.
-
#cartons_for(quantity) ⇒ Integer?
How many cartons a unit quantity fills, rounded up — a part carton still ships as a carton.
-
#compare_at_amount_in(currency) ⇒ BigDecimal
Returns the compare at amount for the given currency.
-
#compare_at_price ⇒ BigDecimal
Returns the compare at price of the variant.
-
#customs_description_for_declaration ⇒ String?
Plain-language contents description for a customs declaration.
- #default_stock_location ⇒ Object
-
#descriptive_name ⇒ String
Returns the descriptive name of the variant.
-
#digital? ⇒ Boolean
Is this variant purely digital? (no physical product).
- #dimension ⇒ Object
-
#dimensions_unit ⇒ String
The unit this variant's width/height/depth are expressed in.
- #discontinue! ⇒ Object
- #discontinued? ⇒ Boolean
-
#exchange_name ⇒ String
Returns the exchange name of the variant.
-
#find_option_value(opt_name) ⇒ Spree::OptionValue
Returns the option value for the given option name.
-
#gallery_media ⇒ ActiveRecord::Relation
Returns the variant's media gallery.
-
#has_associated_media? ⇒ Boolean
True if any product-level media is linked to this variant.
-
#has_media? ⇒ Boolean
(also: #has_images?)
Returns true if the variant has media (linked product-level or direct images).
-
#human_name ⇒ String
Returns the human name of the variant.
-
#in_stock? ⇒ Boolean
Returns true if the variant is in stock.
-
#in_stock_or_backorderable? ⇒ Boolean
Returns true if the variant is in stock or backorderable.
- #on_sale?(currency) ⇒ Boolean
-
#option_value(option_type) ⇒ String
Returns the presentation of the option value for the given option type.
-
#options ⇒ Array<Hash>
Returns an array of hashes with the option type name, value and label.
-
#options=(options = {}) ⇒ void
Sets the option values for the variant.
-
#options_text ⇒ String
Returns the options text of the variant.
-
#oversellable_now? ⇒ Boolean
Whether the variant can currently be bought by overselling — via backorder or pre-order.
-
#owned_by_product_seller? ⇒ Boolean
Whether this variant sits on an owned product — the mode in which the variant's own seller and delivery-profile columns carry no meaning.
-
#preference_store ⇒ Spree::Store?
Variants carry no store of their own; the product owns it.
-
#preorder? ⇒ Boolean
Returns true if the variant is sold as a pre-order: the product is active and not deleted, the variant is flagged preorderable and not discontinued, and the "ships by" date is open-ended or still in the future.
-
#price_for(context_or_options) ⇒ Spree::Price?
Returns the price for the given context or options.
-
#price_in(currency) ⇒ Spree::Price
Returns the base price (global price, not from a price list) for the given currency.
-
#price_modifier_amount(options = {}) ⇒ BigDecimal
Returns the price modifier amount of the variant.
- #price_modifier_amount_in(currency, options = {}) ⇒ Object
-
#prices=(prices_params) ⇒ void
Syncs base prices from an array of hashes.
- #purchasable? ⇒ Boolean
-
#purchasable_in?(currency, quote: nil) ⇒ Boolean
Whether a shopper could put this in a cart in the currency.
-
#quantity_rule ⇒ Spree::QuantityRule
The variant's own purchasing rules — the base every cart obeys, and the floor a buyer falls back to when their catalogs state nothing.
-
#resolved_delivery_profile ⇒ Spree::DeliveryProfile?
How this variant ships, on the same two-mode rule as the seller, keyed on OWNERSHIP rather than on whether the product has a profile — every product does, so "product's profile if set" would never reach the variant's own and no seller on a master could ship differently.
- #resolved_delivery_profile_id ⇒ Integer?
-
#resolved_seller ⇒ Spree::Seller?
Who sells this variant.
- #resolved_seller_id ⇒ Integer?
-
#secondary_image ⇒ Spree::Media?
deprecated
Deprecated.
Read #gallery_media directly; removed in 6.3. Nothing in Spree calls this — a hover image is a storefront presentation choice, not something core should name.
-
#set_option_value(opt_name, opt_value, opt_type_position = nil) ⇒ void
Sets the option value for the given option name.
-
#set_price(currency, amount, compare_at_amount = nil) ⇒ void
Sets the base price (global price, not for a price list) for the given currency.
-
#set_stock(count_on_hand, backorderable = nil, stock_location = nil) ⇒ void
Sets the count at a location.
-
#should_track_inventory? ⇒ Boolean
Shortcut method to determine if inventory tracking is enabled for this variant This considers both the variant tracking flag and the store's setting.
-
#sold_by_carton? ⇒ Boolean
True when this variant is quoted in cartons rather than units.
-
#stock_items ⇒ Object
deprecated
Deprecated.
Use #stock_levels; removed in 6.3.
-
#stock_items=(value) ⇒ Object
deprecated
Deprecated.
Use #stock_levels=; removed in 6.3.
-
#stock_items_attributes=(value) ⇒ Object
deprecated
Deprecated.
Use
stock_levels_attributes=; removed in 6.3. -
#stock_levels=(stock_levels_params) ⇒ void
Syncs stock items from an array of hashes.
-
#stock_levels_attributes=(rows) ⇒ void
The v3 API sends
stock_levels: [...], which the params normalizer rewrites to nested attributes — and Rails would then write count_on_hand straight onto the row. -
#tax_category ⇒ Spree::TaxCategory
Returns tax category for Variant.
-
#tax_category_id ⇒ Integer
Returns tax category ID for Variant.
-
#thumbnail ⇒ Spree::Media?
The variant's own image, or its product's when it has none — the picture a list row shows for it.
-
#units_per_pallet ⇒ Integer?
How many units a full pallet of this variant holds.
-
#update_thumbnail! ⇒ Object
Updates primary_media_id to the first media item by position.
-
#volume ⇒ BigDecimal
The cubic meters one unit of this variant occupies.
-
#weight_unit ⇒ String
Returns the weight unit for the variant Falls back to the variant's own store, like #dimensions_unit below — on a multi-store install the default store's unit is someone else's, and converting a kilogram catalog as pounds misweighs every quote.
- #with_digital_assets? ⇒ Boolean
Methods included from StorePreferences
current, read, #store_preference
Methods included from HasExternalReferences
#assign_external_references, #external_id_for, #set_external_id
Methods included from Metadata
#private_metadata, #private_metadata=
Class Method Details
.for_option_filters(currency = nil, in_stock: false, store: Spree::Current.store) ⇒ ActiveRecord::Relation<Spree::Variant>
The variants a storefront option filter matches and counts. The rules
Product.available (a base price, unless the store lists products
without one) and Product.in_stock apply to a product as a whole, so a
value carried only by an unpriced, sold-out or discontinued variant
would otherwise offer the shopper a product they cannot buy in it.
189 190 191 192 193 194 195 196 197 198 199 |
# File 'app/models/spree/variant.rb', line 189 def self.for_option_filters(currency = nil, in_stock: false, store: Spree::Current.store) scope = not_discontinued unless Spree::StorePreferences.read(store, :show_products_without_price) priced = for_currency_and_available_price_amount(currency || Spree::Current.currency) scope = scope.where(id: priced.select(:id)) end scope = scope.where(id: in_stock_or_backorderable.select(:id)) if in_stock scope end |
.product_name_or_sku_cont(query) ⇒ Object
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
# File 'app/models/spree/variant.rb', line 355 def self.product_name_or_sku_cont(query) sanitized_query = ActiveRecord::Base.sanitize_sql_like(query.to_s.downcase.strip) query_pattern = "%#{sanitized_query}%" sku_condition = arel_table[:sku].lower.matches(query_pattern) if Spree.use_translations? translation_arel_table = Product::Translation.arel_table.alias(Product.translation_table_alias)[:name] product_name_condition = translation_arel_table.lower.matches(query_pattern) joins(:product). join_translation_table(Product). where(product_name_condition.or(sku_condition)) else product_name_condition = Product.arel_table[:name].lower.matches(query_pattern) joins(:product).where(product_name_condition.or(sku_condition)) end end |
.search(query) ⇒ Object
Free-text variant search: SKU, parent product name, and any option-value presentation (e.g. "Red", "XL"). The 3-char floor keeps single-letter queries from triggering a full scan.
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
# File 'app/models/spree/variant.rb', line 294 def self.search(query) return none if query.blank? || query.length < 3 conditions = [ search_condition(self, :sku, query), search_condition(Spree::OptionValue, :label, query), ] if Spree.use_translations? translation_table = Product::Translation.arel_table.alias(Product.translation_table_alias) sanitized = sanitize_query_for_search(query) conditions << translation_table[:name].lower.matches("%#{sanitized}%", '\\') else conditions << search_condition(Spree::Product, :name, query) end relation = joins(:product).left_joins(:option_values) relation = relation.join_translation_table(Product) if Spree.use_translations? relation.where(conditions.reduce(:or)).distinct end |
.search_by_product_name_or_sku(query) ⇒ Object
373 374 375 |
# File 'app/models/spree/variant.rb', line 373 def self.search_by_product_name_or_sku(query) product_name_or_sku_cont(query) end |
Instance Method Details
#additional_images ⇒ Array<Spree::Media>
Read #gallery_media directly; removed in 6.3. Nothing in Spree calls this, and which images to show beside the main one is a storefront presentation choice.
584 585 586 587 |
# File 'app/models/spree/variant.rb', line 584 def additional_images Spree::Deprecation.warn('Spree::Variant#additional_images is deprecated and will be removed in Spree 6.3. Use #gallery_media instead.') gallery_media.reject { |media| media.id == primary_media&.id } end |
#amount_in(currency) ⇒ BigDecimal
Returns the amount for the given currency.
716 717 718 |
# File 'app/models/spree/variant.rb', line 716 def amount_in(currency) price_in(currency).try(:amount) end |
#available? ⇒ Boolean
Returns true if the variant is available.
389 390 391 |
# File 'app/models/spree/variant.rb', line 389 def available? !discontinued? && product.available? end |
#backorderable? ⇒ Boolean Also known as: is_backorderable?
Returns true if the variant is backorderable.
969 970 971 |
# File 'app/models/spree/variant.rb', line 969 def backorderable? @backorderable ||= quantifier.backorderable? end |
#backordered? ⇒ Boolean
1078 1079 1080 |
# File 'app/models/spree/variant.rb', line 1078 def backordered? @backordered ||= !in_stock? && stock_levels.exists?(backorderable: true) end |
#carton_volume ⇒ BigDecimal?
The cubic meters one packed carton of this variant occupies. Geometry comes from the shared carton row, so correcting a carton size fixes every product packed in it.
1134 1135 1136 |
# File 'app/models/spree/variant.rb', line 1134 def carton_volume carton_package_type&.volume end |
#cartons_for(quantity) ⇒ Integer?
How many cartons a unit quantity fills, rounded up — a part carton still ships as a carton. Nil when the variant declares no carton size.
1123 1124 1125 1126 1127 |
# File 'app/models/spree/variant.rb', line 1123 def cartons_for(quantity) return nil unless units_per_carton.to_i.positive? (quantity.to_i / units_per_carton.to_f).ceil end |
#compare_at_amount_in(currency) ⇒ BigDecimal
Returns the compare at amount for the given currency.
723 724 725 |
# File 'app/models/spree/variant.rb', line 723 def compare_at_amount_in(currency) price_in(currency).try(:compare_at_amount) end |
#compare_at_price ⇒ BigDecimal
Returns the compare at price of the variant.
957 958 959 |
# File 'app/models/spree/variant.rb', line 957 def compare_at_price @compare_at_price ||= price_in(cost_currency).try(:compare_at_amount) end |
#customs_description_for_declaration ⇒ String?
Plain-language contents description for a customs declaration. Customs authorities reject marketing names, so merchants set an explicit one; the product name is the fallback that keeps a declaration valid.
522 523 524 |
# File 'app/models/spree/variant.rb', line 522 def customs_description_for_declaration customs_description.presence || name end |
#default_stock_location ⇒ Object
922 923 924 |
# File 'app/models/spree/variant.rb', line 922 def default_stock_location Spree::Store.current.default_stock_location end |
#descriptive_name ⇒ String
Returns the descriptive name of the variant.
514 515 516 |
# File 'app/models/spree/variant.rb', line 514 def descriptive_name option_values.any? ? "#{name} - #{}" : name end |
#digital? ⇒ Boolean
Is this variant purely digital? (no physical product)
Answered by the variant's own profile so a download and its printed edition can sit on one product — the profile kind declares it, here as everywhere else.
1089 1090 1091 |
# File 'app/models/spree/variant.rb', line 1089 def digital? !!resolved_delivery_profile&.digital? end |
#dimension ⇒ Object
1035 1036 1037 |
# File 'app/models/spree/variant.rb', line 1035 def dimension (width || 0) + (height || 0) + (depth || 0) end |
#dimensions_unit ⇒ String
The unit this variant's width/height/depth are expressed in. Falls back to what the store's unit system implies, which is what every other dimension in the store already means — there is no separate store preference for it, so a second settable value cannot contradict the first. Mirrors #weight_unit, which has always resolved this way.
Surfaces that show or export what the merchant actually stored — the CSV export, so a round-trip does not stamp one store's unit onto every variant — read the raw column instead.
1059 1060 1061 |
# File 'app/models/spree/variant.rb', line 1059 def dimensions_unit attributes['dimensions_unit'].presence || self.class.store_dimensions_unit(preference_store) end |
#discontinue! ⇒ Object
1070 1071 1072 |
# File 'app/models/spree/variant.rb', line 1070 def discontinue! update_attribute(:discontinue_on, Time.current) end |
#discontinued? ⇒ Boolean
1074 1075 1076 |
# File 'app/models/spree/variant.rb', line 1074 def discontinued? !!discontinue_on && discontinue_on <= Time.current end |
#exchange_name ⇒ String
Returns the exchange name of the variant.
508 509 510 |
# File 'app/models/spree/variant.rb', line 508 def exchange_name option_values.any? ? : name end |
#find_option_value(opt_name) ⇒ Spree::OptionValue
Returns the option value for the given option name.
670 671 672 |
# File 'app/models/spree/variant.rb', line 670 def find_option_value(opt_name) option_values.includes(:option_type).detect { |o| o.option_type.name.parameterize == opt_name.parameterize } end |
#gallery_media ⇒ ActiveRecord::Relation
Returns the variant's media gallery. Prefers product-level media linked via variant_media (5.5+) — these reuse a single blob across variants. Falls back to direct variant images for legacy uploads.
531 532 533 534 535 |
# File 'app/models/spree/variant.rb', line 531 def gallery_media return associated_media if has_associated_media? images end |
#has_associated_media? ⇒ Boolean
Returns true if any product-level media is linked to this variant.
550 551 552 553 554 |
# File 'app/models/spree/variant.rb', line 550 def has_associated_media? return variant_media.any? if variant_media.loaded? variant_media.exists? end |
#has_media? ⇒ Boolean Also known as: has_images?
Returns true if the variant has media (linked product-level or direct images). Uses loaded associations when available, otherwise falls back to counter cache.
540 541 542 543 544 545 |
# File 'app/models/spree/variant.rb', line 540 def has_media? return true if has_associated_media? return images.any? if images.loaded? media_count.positive? end |
#human_name ⇒ String
Returns the human name of the variant.
379 380 381 382 383 384 385 |
# File 'app/models/spree/variant.rb', line 379 def human_name @human_name ||= option_values. joins(option_type: :product_option_types). merge(product.product_option_types). reorder('spree_product_option_types.position'). pluck(:label).join('/') end |
#in_stock? ⇒ Boolean
Returns true if the variant is in stock.
963 964 965 |
# File 'app/models/spree/variant.rb', line 963 def in_stock? @in_stock ||= total_on_hand.positive? end |
#in_stock_or_backorderable? ⇒ Boolean
Returns true if the variant is in stock or backorderable.
408 409 410 |
# File 'app/models/spree/variant.rb', line 408 def in_stock_or_backorderable? self.class.in_stock_or_backorderable.exists?(id: id) end |
#on_sale?(currency) ⇒ Boolean
973 974 975 |
# File 'app/models/spree/variant.rb', line 973 def on_sale?(currency) @on_sale ||= price_in(currency)&.discounted? end |
#option_value(option_type) ⇒ String
Returns the presentation of the option value for the given option type.
677 678 679 680 681 682 683 |
# File 'app/models/spree/variant.rb', line 677 def option_value(option_type) if option_type.is_a?(Spree::OptionType) option_values.detect { |o| o.option_type_id == option_type.id }.try(:label) else find_option_value(option_type).try(:label) end end |
#options ⇒ Array<Hash>
Returns an array of hashes with the option type name, value and label.
The presentation key keeps its name through the 6.0 column rename: it
is a return shape host apps read, nothing in Spree consumes it, and a
renamed hash key breaks silently.
596 597 598 599 600 601 602 603 604 605 606 607 608 |
# File 'app/models/spree/variant.rb', line 596 def @options ||= option_values. includes(option_type: :product_option_types). merge(product.product_option_types). reorder('spree_product_option_types.position'). map do |option_value| { name: option_value.option_type.name, value: option_value.name, presentation: option_value.label } end end |
#options=(options = {}) ⇒ void
This method returns an undefined value.
Sets the option values for the variant
613 614 615 616 617 618 619 620 621 622 623 624 |
# File 'app/models/spree/variant.rb', line 613 def ( = {}) if product.nil? @pending_options = return end .each do |option| next if option[:name].blank? || option[:value].blank? set_option_value(option[:name], option[:value], option[:position]) end end |
#options_text ⇒ String
Returns the options text of the variant.
494 495 496 497 498 499 500 501 502 503 504 |
# File 'app/models/spree/variant.rb', line 494 def @options_text ||= if read_association_in_memory?(:option_values) option_values.sort_by do |ov| ov.option_type.position end.map { |ov| "#{ov.option_type.label}: #{ov.label}" }.to_sentence(words_connector: ', ', two_words_connector: ', ') else option_values.includes(:option_type).joins(:option_type).order("#{Spree::OptionType.table_name}.position").map do |ov| "#{ov.option_type.label}: #{ov.label}" end.to_sentence(words_connector: ', ', two_words_connector: ', ') end end |
#oversellable_now? ⇒ Boolean
Whether the variant can currently be bought by overselling — via
backorder or pre-order. Unlimited when backorder_limit is nil (empty =
no cap); with a limit, purchasable only while the oversell allowance
remains.
1002 1003 1004 1005 1006 |
# File 'app/models/spree/variant.rb', line 1002 def oversellable_now? return false unless backorderable? || preorder? backorder_limit.nil? || can_supply?(1) end |
#owned_by_product_seller? ⇒ Boolean
Whether this variant sits on an owned product — the mode in which the variant's own seller and delivery-profile columns carry no meaning.
463 464 465 |
# File 'app/models/spree/variant.rb', line 463 def owned_by_product_seller? product&.seller_id.present? end |
#preference_store ⇒ Spree::Store?
Variants carry no store of their own; the product owns it.
1016 1017 1018 1019 1020 1021 1022 1023 |
# File 'app/models/spree/variant.rb', line 1016 def preference_store # The request's store instance when it is this one, so a page of # variants reads its settings from one record rather than a copy each. current_store = Spree::Current.store return current_store if current_store && product&.store_id == current_store.id product&.store end |
#preorder? ⇒ Boolean
Returns true if the variant is sold as a pre-order: the product is active
and not deleted, the variant is flagged preorderable and not discontinued,
and the "ships by" date is open-ended or still in the future.
Pre-order relaxes only the publish-date embargo, not the rest of the
availability rules. Like backorder, a pre-order can make the variant
purchasable beyond on-hand stock; the oversell cap is backorder_limit
(empty ⇒ unlimited), and it adds the ship-by promise.
401 402 403 404 |
# File 'app/models/spree/variant.rb', line 401 def preorder? !discontinued? && preorderable? && product.active? && !product.deleted? && (preorder_ships_at.nil? || preorder_ships_at > Time.current) end |
#price_for(context_or_options) ⇒ Spree::Price?
Returns the price for the given context or options.
Answered by the store's pricing provider, which is Spree's own resolver unless a connector has been configured. An external provider's price is an unsaved, readonly Spree::Price — see Spree::PricingProvider::Base.
872 873 874 875 876 877 878 879 880 881 882 |
# File 'app/models/spree/variant.rb', line 872 def price_for() context = if .is_a?(Spree::Pricing::Context) elsif .is_a?(Hash) Spree::Pricing::Context.new(**.merge(variant: self)) else raise ArgumentError, 'Must provide a Pricing::Context or options hash' end Spree::Pricing::PriceResolution.call(context) end |
#price_in(currency) ⇒ Spree::Price
Returns the base price (global price, not from a price list) for the given currency. Use price_for(context) when you need to resolve prices including price lists.
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 |
# File 'app/models/spree/variant.rb', line 689 def price_in(currency) currency = currency&.upcase price = if read_association_in_memory?(:prices) prices.detect { |p| p.currency == currency && p.price_list_id.nil? } else prices.base_prices.find_by(currency: currency) end if price.nil? return Spree::Price.new( currency: currency, variant_id: id ) end price rescue TypeError Spree::Price.new( currency: currency, variant_id: id ) end |
#price_modifier_amount(options = {}) ⇒ BigDecimal
Returns the price modifier amount of the variant.
942 943 944 945 946 947 948 949 950 951 952 953 |
# File 'app/models/spree/variant.rb', line 942 def price_modifier_amount( = {}) return 0 unless .present? .keys.map do |key| m = "#{key}_price_modifier_amount".to_sym if respond_to? m send(m, [key]) else 0 end end.sum end |
#price_modifier_amount_in(currency, options = {}) ⇒ Object
926 927 928 929 930 931 932 933 934 935 936 937 |
# File 'app/models/spree/variant.rb', line 926 def price_modifier_amount_in(currency, = {}) return 0 unless .present? .keys.map do |key| m = "#{key}_price_modifier_amount_in".to_sym if respond_to? m send(m, currency, [key]) else 0 end end.sum end |
#prices=(prices_params) ⇒ void
This method returns an undefined value.
Syncs base prices from an array of hashes.
Upserts prices for listed currencies, removes base prices for unlisted currencies.
On new records, builds prices in memory (saved when variant is saved).
On persisted records, saves prices immediately and removes unlisted currencies.
An empty array clears every base price — distinguished from nil (no
change requested), which falls through to the default ActiveRecord setter.
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 |
# File 'app/models/spree/variant.rb', line 735 def prices=(prices_params) return super if prices_params.nil? || prices_params.first.is_a?(Spree::Price) currencies_in_payload = [] prices_params.each do |price_data| price_data = price_data.to_h.with_indifferent_access currencies_in_payload << price_data[:currency] set_price(price_data[:currency], price_data[:amount], price_data[:compare_at_amount]) end # Remove base prices for currencies not in the payload (including the # `prices_params == []` case, which clears every base price). prices.base_prices.where.not(currency: currencies_in_payload).destroy_all if persisted? end |
#purchasable? ⇒ Boolean
981 982 983 |
# File 'app/models/spree/variant.rb', line 981 def purchasable? in_stock? || oversellable_now? end |
#purchasable_in?(currency, quote: nil) ⇒ Boolean
Whether a shopper could put this in a cart in the currency. Stock alone is not enough: the cart refuses a variant unless it has a base price there or a price list or pricing provider quoted one for the shopper.
992 993 994 |
# File 'app/models/spree/variant.rb', line 992 def purchasable_in?(currency, quote: nil) purchasable? && (quote&.amount.present? || amount_in(currency).present?) end |
#quantity_rule ⇒ Spree::QuantityRule
The variant's own purchasing rules — the base every cart obeys, and the floor a buyer falls back to when their catalogs state nothing. A buyer's effective rules resolve through Catalogs::ResolveQuantityRules; nothing below the cart layer reads either.
1103 1104 1105 1106 1107 1108 |
# File 'app/models/spree/variant.rb', line 1103 def quantity_rule Spree::QuantityRule.new( minimum_order_quantity: minimum_order_quantity, order_multiple: order_multiple ) end |
#resolved_delivery_profile ⇒ Spree::DeliveryProfile?
How this variant ships, on the same two-mode rule as the seller, keyed on OWNERSHIP rather than on whether the product has a profile — every product does, so "product's profile if set" would never reach the variant's own and no seller on a master could ship differently.
- Owned product: every variant ships as the product does; the variant's own column is meaningless and is kept blank.
- Master product: each seller's row names how that seller ships, and falls back to the master's profile when it does not.
A plain read, not memoized.
480 481 482 483 484 |
# File 'app/models/spree/variant.rb', line 480 def resolved_delivery_profile return product&.resolved_delivery_profile if owned_by_product_seller? delivery_profile || product&.resolved_delivery_profile end |
#resolved_delivery_profile_id ⇒ Integer?
487 488 489 |
# File 'app/models/spree/variant.rb', line 487 def resolved_delivery_profile_id resolved_delivery_profile&.id end |
#resolved_seller ⇒ Spree::Seller?
Who sells this variant. Two modes, and they never mix:
- An OWNED product (
product.seller_idset) — every variant is that seller's, by definition. No other seller can create a variant here, so the variant's own column is meaningless and is kept blank. - A MASTER product (
product.seller_idnil) — the shared catalog. This is the only placevariant.seller_idmeans anything: several sellers list variants on one page, and each row names its own.
So the answer is the product's seller if it has one, else the variant's own — a plain read, not an inheritance chain. Line items snapshot it at add-to-cart, and the buy box and SKU check read it. Nil is first-party.
450 451 452 |
# File 'app/models/spree/variant.rb', line 450 def resolved_seller product&.seller || seller end |
#resolved_seller_id ⇒ Integer?
455 456 457 |
# File 'app/models/spree/variant.rb', line 455 def resolved_seller_id product&.seller_id || self[:seller_id] end |
#secondary_image ⇒ Spree::Media?
Read #gallery_media directly; removed in 6.3. Nothing in Spree calls this — a hover image is a storefront presentation choice, not something core should name.
575 576 577 578 |
# File 'app/models/spree/variant.rb', line 575 def secondary_image Spree::Deprecation.warn('Spree::Variant#secondary_image is deprecated and will be removed in Spree 6.3. Use #gallery_media instead.') gallery_media.second end |
#set_option_value(opt_name, opt_value, opt_type_position = nil) ⇒ void
This method returns an undefined value.
Sets the option value for the given option name.
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 |
# File 'app/models/spree/variant.rb', line 631 def set_option_value(opt_name, opt_value, opt_type_position = nil) # The product's own store: option types are store-owned, and matching one # by name elsewhere would attach and extend another store's type. option_type = Spree::OptionType.for_store(product.store).where(name: opt_name.parameterize).first_or_initialize do |o| o.name = o.label = opt_name o.store = product.store o.save! end current_value = find_option_value(opt_name) if current_value.nil? # then we have to check to make sure that the product has the option type product_option_type = if (existing_prod_ot = product.product_option_types.find { |ot| ot.option_type_id == option_type.id }) existing_prod_ot else product_option_type = product.product_option_types.new product_option_type.option_type = option_type end product_option_type.position = opt_type_position if opt_type_position product_option_type.save! if product_option_type.new_record? || product_option_type.changed? else return if current_value.name.parameterize == opt_value.parameterize option_values.delete(current_value) end option_value = option_type.option_values.where(name: opt_value.parameterize).first_or_initialize do |o| o.name = o.label = opt_value o.save! end option_values << option_value save end |
#set_price(currency, amount, compare_at_amount = nil) ⇒ void
This method returns an undefined value.
Sets the base price (global price, not for a price list) for the given currency.
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 |
# File 'app/models/spree/variant.rb', line 826 def set_price(currency, amount, compare_at_amount = nil) # When the prices association is already loaded (eager-loaded for # serialization), reuse the cached base-price instance so readers that # branch on `prices.loaded?` (the Internal provider's resolution, # #price_in, serializers) # observe the write without a reload. `base_prices.find_or_initialize_by` # would issue a fresh query and return a detached object, leaving the # loaded collection — and the serialized response — stale. existing = if prices.loaded? prices.detect { |p| p.price_list_id.nil? && p.currency == currency } else prices.base_prices.find_by(currency: currency) end # A blank amount means the merchant left that currency empty, which is # the same statement as leaving it out of the payload: there is no base # price in this currency. Writing it would persist a nil amount, and a # base price (unlike a price-list placeholder) must have one. if amount.blank? return if existing.nil? prices.delete(existing) if prices.loaded? existing.destroy if existing.persisted? return end price = existing || if prices.loaded? prices.build(currency: currency) else prices.base_prices.build(currency: currency) end price.amount = amount price.compare_at_amount = compare_at_amount price.save! if persisted? end |
#set_stock(count_on_hand, backorderable = nil, stock_location = nil) ⇒ void
This method returns an undefined value.
Sets the count at a location. The correction goes through an adjusted
movement so it shows up in the stock history like every other change.
A count below zero is refused whatever the variant's backorder settings
say, so a caller passing one gets ActiveRecord::RecordInvalid.
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 |
# File 'app/models/spree/variant.rb', line 893 def set_stock(count_on_hand, backorderable = nil, stock_location = nil) stock_location ||= default_stock_location stock_level = if stock_levels.loaded? stock_levels.detect { |level| level.stock_location_id == stock_location.id } || stock_levels.build(stock_location: stock_location) else stock_levels.find_or_initialize_by(stock_location: stock_location) end # `unless nil?`, not `if present?` — a caller passing false means it. stock_level.backorderable = backorderable unless backorderable.nil? # Nothing is saved yet, so the count rides on the in-memory record and # the autosave association persists it with the variant. unless persisted? stock_level.count_on_hand = count_on_hand return end stock_level.save! if stock_level.changed? delta = count_on_hand.to_i - stock_level.count_on_hand.to_i return if delta.zero? # Through the level already in hand rather than StockLocation#adjust, # which would look the same row up again. stock_level.stock_movements.create!(quantity: delta, kind: 'adjusted', reason: Spree::StockMovement.default_adjustment_reason) end |
#should_track_inventory? ⇒ Boolean
Shortcut method to determine if inventory tracking is enabled for this variant This considers both the variant tracking flag and the store's setting
1010 1011 1012 |
# File 'app/models/spree/variant.rb', line 1010 def should_track_inventory? track_inventory? && store_preference(:track_inventory_levels) end |
#sold_by_carton? ⇒ Boolean
True when this variant is quoted in cartons rather than units. Requires
units_per_carton, which the validation above guarantees.
1114 1115 1116 |
# File 'app/models/spree/variant.rb', line 1114 def sold_by_carton? purchase_unit == 'carton' && units_per_carton.to_i.positive? end |
#stock_items ⇒ Object
Use #stock_levels; removed in 6.3.
778 779 780 781 |
# File 'app/models/spree/variant.rb', line 778 def stock_items Spree::Deprecation.warn('Spree::Variant#stock_items is deprecated and will be removed in Spree 6.3. Use #stock_levels instead.') stock_levels end |
#stock_items=(value) ⇒ Object
Use #stock_levels=; removed in 6.3.
784 785 786 787 |
# File 'app/models/spree/variant.rb', line 784 def stock_items=(value) Spree::Deprecation.warn('Spree::Variant#stock_items= is deprecated and will be removed in Spree 6.3. Use #stock_levels= instead.') self.stock_levels = value end |
#stock_items_attributes=(value) ⇒ Object
Use stock_levels_attributes=; removed in 6.3.
814 815 816 817 818 819 |
# File 'app/models/spree/variant.rb', line 814 def stock_items_attributes=(value) Spree::Deprecation.warn( 'Spree::Variant#stock_items_attributes= is deprecated and will be removed in Spree 6.3. Use #stock_levels_attributes= instead.' ) self.stock_levels_attributes = value end |
#stock_levels=(stock_levels_params) ⇒ void
This method returns an undefined value.
Syncs stock items from an array of hashes. Upserts stock for listed locations, soft-deletes stock items for unlisted locations. On new records, defers to after_create callback.
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 |
# File 'app/models/spree/variant.rb', line 756 def stock_levels=(stock_levels_params) return super if stock_levels_params.blank? || stock_levels_params.first.is_a?(Spree::StockLevel) return if defer_stock_levels(:stock_levels=, stock_levels_params) location_ids_in_payload = [] stock_levels_params.each do |stock_data| stock_data = stock_data.to_h.with_indifferent_access location = stock_location_for_param(stock_data[:stock_location_id]) # A stale or foreign location id is skipped rather than raising, which # is what #stock_levels_attributes= already does for the same payload. next if location.nil? location_ids_in_payload << location.id set_stock(stock_data[:count_on_hand], stock_data[:backorderable], location) end # Soft-delete stock levels for locations not in the payload stock_levels.where.not(stock_location_id: location_ids_in_payload).destroy_all if persisted? end |
#stock_levels_attributes=(rows) ⇒ void
This method returns an undefined value.
The v3 API sends stock_levels: [...], which the params normalizer
rewrites to nested attributes — and Rails would then write count_on_hand
straight onto the row. Each entry is routed through #set_stock instead,
so a count typed in the dashboard lands in the stock history like every
other change. Entries are upserted and never removed, which is what
accepts_nested_attributes_for did here.
798 799 800 801 802 803 804 805 806 807 808 809 810 811 |
# File 'app/models/spree/variant.rb', line 798 def stock_levels_attributes=(rows) rows = rows.values if rows.respond_to?(:values) && !rows.is_a?(Array) return if defer_stock_levels(:stock_levels_attributes=, rows) Array.wrap(rows).each do |row| row = (row.respond_to?(:to_unsafe_h) ? row.to_unsafe_h : row.to_h).with_indifferent_access next if row[:stock_location_id].blank? || row[:count_on_hand].blank? stock_location = stock_location_for_param(row[:stock_location_id]) next if stock_location.nil? set_stock(row[:count_on_hand], row[:backorderable], stock_location) end end |
#tax_category ⇒ Spree::TaxCategory
Returns tax category for Variant
414 415 416 417 418 419 420 421 422 423 424 |
# File 'app/models/spree/variant.rb', line 414 def tax_category @tax_category ||= if self[:tax_category_id].nil? product.tax_category else # The association, so a page of variants loads its # categories together; one deleted since it was # assigned no longer counts. own = super own.nil? || own.destroyed? || own.try(:deleted?) ? product.tax_category : own end end |
#tax_category_id ⇒ Integer
Returns tax category ID for Variant
428 429 430 431 432 433 434 |
# File 'app/models/spree/variant.rb', line 428 def tax_category_id @tax_category_id ||= if self[:tax_category_id].nil? product.tax_category_id else self[:tax_category_id] end end |
#thumbnail ⇒ Spree::Media?
The variant's own image, or its product's when it has none — the picture a list row shows for it.
93 94 95 |
# File 'app/models/spree/variant.rb', line 93 def thumbnail primary_media || product&.primary_media end |
#units_per_pallet ⇒ Integer?
How many units a full pallet of this variant holds. Nil unless both halves of the chain are recorded.
1142 1143 1144 1145 1146 |
# File 'app/models/spree/variant.rb', line 1142 def units_per_pallet return if units_per_carton.to_i.zero? || cartons_per_pallet.to_i.zero? units_per_carton * cartons_per_pallet end |
#update_thumbnail! ⇒ Object
Updates primary_media_id to the first media item by position. Called when media is added, removed, or reordered. Uses gallery_media so product-level assets linked via VariantMedia are considered alongside legacy variant-pinned images.
560 561 562 563 564 565 566 567 568 569 |
# File 'app/models/spree/variant.rb', line 560 def update_thumbnail! # Read through a fresh scope, never the cached association — this runs # from a media row's after_commit, and a loaded `images`/`associated_media` # would be missing the sibling rows created after it. candidates = gallery_media.reload.to_a # See Product#update_thumbnail! — a video without a still can't be a thumbnail. first_media = candidates.find(&:renderable_as_image?) update_column(:primary_media_id, first_media&.id) end |
#volume ⇒ BigDecimal
The cubic meters one unit of this variant occupies. Multiplying the raw dimension columns would answer in whatever unit the merchant typed, which is a sixteenfold error between inches and centimeters — so the name means CBM everywhere it appears (Variant, ContentItem, Package).
1031 1032 1033 |
# File 'app/models/spree/variant.rb', line 1031 def volume Spree::Measurement.cubic_meters(width, height, depth, unit: dimensions_unit) || 0 end |
#weight_unit ⇒ String
Returns the weight unit for the variant Falls back to the variant's own store, like #dimensions_unit below — on a multi-store install the default store's unit is someone else's, and converting a kilogram catalog as pounds misweighs every quote.
1044 1045 1046 |
# File 'app/models/spree/variant.rb', line 1044 def weight_unit attributes['weight_unit'] || (preference_store || Spree::Store.default)&.preferred_weight_unit end |
#with_digital_assets? ⇒ Boolean
1093 1094 1095 |
# File 'app/models/spree/variant.rb', line 1093 def with_digital_assets? digital_assets.any? end |