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.

Give a variant one write path for its options, prices and stock (#14477)

Damian Legawiec01ffa80b90a8
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb
index 9ec9ddbe04..f941c1c744 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products/variants_controller.rb
@@ -29,6 +29,22 @@ module Spree
[:prices, stock_levels: :stock_location]
end
+ def create_workflow
+ Spree.variant_create_workflow
+ end
+
+ def update_workflow
+ Spree.variant_update_workflow
+ end
+
+ # A variant belongs to a product, not directly to a store, and
+ # everything nested in the payload is resolved through it — an
+ # option value attaches its option type to the product, a stock
+ # location is scoped to the product's store.
+ def create_workflow_arguments
+ { product: @parent, attributes: permitted_params }
+ end
+
def permitted_params
params.permit(
*model_additional_permitted_attributes,
diff --git a/spree/core/app/workflows/spree/products/nested_attributes.rb b/spree/core/app/workflows/spree/products/nested_attributes.rb
index 8357d6cfc7..ca81769db5 100644
--- a/spree/core/app/workflows/spree/products/nested_attributes.rb
+++ b/spree/core/app/workflows/spree/products/nested_attributes.rb
@@ -30,9 +30,7 @@ module Spree
variant_data = raw.to_h.with_indifferent_access
variant_id = variant_data.delete(:id)
- variant = resolve_variant(product, variant_data, variant_id, variant_ids_in_payload)
- variant.assign_attributes(variant_data)
- variant.save!
+ variant = write_variant(product, variant_data, variant_id, variant_ids_in_payload)
variant_ids_in_payload << variant.id
mutated = true
@@ -46,6 +44,29 @@ module Spree
sync_variant_state(product) if mutated
end
+ # Delegates to the variant workflows rather than assigning and saving
+ # here, so a variant written as part of a product payload passes the
+ # same gate — and the same :validate handlers — as one written through
+ # the variants endpoint.
+ def write_variant(product, variant_data, variant_id, consumed_ids)
+ existing = resolve_variant(product, variant_data, variant_id, consumed_ids)
+
+ result =
+ if existing
+ Spree.variant_update_workflow.call(variant: existing, attributes: variant_data)
+ else
+ Spree.variant_create_workflow.call(product: product, attributes: variant_data)
+ end
+
+ # A rejection inside the nested write is the product write failing;
+ # raising rolls the whole payload back rather than leaving a product
+ # with half its variants.
+ raise ActiveRecord::RecordInvalid, result.value if result.failure?
+
+ result.value
+ end
+
+ # The variant this entry names, or nil when it describes a new one.
def resolve_variant(product, variant_data, variant_id, consumed_ids)
return product.variants.find_by_param!(variant_id) if variant_id.present?
@@ -53,11 +74,8 @@ module Spree
# option-less default variant — the simple-product case. Updating it in
# place keeps its id, the order lines referencing it, and any prices or
# stock the payload does not mention.
- if reuse_default_variant?(product, variant_data, consumed_ids)
- product.default_variant
- else
- product.variants.build
- end
+ # nil means "a new variant", which Spree::Variants::Create builds.
+ reuse_default_variant?(product, variant_data, consumed_ids) ? product.default_variant : nil
end
def reuse_default_variant?(product, variant_data, consumed_ids)
diff --git a/spree/core/app/workflows/spree/variants/create.rb b/spree/core/app/workflows/spree/variants/create.rb
new file mode 100644
index 0000000000..8d77e8f3b0
--- /dev/null
+++ b/spree/core/app/workflows/spree/variants/create.rb
@@ -0,0 +1,66 @@
+module Spree
+ module Variants
+ # Creates a variant on a product. The single gate for variant creation —
+ # the standalone variants endpoint and the nested payload on a product
+ # write both run through it, so a :validate handler sees every variant a
+ # catalog gains.
+ #
+ # The product is a parameter rather than something read off the payload
+ # because everything nested needs it: an option value attaches an option
+ # type to the product, and a stock location is resolved through the
+ # product's store. The model defers those writes when it is built without
+ # an owner; a caller of this workflow has already named one, so they
+ # apply directly.
+ class Create < Spree::Workflow
+ include Spree::Variants::NestedAttributes
+
+ hooks :validate, :after_create
+
+ # The unsaved record a :validate handler reads.
+ attr_reader :variant
+
+ # @param product [Spree::Product]
+ # @param attributes [Hash] may carry `options`, `prices`, `stock_levels`
+ # @return [Spree::ServiceModule::Result] value is the variant
+ def perform(product:, attributes: {})
+ super
+
+ step :build_variant
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :save_variant
+ step :apply_nested_attributes
+ run_hooks :after_create
+ end
+
+ success(variant)
+ end
+
+ private
+
+ def build_variant
+ attrs = attributes.to_h.with_indifferent_access
+
+ @options_params = attrs.delete(:options)
+ @prices_params = attrs.delete(:prices)
+ @stock_levels_params = attrs.delete(:stock_levels) || attrs.delete(:stock_levels_attributes)
+
+ @variant = product.variants.new(attrs)
+ end
+
+ def save_variant
+ failure(variant) unless variant.save
+ end
+
+ # Options first: an option value attaches its option type to the
+ # product, and the variant's identity depends on it before prices or
+ # stock mean anything.
+ def apply_nested_attributes
+ apply_options(variant, @options_params)
+ apply_prices(variant, @prices_params)
+ apply_stock_levels(variant, @stock_levels_params)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/variants/nested_attributes.rb b/spree/core/app/workflows/spree/variants/nested_attributes.rb
new file mode 100644
index 0000000000..e4b3a71940
--- /dev/null
+++ b/spree/core/app/workflows/spree/variants/nested_attributes.rb
@@ -0,0 +1,90 @@
+module Spree
+ module Variants
+ # Applies the nested data a variant write can carry: its option values,
+ # its prices and its stock levels. Shared by Spree::Variants::Create and
+ # ::Update so both write paths reconcile them the same way.
+ #
+ # All three go through the model's own writers (`set_option_value`,
+ # `set_price`, `set_stock`) rather than touching rows directly. That is
+ # deliberate: `set_price` reuses the loaded prices association so a
+ # response serialized in the same request sees the write, and `set_stock`
+ # routes a count change through a stock movement so it lands in the
+ # history like every other adjustment.
+ #
+ # The three payloads do not share one nullability contract, because the
+ # records do not carry the same risk:
+ #
+ # * `prices` is a full replacement — a currency missing from the payload
+ # loses its base price, and `[]` clears every one.
+ # * `stock_levels` is upsert-only. Dropping a warehouse from a payload
+ # must not silently destroy its stock: the count is a fact about a
+ # shelf, with a movement history behind it, and a partial payload is
+ # far likelier than an instruction to zero a warehouse.
+ # * `options` is upsert-only, matching what the model has always done.
+ module NestedAttributes
+ extend ActiveSupport::Concern
+
+ private
+
+ # @param variant [Spree::Variant]
+ # @param options_params [Array<Hash>, nil]
+ # @return [void]
+ def apply_options(variant, options_params)
+ return if options_params.blank?
+
+ options_params.each do |raw|
+ option = raw.to_h.with_indifferent_access
+ next if option[:name].blank? || option[:value].blank?
+
+ variant.set_option_value(option[:name], option[:value], option[:position])
+ end
+ end
+
+ # @param variant [Spree::Variant]
+ # @param prices_params [Array<Hash>, nil] nil leaves prices alone; an
+ # empty array clears every base price
+ # @return [void]
+ def apply_prices(variant, prices_params)
+ return if prices_params.nil?
+
+ currencies = []
+
+ Array(prices_params).each do |raw|
+ price = raw.to_h.with_indifferent_access
+ next if price[:currency].blank?
+
+ currencies << price[:currency]
+ variant.set_price(price[:currency], price[:amount], price[:compare_at_amount])
+ end
+
+ return unless variant.persisted?
+
+ variant.prices.base_prices.where.not(currency: currencies).destroy_all
+ end
+
+ # @param variant [Spree::Variant]
+ # @param stock_levels_params [Array<Hash>, nil]
+ # @return [void]
+ def apply_stock_levels(variant, stock_levels_params)
+ return if stock_levels_params.blank?
+
+ Array(stock_levels_params).each do |raw|
+ row = raw.to_h.with_indifferent_access
+ next if row[:stock_location_id].blank?
+
+ # Scoped through the product's own store: Spree::StockLocation
+ # lookup is global, so an id belonging to another store would
+ # otherwise put this variant's stock in that store's warehouse.
+ location = stock_location_for(variant, row[:stock_location_id])
+ next if location.nil?
+
+ variant.set_stock(row[:count_on_hand], row[:backorderable], location)
+ end
+ end
+
+ def stock_location_for(variant, param)
+ variant.product&.store&.stock_locations&.find_by_param(param)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/variants/update.rb b/spree/core/app/workflows/spree/variants/update.rb
new file mode 100644
index 0000000000..ba310340ec
--- /dev/null
+++ b/spree/core/app/workflows/spree/variants/update.rb
@@ -0,0 +1,55 @@
+module Spree
+ module Variants
+ # Updates a variant, reconciling the option values, prices and stock
+ # levels the payload carries (see Spree::Variants::NestedAttributes —
+ # prices replace, stock levels and options upsert).
+ #
+ # Handlers reading `variant.changes` in :validate see the pending edit
+ # before it is written.
+ class Update < Spree::Workflow
+ include Spree::Variants::NestedAttributes
+
+ hooks :validate, :after_update
+
+ # @param variant [Spree::Variant]
+ # @param attributes [Hash] may carry `options`, `prices`, `stock_levels`
+ # @return [Spree::ServiceModule::Result] value is the variant
+ def perform(variant:, attributes: {})
+ super
+
+ step :assign_attributes
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :save_variant
+ step :apply_nested_attributes
+ run_hooks :after_update
+ end
+
+ success(variant)
+ end
+
+ private
+
+ def assign_attributes
+ attrs = attributes.to_h.with_indifferent_access
+
+ @options_params = attrs.delete(:options)
+ @prices_params = attrs.delete(:prices)
+ @stock_levels_params = attrs.delete(:stock_levels) || attrs.delete(:stock_levels_attributes)
+
+ variant.assign_attributes(attrs)
+ end
+
+ def save_variant
+ failure(variant) unless variant.save
+ end
+
+ def apply_nested_attributes
+ apply_options(variant, @options_params)
+ apply_prices(variant, @prices_params)
+ apply_stock_levels(variant, @stock_levels_params)
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index d040b0da2d..9432e5cb4d 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -137,6 +137,11 @@ module Spree
product_update_workflow: 'Spree::Products::Update',
product_destroy_workflow: 'Spree::Products::Destroy',
product_activate_workflow: 'Spree::Products::Activate',
+
+ # variants — every write path runs through these, so a :validate
+ # handler sees a nested payload and the variants endpoint alike
+ variant_create_workflow: 'Spree::Variants::Create',
+ variant_update_workflow: 'Spree::Variants::Update',
product_archive_workflow: 'Spree::Products::Archive',
product_draft_workflow: 'Spree::Products::Draft',
diff --git a/spree/core/spec/workflows/spree/variants/write_spec.rb b/spree/core/spec/workflows/spree/variants/write_spec.rb
new file mode 100644
index 0000000000..dd7d6010e7
--- /dev/null
+++ b/spree/core/spec/workflows/spree/variants/write_spec.rb
@@ -0,0 +1,104 @@
+require 'spec_helper'
+
+RSpec.describe 'Spree::Variants write workflows' do
+ let(:store) { @default_store }
+ let(:product) { create(:product, store: store) }
+ let!(:stock_location) { create(:stock_location, store: store) }
+
+ describe Spree::Variants::Create do
+ it 'creates a variant on the product' do
+ result = described_class.call(product: product, attributes: { sku: 'NEW-1' })
+
+ expect(result).to be_success
+ expect(result.value.sku).to eq('NEW-1')
+ expect(result.value.product).to eq(product)
+ end
+
+ # The model defers these when it is built without an owner; the workflow
+ # names the product up front, so they apply directly.
+ it 'applies options, prices and stock in one call' do
+ result = described_class.call(
+ product: product,
+ attributes: {
+ sku: 'FULL-1',
+ options: [{ name: 'Color', value: 'Red' }],
+ prices: [{ currency: 'USD', amount: 12 }],
+ stock_levels: [{ stock_location_id: stock_location.id, count_on_hand: 7 }]
+ }
+ )
+
+ variant = result.value
+ expect(result).to be_success
+ expect(variant.option_values.map(&:presentation)).to include('Red')
+ expect(variant.price_in('USD').amount).to eq(12)
+ expect(variant.stock_levels.find_by(stock_location: stock_location).count_on_hand).to eq(7)
+ end
+
+ it 'can be vetoed before the variant is written' do
+ Spree.hooks.clear!
+ Spree.hooks.register('variants.create.validate') { |workflow| workflow.reject!('nope') }
+
+ expect(described_class.call(product: product, attributes: { sku: 'VETO-1' })).not_to be_success
+ expect(Spree::Variant.where(sku: 'VETO-1')).to be_empty
+ ensure
+ Spree.hooks.clear!
+ end
+ end
+
+ describe Spree::Variants::Update do
+ let(:variant) { create(:variant, product: product) }
+
+ it 'updates plain attributes' do
+ result = described_class.call(variant: variant, attributes: { sku: 'CHANGED' })
+
+ expect(result).to be_success
+ expect(variant.reload.sku).to eq('CHANGED')
+ end
+
+ # Prices replace: a currency missing from the payload loses its base price.
+ it 'replaces prices' do
+ variant.set_price('USD', 10)
+ variant.set_price('EUR', 20)
+
+ described_class.call(variant: variant, attributes: { prices: [{ currency: 'USD', amount: 15 }] })
+
+ expect(variant.reload.price_in('USD').amount).to eq(15)
+ expect(variant.price_in('EUR')&.amount).to be_nil
+ end
+
+ # Stock upserts: a warehouse missing from the payload keeps its stock,
+ # because a partial payload must not silently destroy a shelf count.
+ it 'leaves a stock level the payload does not mention' do
+ other = create(:stock_location, store: store)
+ variant.set_stock(5, nil, stock_location)
+ variant.set_stock(3, nil, other)
+
+ described_class.call(
+ variant: variant,
+ attributes: { stock_levels: [{ stock_location_id: stock_location.id, count_on_hand: 9 }] }
+ )
+
+ expect(variant.reload.stock_levels.find_by(stock_location: stock_location).count_on_hand).to eq(9)
+ expect(variant.stock_levels.find_by(stock_location: other).count_on_hand).to eq(3)
+ end
+
+ # Spree::StockLocation lookup is global, so an id from another store must
+ # not put this variant's stock in that store's warehouse.
+ # The variant factory propagates into every existing stock location
+ # regardless of store, so the foreign one is created after the variant to
+ # keep this about what the workflow does rather than what the factory did.
+ it 'ignores a stock location belonging to another store' do
+ variant
+ foreign = create(:stock_location, store: create(:store))
+ levels_before = variant.reload.stock_levels.pluck(:stock_location_id).sort
+
+ described_class.call(
+ variant: variant,
+ attributes: { stock_levels: [{ stock_location_id: foreign.id, count_on_hand: 4 }] }
+ )
+
+ expect(variant.reload.stock_levels.pluck(:stock_location_id).sort).to eq(levels_before)
+ expect(variant.stock_levels.map(&:stock_location)).not_to include(foreign)
+ end
+ end
+end