Class: Item::PrepareNewKitComponent

Inherits:
BaseService show all
Defined in:
app/services/item/prepare_new_kit_component.rb

Overview

Prepare a new component to be added to the same catalogs as the original kit item

Defined Under Namespace

Classes: Result

Instance Method Summary collapse

Methods inherited from BaseService

#initialize, #log_debug, #log_error, #log_info, #log_warning, #logger, #options, #tagged_logger

Constructor Details

This class inherits a constructor from BaseService

Instance Method Details

#process(kit_item_id:, component_item_id:) ⇒ Object



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
# File 'app/services/item/prepare_new_kit_component.rb', line 8

def process(kit_item_id:, component_item_id:)
  kit_item = Item.kits.find(kit_item_id)
  # Load up the component item
  component = Item.find(component_item_id)

  # in what catalogs does this kit exist?
  catalogs = kit_item.catalog_items.includes(:catalog).map(&:catalog).uniq

  catalog_items_created = []
  errors = []
  notices = []
  catalogs.each do |catalog|
    # find store item in catalog
    store_item = component.store_items.where(location: 'AVAILABLE', store_id: catalog.store_id).first
    if catalog.catalog_items.where(store_item_id: store_item.id).exists?
      notices << "Component item #{component.sku} already exists in catalog #{catalog.id} : #{catalog.name}"
    else
      # create catalog item for this store item
      ci = CatalogItem.create(store_item: store_item,
                              catalog: catalog,
                              state: 'active_hidden',
                              amount: 0)
      if ci.persisted?
        # Do a price sync
        CatalogItem::PriceSync.new(CatalogItem.where(id: ci.id)).sync_all_catalog_items
        catalog_items_created << ci
        notices << "Component item #{component.sku} created in catalog #{catalog.id} : #{catalog.name}"
      else
        errors << "Error creating component item in catalog #{catalog.id} : #{catalog.name} : #{ci.errors_to_s}"
      end
    end
  end

  Result.new(errors: errors, notices: notices, catalog_items_created: catalog_items_created)
end