Class: Spree::Product

Inherits:
Object
  • Object
show all
Includes:
LegacyMultiStoreSupport, MemoizedData, Metadata, MetafieldFilterable, Metafields, Channels, Slugs, Webhooks, ProductScopes, SearchIndexable, Searchable, TranslatableResource, VendorConcern
Defined in:
app/models/spree/product.rb,
app/models/spree/product/slugs.rb,
app/models/spree/product/channels.rb,
app/models/spree/product/webhooks.rb

Defined Under Namespace

Modules: Channels, Slugs, Webhooks

Constant Summary collapse

MEMOIZED_METHODS =
%w[total_on_hand taxonomy_ids taxon_and_ancestors
default_variant_id tax_category default_variant variant_for_images
brand_taxon main_taxon
purchasable? in_stock? backorderable? digital?]
STATUSES =
%w[draft active archived].freeze
STATUS_TO_WEBHOOK_EVENT =
{
  'active' => 'activated',
  'draft' => 'drafted',
  'archived' => 'archived'
}.freeze
TRANSLATABLE_FIELDS =
%i[name description slug meta_description meta_title].freeze
RICH_TEXT_TRANSLATABLE_FIELDS =
%i[description].freeze

Constants included from Channels

Channels::DEPRECATED_DATE_TO_PUBLICATION_FIELD

Constants included from MetafieldFilterable

MetafieldFilterable::LIKE_PATTERNS, MetafieldFilterable::NUMERIC_OPERATORS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from SearchIndexable

#add_to_search_index, #enqueue_search_index, #enqueue_search_removal, #remove_from_search_index, #search_indexing_enabled?, #search_presentation, #store_ids_for_indexing

Methods included from Channels

#product_publications=, #publication_for

Methods included from Slugs

#ensure_slug_is_unique

Methods included from Webhooks

#send_product_activated_webhook, #send_product_archived_webhook, #send_product_drafted_webhook

Methods included from Metadata

#metadata, #metadata=, #public_metadata=

Methods included from TranslatableResource

#get_field_with_locale, #translatable_store, #upsert_translations

Instance Attribute Details

#option_values_hashObject

Returns the value of attribute option_values_hash.



203
204
205
# File 'app/models/spree/product.rb', line 203

def option_values_hash
  @option_values_hash
end

#prototype_idObject

Adding properties and option types on creation based on a chosen prototype



486
487
488
# File 'app/models/spree/product.rb', line 486

def prototype_id
  @prototype_id
end

Class Method Details

.bulk_auto_match_taxons(store, product_ids) ⇒ Object



334
335
336
337
338
339
340
341
342
343
344
# File 'app/models/spree/product.rb', line 334

def self.bulk_auto_match_taxons(store, product_ids)
  return if store.taxons.automatic.none?

  products_to_auto_match_ids = store.products.not_deleted.not_archived.where(id: product_ids).ids

  auto_match_taxons_jobs = products_to_auto_match_ids.map do |product_id|
    Spree::Products::AutoMatchTaxonsJob.new(product_id).tap { |job| job.scheduled_at = 30.seconds.from_now }
  end

  ActiveJob.perform_all_later(auto_match_taxons_jobs)
end

.like_any(fields, values) ⇒ Object



585
586
587
588
589
590
# File 'app/models/spree/product.rb', line 585

def self.like_any(fields, values)
  conditions = fields.product(values).map do |(field, value)|
    arel_table[field].matches("%#{value}%")
  end
  where conditions.inject(:or)
end

Instance Method Details

#any_variant_available?(currency) ⇒ Boolean

Returns:



506
507
508
509
510
511
512
# File 'app/models/spree/product.rb', line 506

def any_variant_available?(currency)
  if has_variants?
    first_available_variant(currency).present?
  else
    master.purchasable? && master.price_in(currency).amount.present?
  end
end

#any_variant_in_stock_or_backorderable?Boolean

Returns:



654
655
656
657
658
659
660
# File 'app/models/spree/product.rb', line 654

def any_variant_in_stock_or_backorderable?
  if has_variants?
    variants_including_master.in_stock_or_backorderable.exists?
  else
    master.in_stock_or_backorderable?
  end
end

#auto_match_taxonsObject



671
672
673
674
675
676
677
# File 'app/models/spree/product.rb', line 671

def auto_match_taxons
  return if deleted?
  return if archived?
  return if store.nil? || store.taxons.automatic.none?

  Spree::Products::AutoMatchTaxonsJob.set(wait: 30.seconds).perform_later(id)
end

#available?Boolean

determine if product is available. deleted products and products with status different than active are not available

Returns:



541
542
543
# File 'app/models/spree/product.rb', line 541

def available?
  active? && !deleted? && (available_on.nil? || available_on <= Time.current)
end

#backorderable?Boolean

Can't use short form block syntax due to https://github.com/Netflix/fast_jsonapi/issues/259

Returns:



357
358
359
# File 'app/models/spree/product.rb', line 357

def backorderable?
  default_variant.backorderable? || variants.any?(&:backorderable?)
end

#backordered?Boolean

determine if any variant (including master) is out of stock and backorderable

Returns:



581
582
583
# File 'app/models/spree/product.rb', line 581

def backordered?
  variants_including_master.any?(&:backordered?)
end

#brand_nameString

Returns the brand name for the product

Returns:

  • (String)


638
639
640
# File 'app/models/spree/product.rb', line 638

def brand_name
  brand_taxon&.name
end

#brand_taxonSpree::Taxon

Returns the brand taxon for the product

Returns:



622
623
624
625
626
627
628
629
630
631
632
633
634
# File 'app/models/spree/product.rb', line 622

def brand_taxon
  @brand_taxon ||= if classification_count.zero?
                     nil
                   elsif Spree.use_translations?
                     taxons.joins(:taxonomy).
                       join_translation_table(Taxonomy).
                       find_by(Taxonomy.translation_table_alias => { name: Spree.t(:taxonomy_brands_name) })
                   elsif taxons.loaded?
                     taxons.find { |taxon| taxon.taxonomy.name == Spree.t(:taxonomy_brands_name) }
                   else
                     taxons.joins(:taxonomy).find_by(Taxonomy.table_name => { name: Spree.t(:taxonomy_brands_name) })
                   end
end

#can_supply?Boolean

determine if any variant (including master) can be supplied

Returns:



576
577
578
# File 'app/models/spree/product.rb', line 576

def can_supply?
  variants_including_master.any?(&:can_supply?)
end

#category_ids=(ids) ⇒ Object

Maps 6.0 API name (category_ids) to model column (taxon_ids). Accepts both prefixed IDs and raw integer IDs. Only taxons belonging to the product's own store are assigned — ids from another store's taxonomies are dropped, preventing cross-store category attachment.



237
238
239
240
241
242
# File 'app/models/spree/product.rb', line 237

def category_ids=(ids)
  decoded_ids = Array(ids).filter_map do |id|
    id.to_s.include?('_') ? Spree::Taxon.decode_prefixed_id(id) : id
  end
  self.taxon_ids = Spree::Taxon.for_store(assignable_store).where(id: decoded_ids).ids
end

#default_imageObject

Deprecated.

Use #primary_media instead.



429
430
431
432
# File 'app/models/spree/product.rb', line 429

def default_image
  Spree::Deprecation.warn('Spree::Product#default_image is deprecated and will be removed in Spree 6.0. Please use Spree::Product#primary_media instead.')
  primary_media
end

#default_variantSpree::Variant

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

Returns:



386
387
388
389
390
391
392
# File 'app/models/spree/product.rb', line 386

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

#default_variant_idInteger

Returns default Variant ID for Product

Returns:

  • (Integer)


396
397
398
# File 'app/models/spree/product.rb', line 396

def default_variant_id
  @default_variant_id ||= default_variant.id
end

#digital?Boolean

Check if the product is digital by checking if any of its shipping methods are digital delivery This is used to determine if the product is digital and should have a digital delivery price instead of a physical shipping price

Returns:



667
668
669
# File 'app/models/spree/product.rb', line 667

def digital?
  @digital ||= shipping_category&.includes_digital_shipping_method?
end

#discontinue!Object



565
566
567
568
569
# File 'app/models/spree/product.rb', line 565

def discontinue!
  self.discontinue_on = Time.current
  self.status = 'archived'
  save(validate: false)
end

#discontinued?Boolean

Returns:



571
572
573
# File 'app/models/spree/product.rb', line 571

def discontinued?
  !!discontinue_on && discontinue_on <= Time.current
end

#duplicateObject

for adding products which are closely related to existing ones define "duplicate_extra" for site-specific actions, eg for additional fields



534
535
536
# File 'app/models/spree/product.rb', line 534

def duplicate
  Products::Duplicator.call(product: self)
end

#ensure_option_types_exist_for_values_hashObject

Ensures option_types and product_option_types exist for keys in option_values_hash



521
522
523
524
525
526
527
528
529
530
# File 'app/models/spree/product.rb', line 521

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
end
Deprecated.

Use #primary_media instead.



435
436
437
438
# File 'app/models/spree/product.rb', line 435

def featured_image
  Spree::Deprecation.warn('Spree::Product#featured_image is deprecated and will be removed in Spree 6.0. Please use Spree::Product#primary_media instead.')
  primary_media
end

#find_or_build_masterObject



365
366
367
# File 'app/models/spree/product.rb', line 365

def find_or_build_master
  master || build_master
end

#find_variant_with_imagesSpree::Variant?

Finds first variant with media using preloaded data when available.

Returns:



467
468
469
470
471
# File 'app/models/spree/product.rb', line 467

def find_variant_with_images
  return variants.find(&:has_media?) if variants.loaded?

  variants.joins(:images).first
end

#first_available_variant(currency) ⇒ Object



498
499
500
# File 'app/models/spree/product.rb', line 498

def first_available_variant(currency)
  variants.find { |v| v.purchasable? && v.price_in(currency).amount.present? }
end

#first_or_default_variant(currency) ⇒ Object



488
489
490
491
492
493
494
495
496
# File 'app/models/spree/product.rb', line 488

def first_or_default_variant(currency)
  if !has_variants?
    default_variant
  elsif first_available_variant(currency).present?
    first_available_variant(currency)
  else
    variants.first
  end
end

Returns the product's media gallery. Uses product-level media if present, otherwise falls back to variant images.

Returns:

  • (ActiveRecord::Relation)


403
404
405
406
407
# File 'app/models/spree/product.rb', line 403

def gallery_media
  return media if association(:media).loaded? ? media.any? : media.exists?

  variant_images
end

#has_media?Boolean Also known as: has_images?, has_variant_images?

Returns true if the product has any media (product-level or variant-level). Uses counter cache for performance.

Returns:



412
413
414
415
416
# File 'app/models/spree/product.rb', line 412

def has_media?
  return variant_images.any? if association(:variant_images).loaded?

  media_count.positive?
end

#has_variants?Boolean

Checks if product has variants (non-master variants) Uses variant_count counter cache for performance

Returns:



372
373
374
375
376
# File 'app/models/spree/product.rb', line 372

def has_variants?
  return variants.size.positive? if variants.loaded?

  variant_count.positive?
end

#image_countObject

Deprecated.

Use media_count instead



453
454
455
# File 'app/models/spree/product.rb', line 453

def image_count
  media_count
end

#in_stock?Boolean

Can't use short form block syntax due to https://github.com/Netflix/fast_jsonapi/issues/259

Returns:



352
353
354
# File 'app/models/spree/product.rb', line 352

def in_stock?
  @in_stock ||= default_variant.in_stock? || variants.any?(&:in_stock?)
end

#lowest_price(currency) ⇒ Object

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



516
517
518
# File 'app/models/spree/product.rb', line 516

def lowest_price(currency)
  prices_including_master.find_all { |p| p.currency == currency }.min_by(&:amount)
end

#main_taxonObject



642
643
644
645
646
# File 'app/models/spree/product.rb', line 642

def main_taxon
  return if classification_count.zero?

  @main_taxon ||= taxons.first
end

#masterObject

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.



616
617
618
# File 'app/models/spree/product.rb', line 616

def master
  super || variants_including_master.with_deleted.find_by(is_master: true)
end

#media=(media_params) ⇒ void

This method returns an undefined value.

Sync media inline. Entries with id patch the existing asset (alt/position/variant_ids); entries with signed_id create + attach a fresh upload; missing items are left alone (delete still goes through the dedicated DELETE /media endpoint to avoid accidental data loss when a form ships stale state).

Deferred: ActiveStorage attaches require a persisted record, so on new records we stash the params and replay them in after_create.

Parameters:

  • media_params (Array<Hash>)


254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'app/models/spree/product.rb', line 254

def media=(media_params)
  # Blank input is a no-op — never call `super` with an empty array,
  # because the ActiveRecord collection setter would replace media with
  # `[]` and trigger `dependent: :destroy` on every persisted asset.
  # Explicit deletes go through the dedicated DELETE /media endpoint.
  return if media_params.blank?
  return super if media_params.first.is_a?(Spree::Asset)

  if new_record?
    @pending_media_params = media_params
    return
  end

  apply_media(media_params)
end

#on_sale?(currency) ⇒ Boolean

Returns:



361
362
363
# File 'app/models/spree/product.rb', line 361

def on_sale?(currency)
  prices_including_master.find_all { |p| p.currency == currency }.any?(&:discounted?)
end

#preorder?Boolean

True when the product is currently offered as a pre-order: at least one variant is sold before it is in stock (see Variant#preorder?). Independent of publishing — a pre-order product is live in the catalog, just flagged "buy now, ships later".

Returns:



550
551
552
# File 'app/models/spree/product.rb', line 550

def preorder?
  default_variant.preorder? || variants.any?(&:preorder?)
end

#preorder_ships_atActiveSupport::TimeWithZone?

The latest "ships by" date across the product's pre-order variants, so a storefront can show a single "ships by" promise for the product. Nil when the product is not a pre-order. Scans the same sellable set #preorder? consults (the master only counts when it is the sole, purchasable variant), reading preloaded associations to avoid an N+1.

Returns:

  • (ActiveSupport::TimeWithZone, nil)


560
561
562
563
# File 'app/models/spree/product.rb', line 560

def preorder_ships_at
  candidates = has_variants? ? variants : [master]
  candidates.select(&:preorder?).filter_map(&:preorder_ships_at).max
end

#price_varies?(currency) ⇒ Boolean

Returns:



502
503
504
# File 'app/models/spree/product.rb', line 502

def price_varies?(currency)
  prices_including_master.find_all { |p| p.currency == currency && p.amount.present? }.map(&:amount).uniq.count > 1
end

#prices=(prices_params) ⇒ Object

Sets prices on the master variant. Accepts array of { currency:, amount:, compare_at_amount: } hashes.



229
230
231
# File 'app/models/spree/product.rb', line 229

def prices=(prices_params)
  find_or_build_master.prices = prices_params
end

#primary_imageObject

Deprecated.

Use #primary_media instead.



441
442
443
444
# File 'app/models/spree/product.rb', line 441

def primary_image
  Spree::Deprecation.warn('Spree::Product#primary_image is deprecated and will be removed in Spree 6.0. Please use Spree::Product#primary_media instead.')
  primary_media
end

#purchasable?Boolean

Can't use short form block syntax due to https://github.com/Netflix/fast_jsonapi/issues/259

Returns:



347
348
349
# File 'app/models/spree/product.rb', line 347

def purchasable?
  @purchasable ||= default_variant.purchasable? || variants.any?(&:purchasable?)
end

#secondary_imageSpree::Asset?

Returns secondary media for Product (for hover effects).

Returns:



448
449
450
# File 'app/models/spree/product.rb', line 448

def secondary_image
  variant_for_images&.secondary_image
end

#storefront_descriptionString

Returns the short description for the product

Returns:

  • (String)


475
476
477
# File 'app/models/spree/product.rb', line 475

def storefront_description
  description
end

#tags=(tags) ⇒ Object

Maps tags array to tag_list for API convenience.

Parameters:

  • tags (Array<String>)


223
224
225
# File 'app/models/spree/product.rb', line 223

def tags=(tags)
  self.tag_list = tags
end

#tax_categorySpree::TaxCategory?

Returns tax category for Product

Returns:



481
482
483
# File 'app/models/spree/product.rb', line 481

def tax_category
  @tax_category ||= super || TaxCategory.default
end

#taxons_for_store(store) ⇒ Object



648
649
650
651
652
# File 'app/models/spree/product.rb', line 648

def taxons_for_store(store)
  return if classification_count.zero?

  taxons.loaded? ? taxons.find_all { |taxon| taxon.taxonomy.store_id == store.id } : taxons.for_store(store)
end

#to_csv(store = nil) ⇒ Object



679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
# File 'app/models/spree/product.rb', line 679

def to_csv(store = nil)
  store ||= self.store
  properties_for_csv = if respond_to?(:product_properties) && Spree::Config.respond_to?(:product_properties_enabled) && Spree::Config[:product_properties_enabled]
                         Spree::Property.order(:position).flat_map do |property|
                           [
                             property.name,
                             product_properties.find { |pp| pp.property_id == property.id }&.value
                           ]
                         end
                       else
                         []
                       end
  metafields_for_csv ||= Spree::MetafieldDefinition.for_resource_type('Spree::Product').order(:namespace, :key).map do |mf_def|
    metafields.find { |mf| mf.metafield_definition_id == mf_def.id }&.csv_value
  end
  taxons_for_csv ||= taxons.manual.reorder(depth: :desc).first(3).pluck(:pretty_name)
  taxons_for_csv.fill(nil, taxons_for_csv.size...3)

  csv_lines = []
  all_variants = has_variants? ? variants_including_master.to_a : [master]
  default_currency = store.default_currency
  additional_currencies = store.supported_currencies_list.map(&:iso_code) - [default_currency]

  # Primary rows in the store's default currency
  all_variants.each_with_index do |variant, index|
    csv_lines << Spree::CSV::ProductVariantPresenter.new(self, variant, index, properties_for_csv, taxons_for_csv, store,
                                                         metafields_for_csv).call
  end

  # Price-only rows for each additional currency
  additional_currencies.each do |currency|
    all_variants.each do |variant|
      next unless variant.amount_in(currency)

      csv_lines << Spree::CSV::ProductVariantPresenter.new(self, variant, 0, [], [], store,
                                                           [], currency).call
    end
  end

  csv_lines
end

#to_translation_csv(store = nil, locales = []) ⇒ Object



721
722
723
724
725
726
727
728
729
730
# File 'app/models/spree/product.rb', line 721

def to_translation_csv(store = nil, locales = [])
  locales.filter_map do |locale|
    # Only export if at least one field has a translation for this locale
    has_translation = Spree::CSV::ProductTranslationPresenter::TRANSLATABLE_FIELDS.any? do |field|
      get_field_with_locale(locale, field).present?
    end

    Spree::CSV::ProductTranslationPresenter.new(self, locale).call if has_translation
  end
end

#total_on_handObject



601
602
603
604
605
606
607
608
609
610
611
# File 'app/models/spree/product.rb', line 601

def total_on_hand
  @total_on_hand ||= if any_variants_not_track_inventory?
                       BigDecimal::INFINITY
                     else
                       if variants_including_master.loaded?
                         variants_including_master.sum(&:total_on_hand)
                       else
                         stock_items.loaded? ? stock_items.sum(&:count_on_hand) : stock_items.sum(:count_on_hand)
                       end
                     end
end

#update_thumbnail!Object

Updates primary_media_id to the first media item. Checks product-level media first, then falls back to variant images. Called when media is added, removed, or reordered.



460
461
462
463
# File 'app/models/spree/product.rb', line 460

def update_thumbnail!
  first_media = media.order(:position).first || variant_images.order(:position).first
  update_column(:primary_media_id, first_media&.id)
end

#variant_for_imagesSpree::Variant?

Returns the variant that should be used for displaying images. Priority: master > default_variant > first variant with images

Returns:



424
425
426
# File 'app/models/spree/product.rb', line 424

def variant_for_images
  @variant_for_images ||= find_variant_for_images
end

#variants=(variants_params) ⇒ void

This method returns an undefined value.

Syncs variants from an array of hashes. Creates new variants, updates existing ones (matched by :id), and removes unlisted ones. Must be called on a persisted product (use after_save or call explicitly after create).

Parameters:

  • variants_params (Array<Hash>)

    array of variant attribute hashes



275
276
277
278
279
280
281
282
283
284
285
# File 'app/models/spree/product.rb', line 275

def variants=(variants_params)
  return super if variants_params.blank? || variants_params.first.is_a?(Spree::Variant)

  # Store for deferred processing if product is not yet persisted
  if new_record?
    @pending_variants_params = variants_params
    return
  end

  apply_variants(variants_params)
end

#variants_and_option_values(current_currency = nil) ⇒ Object

Suitable for displaying only variants that has at least one option value. There may be scenarios where an option type is removed and along with it all option values. At that point all variants associated with only those values should not be displayed to frontend users. Otherwise it breaks the idea of having variants



597
598
599
# File 'app/models/spree/product.rb', line 597

def variants_and_option_values(current_currency = nil)
  variants.active(current_currency).joins(:option_value_variants)
end