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
39
40
41
42
43
44
45
46
47
48
|
# File 'app/services/spree/taxons/regenerate_products.rb', line 6
def call(taxon:)
return if taxon.nil?
return if taxon.destroyed?
return if taxon.manual?
previous_products_ids = taxon.classifications.order(position: :asc).pluck(:product_id)
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)
products = Spree::Product.where(id: (previous_products_ids + product_ids_to_insert).uniq)
products.touch_all
products.each(&:enqueue_search_index)
end
Spree::Taxon.reset_counters(taxon.id, :classifications)
all_product_ids = (previous_products_ids + product_ids_to_insert).uniq
existing_product_ids = Spree::Product.where(id: all_product_ids).pluck(:id)
existing_product_ids.each { |id| Spree::Product.reset_counters(id, :classifications) }
success(taxon)
end
|