Class: Spree::AgentTools::SetStock

Inherits:
Spree::AgentTool show all
Defined in:
app/tools/spree/agent_tools/set_stock.rb

Overview

Sets how many of something is on a shelf, through the Admin API's own bulk endpoint.

Named for what a merchant says — "forty in stock", "two fewer, damaged" — rather than for the operation. Either an absolute figure or a signed change, per variant and location, as many at once as the merchant has counted.

Constant Summary

Constants inherited from Spree::AgentTool

Spree::AgentTool::PARENT_ID_DESCRIPTION

Instance Attribute Summary

Attributes inherited from Spree::AgentTool

#context

Instance Method Summary collapse

Methods inherited from Spree::AgentTool

additive!, audience, description, destructive?, #initialize, input_schema, mutating!, mutating?, param, params, permission, #permitted?, tool_name, #unknown_resource

Constructor Details

This class inherits a constructor from Spree::AgentTool

Instance Method Details

#call(rows:) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/tools/spree/agent_tools/set_stock.rb', line 24

def call(rows:)
  prepared = Array(rows).map { |row| row.respond_to?(:to_h) ? row.to_h.stringify_keys : {} }
  return { error: 'Give at least one row.' } if prepared.empty?

  response = ApiDispatch.new(context).call(
    method: :post, path: '/api/v3/admin/stock_levels/bulk_upsert', body: { stock_levels: prepared }
  )

  unless response.success?
    # The endpoint names the missing field per row, which is what lets a
    # model repair its own request rather than resend it whole.
    rows = response.body.is_a?(Hash) ? response.body.dig('error', 'details', 'rows') : nil

    return { error: response.error_message, rows: rows }.compact
  end

  changed = response.body.is_a?(Hash) ? response.body['stock_level_count'] : nil

  { ok: true, shelves_changed: changed || prepared.size }
end

#summary(arguments) ⇒ Object



45
46
47
48
49
# File 'app/tools/spree/agent_tools/set_stock.rb', line 45

def summary(arguments)
  count = Array(arguments[:rows]).size

  "Set stock on #{count} #{'shelf'.pluralize(count)}"
end