Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Let a warehouse push its stock levels in

Damian Legawiecd71dcdbf8874
diff --git a/packages/admin-sdk/examples/stock-levels/bulk-upsert.ts b/packages/admin-sdk/examples/stock-levels/bulk-upsert.ts
new file mode 100644
index 0000000000..3e10b46c95
--- /dev/null
+++ b/packages/admin-sdk/examples/stock-levels/bulk-upsert.ts
@@ -0,0 +1,27 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const { stock_level_count } = await client.stockLevels.bulkUpsert({
+ stock_levels: [
+ {
+ variant_id: 'variant_xxx',
+ stock_location_id: 'sloc_xxx',
+ count_on_hand: 42,
+ },
+ // Rows may instead name records by the key the feeding system holds.
+ {
+ variant: { external_id: { erp: 'MAT-100' } },
+ stock_location: { external_id: { erp: 'WH-1' } },
+ count_on_hand: 7,
+ },
+ ],
+})
+
+// endregion:example
+
+export { stock_level_count }
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
index 9655d03642..b08e654c4b 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
@@ -8,6 +8,33 @@ module Spree
class StockLevelsController < ResourceController
scoped_resource :stock
+ before_action :require_stock_levels!, only: [:bulk_upsert]
+
+ def bulk_upsert
+ authorize! :update, Spree::StockLevel
+
+ rows = Array(params[:stock_levels]).map { |row| decode_stock_row(row) }
+
+ invalid = rows.each_with_index.filter_map do |row, index|
+ missing = %i[variant_id stock_location_id].reject { |key| row[key].present? }
+ missing << :count_on_hand if row[:count_on_hand].blank? && row[:adjustment].blank?
+ { index: index, missing: missing } if missing.any?
+ end
+
+ if invalid.any?
+ return render_error(
+ code: 'invalid_stock_levels',
+ message: 'Each row must name a variant and stock location in this store, ' \
+ 'and either a count_on_hand or an adjustment.',
+ status: :unprocessable_content,
+ details: { rows: invalid }
+ )
+ end
+
+ result = Spree::StockLevels::BulkUpsert.call(rows: rows)
+ render json: result.value
+ end
+
# PATCH /api/v3/admin/stock_levels/:id
#
# A count edit is a correction, so it is written as an `adjusted`
@@ -95,6 +122,56 @@ module Spree
def permitted_params
params.permit(*model_additional_permitted_attributes, :count_on_hand, :backorderable, :reason, metadata: {})
end
+
+ private
+
+ def bulk_record_count_key
+ :stock_level_count
+ end
+
+ def require_stock_levels!
+ return if params.key?(:stock_levels)
+
+ render_error(
+ code: 'missing_stock_levels',
+ message: 'stock_levels is required (send an empty array to no-op).',
+ status: :unprocessable_content
+ )
+ end
+
+ # Every id is resolved through the current store's own scopes, so a
+ # variant or location belonging to another store is simply not found
+ # rather than quietly written to.
+ def decode_stock_row(row)
+ row = row.respond_to?(:to_unsafe_h) ? row.to_unsafe_h : row.to_h
+ row = row.with_indifferent_access
+
+ {
+ variant_id: resolve_id(store_variants, row[:variant_id], row[:variant]),
+ stock_location_id: resolve_id(store_stock_locations, row[:stock_location_id], row[:stock_location]),
+ count_on_hand: row[:count_on_hand],
+ adjustment: row[:adjustment],
+ backorderable: row[:backorderable]
+ }.compact
+ end
+
+ def resolve_id(scope, prefixed_id, reference)
+ return scope.find_by_prefix_id(prefixed_id)&.id if prefixed_id.present?
+
+ external = reference.is_a?(Hash) ? reference[:external_id] : nil
+ return if external.blank?
+
+ system, external_id = external.to_h.first
+ scope.find_by_external_id(system, external_id)&.id
+ end
+
+ def store_variants
+ current_store.variants.accessible_by(current_ability, :update)
+ end
+
+ def store_stock_locations
+ current_store.stock_locations.accessible_by(current_ability, :update)
+ end
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_levels_bulk_upsert_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_levels_bulk_upsert_spec.rb
new file mode 100644
index 0000000000..e3c79e1365
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_levels_bulk_upsert_spec.rb
@@ -0,0 +1,134 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::StockLevelsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:stock_location) { create(:stock_location, store: store) }
+ let!(:variant) { create(:variant) }
+
+ before do
+ request.headers.merge!(headers)
+ variant.stock_levels.destroy_all
+ create(:stock_level, variant: variant, stock_location: stock_location,
+ count_on_hand: 5, adjust_count_on_hand: false)
+ variant.stock_levels.reload
+ end
+
+ def stock_level
+ variant.stock_levels.find_by(stock_location: stock_location)
+ end
+
+ describe 'POST #bulk_upsert' do
+ it 'sets the level a feed reports' do
+ post :bulk_upsert, params: {
+ stock_levels: [{ variant_id: variant.prefixed_id, stock_location_id: stock_location.prefixed_id,
+ count_on_hand: 12 }]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['stock_level_count']).to eq(1)
+ expect(stock_level.count_on_hand).to eq(12)
+ end
+
+ # A merchant has to be able to see why a number moved, so a feed writes
+ # history rather than overwriting the figure.
+ it 'records the change as a movement rather than a silent overwrite' do
+ expect do
+ post :bulk_upsert, params: {
+ stock_levels: [{ variant_id: variant.prefixed_id, stock_location_id: stock_location.prefixed_id,
+ count_on_hand: 12 }]
+ }, as: :json
+ end.to change(Spree::StockMovement, :count).by(1)
+
+ expect(Spree::StockMovement.last.quantity).to eq(7)
+ end
+
+ it 'accepts a relative adjustment as well as an absolute level' do
+ post :bulk_upsert, params: {
+ stock_levels: [{ variant_id: variant.prefixed_id, stock_location_id: stock_location.prefixed_id,
+ adjustment: -2 }]
+ }, as: :json
+
+ expect(stock_level.count_on_hand).to eq(3)
+ end
+
+ it 'addresses records by the keys the external system holds' do
+ variant.set_external_id('erp', 'MAT-100')
+ stock_location.set_external_id('erp', 'WH-1')
+
+ post :bulk_upsert, params: {
+ stock_levels: [{ variant: { external_id: { erp: 'MAT-100' } },
+ stock_location: { external_id: { erp: 'WH-1' } },
+ count_on_hand: 9 }]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(stock_level.count_on_hand).to eq(9)
+ end
+
+ it 'writes many pairs in one call' do
+ second = create(:variant)
+ second.stock_levels.destroy_all
+ create(:stock_level, variant: second, stock_location: stock_location, count_on_hand: 0,
+ adjust_count_on_hand: false)
+
+ post :bulk_upsert, params: {
+ stock_levels: [
+ { variant_id: variant.prefixed_id, stock_location_id: stock_location.prefixed_id, count_on_hand: 1 },
+ { variant_id: second.prefixed_id, stock_location_id: stock_location.prefixed_id, count_on_hand: 2 }
+ ]
+ }, as: :json
+
+ expect(json_response['stock_level_count']).to eq(2)
+ expect(stock_level.count_on_hand).to eq(1)
+ expect(second.stock_levels.find_by(stock_location: stock_location).count_on_hand).to eq(2)
+ end
+
+ it 'sets the backorder flag when the feed states it' do
+ post :bulk_upsert, params: {
+ stock_levels: [{ variant_id: variant.prefixed_id, stock_location_id: stock_location.prefixed_id,
+ count_on_hand: 5, backorderable: false }]
+ }, as: :json
+
+ expect(stock_level.backorderable).to be(false)
+ end
+
+ it 'rejects a row that names neither a level nor an adjustment' do
+ post :bulk_upsert, params: {
+ stock_levels: [{ variant_id: variant.prefixed_id, stock_location_id: stock_location.prefixed_id }]
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['details']['rows'].first['missing']).to include('count_on_hand')
+ end
+
+ it 'refuses to write another store stock' do
+ other_store = create(:store)
+ other_location = create(:stock_location, store: other_store)
+
+ post :bulk_upsert, params: {
+ stock_levels: [{ variant_id: variant.prefixed_id, stock_location_id: other_location.prefixed_id,
+ count_on_hand: 99 }]
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(stock_level.count_on_hand).to eq(5)
+ end
+
+ it 'asks for the parameter rather than silently doing nothing' do
+ post :bulk_upsert, params: {}, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('missing_stock_levels')
+ end
+
+ it 'accepts an empty batch as a no-op' do
+ post :bulk_upsert, params: { stock_levels: [] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['stock_level_count']).to eq(0)
+ end
+ end
+end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/stock_levels_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/stock_levels_spec.rb
new file mode 100644
index 0000000000..bf834f798f
--- /dev/null
+++ b/spree/api/spec/integration/spree/api/v3/admin/stock_levels_spec.rb
@@ -0,0 +1,99 @@
+# frozen_string_literal: true
+
+require 'swagger_helper'
+
+RSpec.describe 'Admin Stock Levels API', type: :request, swagger_doc: 'api-reference/admin.yaml' do
+ include_context 'API v3 Admin'
+
+ let(:Authorization) { "Bearer #{admin_jwt_token}" }
+ let(:product) { create(:product, store: store) }
+ let!(:variant) { create(:variant, product: product) }
+ let!(:stock_location) { create(:stock_location, store: store) }
+
+ path '/api/v3/admin/stock_levels/bulk_upsert' do
+ post 'Bulk-upsert stock levels' do
+ tags 'Stock'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Sets stock levels for many (variant, location) pairs at once — what a
+ warehouse or ERP feed posts on a schedule.
+
+ Each row names its variant and stock location either by Spree id
+ (`variant_id`, `stock_location_id`) or by the key the feeding system
+ holds (`"variant": { "external_id": { "erp": "MAT-100" } }`), so a
+ feed can address records without first looking up Spree's own ids.
+
+ A row carries either `count_on_hand` — the absolute level the external
+ system reports — or `adjustment`, a relative change for feeds that
+ report movements instead. Every change is written as a stock movement,
+ so a merchant can still see why a figure moved.
+
+ The response carries `stock_item_count`: how many pairs were processed.
+ DESC
+ admin_scope :write, :stock
+
+ admin_sdk_example 'stock-levels/bulk-upsert'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ required: %w[stock_levels],
+ properties: {
+ stock_levels: {
+ type: :array,
+ items: {
+ type: :object,
+ properties: {
+ variant_id: { type: :string, nullable: true, example: 'variant_xY9' },
+ variant: {
+ type: :object, nullable: true,
+ description: 'Addresses the variant by an external key instead of its Spree id.',
+ properties: { external_id: { type: :object, additionalProperties: { type: :string } } }
+ },
+ stock_location_id: { type: :string, nullable: true, example: 'sloc_aBc' },
+ stock_location: {
+ type: :object, nullable: true,
+ properties: { external_id: { type: :object, additionalProperties: { type: :string } } }
+ },
+ count_on_hand: { type: :integer, nullable: true, example: 42 },
+ adjustment: { type: :integer, nullable: true, example: -3 },
+ backorderable: { type: :boolean, nullable: true }
+ }
+ }
+ }
+ }
+ }
+
+ response '200', 'stock levels updated' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:body) do
+ {
+ stock_levels: [
+ {
+ variant_id: variant.prefixed_id,
+ stock_location_id: stock_location.prefixed_id,
+ count_on_hand: 42
+ }
+ ]
+ }
+ end
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['stock_level_count']).to eq(1)
+ end
+ end
+
+ response '422', 'row is missing a level' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:body) do
+ { stock_levels: [{ variant_id: variant.prefixed_id, stock_location_id: stock_location.prefixed_id }] }
+ end
+
+ run_test!
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/stock_levels/bulk_upsert.rb b/spree/core/app/services/spree/stock_levels/bulk_upsert.rb
new file mode 100644
index 0000000000..0fdd2c98f9
--- /dev/null
+++ b/spree/core/app/services/spree/stock_levels/bulk_upsert.rb
@@ -0,0 +1,100 @@
+module Spree
+ module StockLevels
+ # Sets stock levels for many (variant, location) pairs in one call — what a
+ # warehouse feed posts on a schedule.
+ #
+ # Deliberately not an +upsert_all+. Stock changes are recorded as movements
+ # so a merchant can see why a figure changed, and writing +count_on_hand+
+ # straight would leave that history with a hole in it. The cost is a row
+ # per change rather than one statement; the alternative is stock that
+ # cannot be explained.
+ #
+ # A feed states absolute levels (+count_on_hand+), which is what an
+ # external system knows. The movement records the delta between what Spree
+ # held and what the feed says.
+ class BulkUpsert
+ prepend Spree::ServiceModule::Base
+
+ # What the stock history shows against a movement this service wrote.
+ FEED_REASON = 'Inventory feed'.freeze
+
+ # @param rows [Array<Hash>] each with +variant_id+, +stock_location_id+,
+ # and either +count_on_hand+ (absolute) or +adjustment+ (relative);
+ # +backorderable+ optional
+ # @return [Spree::ServiceModule::Result] +{ stock_level_count: N }+
+ def call(rows:)
+ rows = Array(rows).map { |row| row.with_indifferent_access }
+ keyed = rows.select { |row| row[:variant_id].present? && row[:stock_location_id].present? }
+ return success(stock_level_count: 0) if keyed.empty?
+
+ # Last write wins per pair: a feed that mentions the same shelf twice
+ # means the later line, not the sum of both.
+ deduped = keyed.reverse.uniq { |row| [row[:variant_id].to_s, row[:stock_location_id].to_s] }.reverse
+
+ count = 0
+ Spree::StockLevel.transaction do
+ deduped.each { |row| count += 1 if apply_row(row) }
+ end
+
+ success(stock_level_count: count)
+ end
+
+ # How much a feed's row moves the shelf, stated once for both the bulk
+ # endpoint and the CSV import: a feed reports either the absolute level
+ # its system holds, or a relative movement.
+ #
+ # @param row [Hash] with +adjustment+ or +count_on_hand+
+ # @param current [Integer] what Spree holds now
+ # @return [Integer, nil] nil when the row states neither
+ def self.delta_for(row, current)
+ row = row.with_indifferent_access
+ return integer!('adjustment', row[:adjustment]) if row[:adjustment].present?
+ return nil if row[:count_on_hand].blank?
+
+ integer!('count_on_hand', row[:count_on_hand]) - current.to_i
+ end
+
+ # `to_i` turns "abc" into 0 and "1O" into 1, so a typo in a feed would
+ # zero a shelf or set it to a number nobody sent, with no error to notice.
+ # A feed must say what it means.
+ #
+ # @return [Integer]
+ # @raise [ArgumentError] when the value is not a whole number
+ def self.integer!(column, value)
+ Integer(value.to_s.strip, 10)
+ rescue ArgumentError, TypeError
+ raise ArgumentError, "#{column} must be a whole number, got #{value.inspect}"
+ end
+
+ private
+
+ def apply_row(row)
+ stock_level = Spree::StockLevel.find_or_initialize_by(
+ variant_id: row[:variant_id], stock_location_id: row[:stock_location_id]
+ )
+ stock_level.backorderable = row[:backorderable] if row.key?(:backorderable)
+ stock_level.save! if stock_level.new_record? || stock_level.changed?
+
+ # An absolute level is a delta against what Spree holds *now*, so the
+ # read and the write must be one step: computing it outside the lock
+ # lets two concurrent feeds both measure the same stale count and land
+ # the shelf on neither figure.
+ stock_level.with_lock do
+ delta = delta_for(row, stock_level)
+ next if delta.blank? || delta.zero?
+
+ # Through the location's own mover rather than building a movement by
+ # hand: it types the row as an adjustment and records the reason, so a
+ # feed's correction reads like every other change in the history.
+ stock_level.stock_location.adjust(stock_level.variant, delta, reason: FEED_REASON)
+ end
+
+ true
+ end
+
+ def delta_for(row, stock_level)
+ self.class.delta_for(row, stock_level.count_on_hand)
+ end
+ end
+ end
+end