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
49
|
# File 'app/services/spree/products/auto_match_taxons.rb', line 6
def call(product:)
return unless product.present?
taxons_to_remove = []
taxons_to_add = []
product.taxons.automatic.includes(:taxon_rules).each do |taxon|
taxons_to_remove << taxon unless taxon.products_matching_rules.ids.include?(product.id)
end
Spree::Classification.where(taxon: taxons_to_remove, product: product).delete_all if taxons_to_remove.any?
Spree::Taxon.automatic.includes(:taxon_rules, :products).each do |taxon|
taxons_to_add << taxon if taxon.products.exclude?(product) && taxon.products_matching_rules.ids.include?(product.id)
end
if taxons_to_add.any?
products_counts = Spree::Taxon.where(id: taxons_to_add.pluck(:id)).
joins(:classifications).
reorder('').
group(:taxon_id).
count(:product_id)
Spree::Classification.insert_all(
taxons_to_add.map do |taxon|
position = products_counts[taxon.id].to_i + 1
classification_attributes(taxon, product, position)
end
)
end
all_affected_taxons = (taxons_to_remove + taxons_to_add).uniq
if all_affected_taxons.any?
Spree::Taxons::TouchFeaturedSections.call(taxon_ids: all_affected_taxons.pluck(:id))
product.touch
end
success(product)
end
|