Class: Spree::Taxons::RegenerateProducts

Inherits:
Object
  • Object
show all
Includes:
ServiceModule::Base
Defined in:
app/services/spree/taxons/regenerate_products.rb

Instance Method Summary collapse

Methods included from ServiceModule::Base

prepended

Instance Method Details

#call(taxon:) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'app/services/spree/taxons/regenerate_products.rb', line 6

def call(taxon:)
  return if taxon.nil?
  return if taxon.manual?

  previous_products_ids = taxon.classifications.order(position: :asc).pluck(:product_id)

  # https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-delete_all
  # we don't want to run destroy_all here to avoid callbacks
  # default dependent value is nullify and that won't work for us
  taxon.classifications.delete_all(:delete_all)

  products_matching_rules = taxon.products_matching_rules
  product_ids_to_insert = products_matching_rules.ids

  previous_filtered_products_ids = previous_products_ids & product_ids_to_insert
  max_products_position = previous_filtered_products_ids.size || 0

  if product_ids_to_insert.any?
    records_to_insert = product_ids_to_insert.map do |product_id|
      position = previous_filtered_products_ids.index(product_id)
      position = position.present? ? position + 1 : max_products_position += 1

      classification_attributes(product_id, taxon, position)
    end

    Spree::Classification.insert_all(records_to_insert)

    # expire product cache
    Spree::Product.where(id: (previous_products_ids + product_ids_to_insert).uniq).touch_all
  end

  success(taxon)
end