Class: Spree::Products::AutoMatchTaxons

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

Instance Method Summary collapse

Methods included from ServiceModule::Base

prepended

Instance Method Details

#call(product:) ⇒ 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
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 = []

  # we need to check if existing taxons still match
  product.taxons.automatic.includes(:taxon_rules).each do |taxon|
    # products shouldn't be part of the taxon anymore
    # eg. product tags or category was changed
    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?

  # we need to check if product matches any existing taxons
  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