Class: Spree::Taxons::RemoveProducts

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

Instance Method Summary collapse

Methods included from ServiceModule::Base

prepended

Instance Method Details

#call(taxons:, products:) ⇒ Spree::ServiceModule::Base::Result

Removes the given products from the given taxons.

Parameters:

Returns:

  • (Spree::ServiceModule::Base::Result)


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
50
51
52
53
# File 'app/services/spree/taxons/remove_products.rb', line 11

def call(taxons:, products:)
  return if taxons.blank? || products.blank?

  ApplicationRecord.transaction do
    taxons.pluck(:id).each do |taxon_id|
      Spree::Classification.where(taxon_id: taxon_id, product_id: products.pluck(:id)).delete_all
    end

    classifications_params = taxons.pluck(:id).flat_map do |taxon_id|
      position = 0
      existing_product_ids = Spree::Classification.where(taxon_id: taxon_id).pluck(:product_id)

      existing_product_ids.map do |product_id|
        {
          taxon_id: taxon_id,
          product_id: product_id,
          position: (position += 1),
          created_at: Time.current,
          updated_at: Time.current
        }
      end
    end

    if classifications_params.any?
      opts = {}
      opts[:unique_by] = :index_spree_products_taxons_on_product_id_and_taxon_id unless ActiveRecord::Base.connection.adapter_name == 'Mysql2'

      Spree::Classification.upsert_all(
        classifications_params,
        **opts
      )
    end
  end

  # clear cache
  Spree::Product.where(id: products.pluck(:id)).touch_all

  taxon_ids = taxons.pluck(:id)
  Spree::Taxon.where(id: taxon_ids).touch_all
  Spree::Taxons::TouchFeaturedSections.call(taxon_ids: taxon_ids)

  success(true)
end