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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Greatly simplify Product/Variant create/update services
Damian Legawiec18d6ec170182
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.rbindex a9e1aecfc3..1784a65896 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@@ -78,7 +78,7 @@ module Spree:cost_price, :cost_currency,:weight, :height, :width, :depth, :weight_unit, :dimensions_unit,:track_inventory, :tax_category_id,- :option_type, :option_value, :total_on_hand, :position,+ :option_type, :option_value, :position,prices: [:amount, :compare_at_amount, :currency],stock_items: [:stock_location_id, :count_on_hand, :backorderable])diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rbindex 37d589dac9..2c09ec1715 100644--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb@@ -129,7 +129,7 @@ module Spree:cost_price, :cost_currency,:weight, :height, :width, :depth, :weight_unit, :dimensions_unit,:track_inventory, :tax_category_id,- :option_type, :option_value, :total_on_hand, :position,+ :option_type, :option_value, :position,prices: [:amount, :compare_at_amount, :currency]])diff --git a/spree/core/app/models/spree/product/slugs.rb b/spree/core/app/models/spree/product/slugs.rbindex 459d13a343..20aef7c52c 100644--- a/spree/core/app/models/spree/product/slugs.rb+++ b/spree/core/app/models/spree/product/slugs.rb@@ -28,7 +28,7 @@ module Spreedef generate_slugif name.blank? && slug.blank?- translated_model.name.to_url+ translated_model.name&.to_urlelsif slug.blank?name.to_urlelsediff --git a/spree/core/app/services/spree/option_types/update.rb b/spree/core/app/services/spree/option_types/update.rbindex 384a560585..d681dc079b 100644--- a/spree/core/app/services/spree/option_types/update.rb+++ b/spree/core/app/services/spree/option_types/update.rb@@ -47,11 +47,12 @@ module Spreeoption_type.option_values.where.not(name: names).destroy_allif records.any?- Spree::OptionValue.upsert_all(- records,- unique_by: :index_spree_option_values_on_option_type_id_and_name,- update_only: [:presentation, :position]- )+ # Deduplicate by name (last wins) to avoid PG's "ON CONFLICT cannot affect row a second time"+ records = records.reverse.uniq { |r| r[:name] }.reverse++ opts = { update_only: [:presentation, :position] }+ opts[:unique_by] = :index_spree_option_values_on_option_type_id_and_name unless ActiveRecord::Base.connection.adapter_name == 'Mysql2'+ Spree::OptionValue.upsert_all(records, **opts)endsuccess(option_type: option_type.reload)diff --git a/spree/core/app/services/spree/products/create.rb b/spree/core/app/services/spree/products/create.rbindex 317042e1fb..ab699713b9 100644--- a/spree/core/app/services/spree/products/create.rb+++ b/spree/core/app/services/spree/products/create.rb@@ -42,71 +42,12 @@ module Spreereturn success(product: product) if variants_params.blank?variants_params.each do |variant_data|- variant_data = variant_data.to_h.with_indifferent_access- prices_params = variant_data.delete(:prices)- option_type_name = variant_data.delete(:option_type)- option_value_name = variant_data.delete(:option_value)- total_on_hand = variant_data.delete(:total_on_hand)-- variant = product.variants.build(variant_data)-- # Assign option value if provided- if option_type_name.present? && option_value_name.present?- option_type = Spree::OptionType.where(name: option_type_name.to_s.parameterize).first_or_create! do |ot|- ot.presentation = option_type_name- end- product.option_types << option_type unless product.option_types.include?(option_type)-- option_value = option_type.option_values.where(name: option_value_name.to_s.parameterize).first_or_create! do |ov|- ov.presentation = option_value_name- end- variant.option_values = [option_value]- end-- unless variant.save- return failure(variant, variant.errors)- end-- # Set stock- if total_on_hand.present?- variant.stock_items.first&.set_count_on_hand(total_on_hand.to_i)- end-- # Upsert prices- upsert_prices(variant, prices_params) if prices_params.present?+ result = Spree::Variants::Create.call(product: product, params: variant_data)+ return result unless result.success?endsuccess(product: product.reload)end-- def upsert_prices(variant, prices_params)- now = Time.current- currencies = []-- records = prices_params.map do |price_data|- price_data = price_data.to_h.with_indifferent_access- currencies << price_data[:currency]- {- variant_id: variant.id,- currency: price_data[:currency],- amount: price_data[:amount],- compare_at_amount: price_data[:compare_at_amount],- created_at: now,- updated_at: now- }- end-- Spree::Price.where(variant_id: variant.id, price_list_id: nil)- .where.not(currency: currencies)- .update_all(deleted_at: now)-- Spree::Price.upsert_all(- records,- unique_by: :index_spree_prices_on_variant_id_and_currency,- update_only: [:amount, :compare_at_amount]- )- end-endendenddiff --git a/spree/core/app/services/spree/products/update.rb b/spree/core/app/services/spree/products/update.rbindex d5d422d1da..5c6210a1e3 100644--- a/spree/core/app/services/spree/products/update.rb+++ b/spree/core/app/services/spree/products/update.rb@@ -42,76 +42,19 @@ module Spreevariants_params.each do |variant_data|variant_data = variant_data.to_h.with_indifferent_accessvariant_id = variant_data.delete(:id)- prices_params = variant_data.delete(:prices)- option_type_name = variant_data.delete(:option_type)- option_value_name = variant_data.delete(:option_value)- total_on_hand = variant_data.delete(:total_on_hand)- variant = if variant_id.present?- product.variants_including_master.find_by_prefix_id!(variant_id)- else- product.variants.build- end-- # Assign option value if provided- if option_type_name.present? && option_value_name.present?- option_type = Spree::OptionType.where(name: option_type_name.to_s.parameterize).first_or_create! do |ot|- ot.presentation = option_type_name- end- product.option_types << option_type unless product.option_types.include?(option_type)-- option_value = option_type.option_values.where(name: option_value_name.to_s.parameterize).first_or_create! do |ov|- ov.presentation = option_value_name- end- variant.option_values = [option_value]- end-- variant.assign_attributes(variant_data.except(:id))-- unless variant.save- return failure(variant, variant.errors)- end-- # Set stock- if total_on_hand.present?- variant.stock_items.first&.set_count_on_hand(total_on_hand.to_i)+ if variant_id.present?+ variant = product.variants_including_master.find_by_prefix_id!(variant_id)+ result = Spree::Variants::Update.call(variant: variant, params: variant_data)+ else+ result = Spree::Variants::Create.call(product: product, params: variant_data)end- # Upsert prices- upsert_prices(variant, prices_params) if prices_params.present?+ return result unless result.success?endsuccess(product: product.reload)end-- def upsert_prices(variant, prices_params)- now = Time.current- currencies = []-- records = prices_params.map do |price_data|- price_data = price_data.to_h.with_indifferent_access- currencies << price_data[:currency]- {- variant_id: variant.id,- currency: price_data[:currency],- amount: price_data[:amount],- compare_at_amount: price_data[:compare_at_amount],- created_at: now,- updated_at: now- }- end-- Spree::Price.where(variant_id: variant.id, price_list_id: nil)- .where.not(currency: currencies)- .update_all(deleted_at: now)-- Spree::Price.upsert_all(- records,- unique_by: :index_spree_prices_on_variant_id_and_currency,- update_only: [:amount, :compare_at_amount]- )- end-endendenddiff --git a/spree/core/app/services/spree/variants/create.rb b/spree/core/app/services/spree/variants/create.rbindex 674ef09119..e6ea52b835 100644--- a/spree/core/app/services/spree/variants/create.rb+++ b/spree/core/app/services/spree/variants/create.rb@@ -7,7 +7,7 @@ module SpreeApplicationRecord.transaction dorun :create_variantrun :sync_prices- run :sync_stock_items+ run :set_stockendend@@ -15,112 +15,45 @@ module Spreedef create_variant(product:, params:)params = params.to_h.with_indifferent_access- prices_params = params.delete(:prices)- stock_items_params = params.delete(:stock_items)+ @prices_params = params.delete(:prices)+ @stock_items_params = params.delete(:stock_items)option_type_name = params.delete(:option_type)option_value_name = params.delete(:option_value)- total_on_hand = params.delete(:total_on_hand)variant = product.variants.build(params)if option_type_name.present? && option_value_name.present?- assign_option_value(product, variant, option_type_name, option_value_name)+ variant.set_option_value(option_type_name, option_value_name)endif variant.save- # Simple single-location stock shortcut- if total_on_hand.present? && stock_items_params.blank?- variant.stock_items.first&.set_count_on_hand(total_on_hand.to_i)- end-- success(variant: variant, prices_params: prices_params, stock_items_params: stock_items_params)+ success(variant: variant)elsefailure(variant, variant.errors)endend- def sync_prices(variant:, prices_params:, stock_items_params:)- upsert_prices(variant, prices_params) if prices_params.present?- success(variant: variant, stock_items_params: stock_items_params)- end-- def sync_stock_items(variant:, stock_items_params:)- upsert_stock_items(variant, stock_items_params) if stock_items_params.present?- success(variant: variant.reload)- end+ def sync_prices(variant:)+ return success(variant: variant) if @prices_params.blank?- def upsert_prices(variant, prices_params)- now = Time.current- currencies = []-- records = prices_params.map do |price_data|+ @prices_params.each do |price_data|price_data = price_data.to_h.with_indifferent_access- currencies << price_data[:currency]- {- variant_id: variant.id,- currency: price_data[:currency],- amount: price_data[:amount],- compare_at_amount: price_data[:compare_at_amount],- created_at: now,- updated_at: now- }+ variant.set_price(price_data[:currency], price_data[:amount], price_data[:compare_at_amount])end- Spree::Price.where(variant_id: variant.id, price_list_id: nil)- .where.not(currency: currencies)- .update_all(deleted_at: now)-- Spree::Price.upsert_all(- records,- unique_by: :index_spree_prices_on_variant_id_and_currency,- update_only: [:amount, :compare_at_amount]- )+ success(variant: variant.reload)end- def upsert_stock_items(variant, stock_items_params)- now = Time.current- location_ids = []+ def set_stock(variant:)+ return success(variant: variant) if @stock_items_params.blank?- records = stock_items_params.map do |stock_data|+ @stock_items_params.each do |stock_data|stock_data = stock_data.to_h.with_indifferent_access- stock_location = resolve_stock_location(stock_data[:stock_location_id])- location_ids << stock_location.id- {- variant_id: variant.id,- stock_location_id: stock_location.id,- count_on_hand: stock_data[:count_on_hand].to_i,- backorderable: stock_data[:backorderable] || false,- created_at: now,- updated_at: now- }+ location = Spree::StockLocation.find_by_prefix_id!(stock_data[:stock_location_id])+ variant.set_stock(stock_data[:count_on_hand], stock_data[:backorderable], location)end- # Soft-delete stock items for locations not in the payload- Spree::StockItem.where(variant_id: variant.id)- .where.not(stock_location_id: location_ids)- .update_all(deleted_at: now)-- Spree::StockItem.upsert_all(- records,- unique_by: :index_spree_stock_items_unique_without_deleted_at,- update_only: [:count_on_hand, :backorderable]- )- end-- def assign_option_value(product, variant, option_type_name, option_value_name)- option_type = Spree::OptionType.where(name: option_type_name.to_s.parameterize).first_or_create! do |ot|- ot.presentation = option_type_name- end- product.option_types << option_type unless product.option_types.include?(option_type)-- option_value = option_type.option_values.where(name: option_value_name.to_s.parameterize).first_or_create! do |ov|- ov.presentation = option_value_name- end- variant.option_values = [option_value]- end-- def resolve_stock_location(id)- Spree::StockLocation.find_by_param!(id)+ success(variant: variant.reload)endendenddiff --git a/spree/core/app/services/spree/variants/update.rb b/spree/core/app/services/spree/variants/update.rbindex 731d64d156..3daa0073e0 100644--- a/spree/core/app/services/spree/variants/update.rb+++ b/spree/core/app/services/spree/variants/update.rb@@ -7,7 +7,7 @@ module SpreeApplicationRecord.transaction dorun :update_variantrun :sync_prices- run :sync_stock_items+ run :sync_stockendend@@ -15,113 +15,62 @@ module Spreedef update_variant(variant:, params:)params = params.to_h.with_indifferent_access- prices_params = params.delete(:prices)- stock_items_params = params.delete(:stock_items)+ @prices_params = params.delete(:prices)+ @stock_items_params = params.delete(:stock_items)option_type_name = params.delete(:option_type)option_value_name = params.delete(:option_value)- total_on_hand = params.delete(:total_on_hand)- if option_type_name.present? && option_value_name.present?- assign_option_value(variant.product, variant, option_type_name, option_value_name)+ # When explicit prices are provided, remove shortcut attrs to avoid conflicts+ if @prices_params+ params.delete(:price)+ params.delete(:compare_at_price)+ params.delete(:currency)end- variant.assign_attributes(params)-- if variant.save- # Simple single-location stock shortcut- if total_on_hand.present? && stock_items_params.blank?- variant.stock_items.first&.set_count_on_hand(total_on_hand.to_i)- end+ if option_type_name.present? && option_value_name.present?+ variant.set_option_value(option_type_name, option_value_name)+ end- success(variant: variant, prices_params: prices_params, stock_items_params: stock_items_params)+ if variant.update(params)+ success(variant: variant)elsefailure(variant, variant.errors)endend- def sync_prices(variant:, prices_params:, stock_items_params:)- upsert_prices(variant, prices_params) if prices_params.present?- success(variant: variant, stock_items_params: stock_items_params)- end+ def sync_prices(variant:)+ return success(variant: variant) unless @prices_params- def sync_stock_items(variant:, stock_items_params:)- upsert_stock_items(variant, stock_items_params) if stock_items_params.present?- success(variant: variant.reload)- end+ currencies_in_payload = []- def upsert_prices(variant, prices_params)- now = Time.current- currencies = []-- records = prices_params.map do |price_data|+ @prices_params.each do |price_data|price_data = price_data.to_h.with_indifferent_access- currencies << price_data[:currency]- {- variant_id: variant.id,- currency: price_data[:currency],- amount: price_data[:amount],- compare_at_amount: price_data[:compare_at_amount],- created_at: now,- updated_at: now- }+ currencies_in_payload << price_data[:currency]+ variant.set_price(price_data[:currency], price_data[:amount], price_data[:compare_at_amount])end# Soft-delete prices for currencies not in the payload- Spree::Price.where(variant_id: variant.id, price_list_id: nil)- .where.not(currency: currencies)- .update_all(deleted_at: now)-- Spree::Price.upsert_all(- records,- unique_by: :index_spree_prices_on_variant_id_and_currency,- update_only: [:amount, :compare_at_amount]- )+ variant.prices.base_prices.where.not(currency: currencies_in_payload).destroy_all++ success(variant: variant.reload)end- def upsert_stock_items(variant, stock_items_params)- now = Time.current- location_ids = []+ def sync_stock(variant:)+ return success(variant: variant) unless @stock_items_params++ location_ids_in_payload = []- records = stock_items_params.map do |stock_data|+ @stock_items_params.each do |stock_data|stock_data = stock_data.to_h.with_indifferent_access- stock_location = resolve_stock_location(stock_data[:stock_location_id])- location_ids << stock_location.id- {- variant_id: variant.id,- stock_location_id: stock_location.id,- count_on_hand: stock_data[:count_on_hand].to_i,- backorderable: stock_data[:backorderable] || false,- created_at: now,- updated_at: now- }+ location = Spree::StockLocation.find_by_prefix_id!(stock_data[:stock_location_id])+ location_ids_in_payload << location.id+ variant.set_stock(stock_data[:count_on_hand], stock_data[:backorderable], location)end# Soft-delete stock items for locations not in the payload- Spree::StockItem.where(variant_id: variant.id)- .where.not(stock_location_id: location_ids)- .update_all(deleted_at: now)-- Spree::StockItem.upsert_all(- records,- unique_by: :index_spree_stock_items_unique_without_deleted_at,- update_only: [:count_on_hand, :backorderable]- )- end-- def assign_option_value(product, variant, option_type_name, option_value_name)- option_type = Spree::OptionType.where(name: option_type_name.to_s.parameterize).first_or_create! do |ot|- ot.presentation = option_type_name- end- product.option_types << option_type unless product.option_types.include?(option_type)+ variant.stock_items.where.not(stock_location_id: location_ids_in_payload).update_all(deleted_at: Time.current)- option_value = option_type.option_values.where(name: option_value_name.to_s.parameterize).first_or_create! do |ov|- ov.presentation = option_value_name- end- variant.option_values = [option_value]- end-- def resolve_stock_location(id)- Spree::StockLocation.find_by_param!(id)+ success(variant: variant.reload)endendenddiff --git a/spree/core/spec/services/spree/products/create_spec.rb b/spree/core/spec/services/spree/products/create_spec.rbindex c0c1baaf4a..522e834d67 100644--- a/spree/core/spec/services/spree/products/create_spec.rb+++ b/spree/core/spec/services/spree/products/create_spec.rb@@ -88,7 +88,7 @@ RSpec.describe Spree::Products::Create doendend- describe 'variant with prices upserted' do+ describe 'variant with prices' dolet(:params) do{name: 'Multi-price Product',@@ -108,7 +108,7 @@ RSpec.describe Spree::Products::Create do}end- it 'upserts prices for the variant' do+ it 'sets prices for the variant' doexpect(result).to be_successvariant = result.value[:product].variants.find_by(sku: 'MP-1')usd = variant.prices.find_by(currency: 'USD')@@ -120,7 +120,7 @@ RSpec.describe Spree::Products::Create doendend- describe 'variant with total_on_hand' do+ describe 'variant with stock_items' dolet!(:stock_location) { create(:stock_location, propagate_all_variants: true) }let(:params) do@@ -129,7 +129,14 @@ RSpec.describe Spree::Products::Create doprice: 10,shipping_category_id: shipping_category.id,variants: [- { sku: 'STK-1', option_type: 'Size', option_value: 'M', total_on_hand: 25 }+ {+ sku: 'STK-1',+ option_type: 'Size',+ option_value: 'M',+ stock_items: [+ { stock_location_id: stock_location.prefixed_id, count_on_hand: 25 }+ ]+ }]}end@@ -137,7 +144,8 @@ RSpec.describe Spree::Products::Create doit 'sets stock level' doexpect(result).to be_successvariant = result.value[:product].variants.find_by(sku: 'STK-1')- expect(variant.total_on_hand).to eq(25)+ si = variant.stock_items.find_by(stock_location: stock_location)+ expect(si.count_on_hand).to eq(25)endenddiff --git a/spree/core/spec/services/spree/variants/create_spec.rb b/spree/core/spec/services/spree/variants/create_spec.rbindex 15c0aca006..d776662f76 100644--- a/spree/core/spec/services/spree/variants/create_spec.rb+++ b/spree/core/spec/services/spree/variants/create_spec.rb@@ -51,7 +51,7 @@ RSpec.describe Spree::Variants::Create do}end- it 'creates prices via upsert' do+ it 'creates prices' doexpect(result).to be_successvariant = result.value[:variant]expect(variant.prices.find_by(currency: 'USD').amount.to_f).to eq(25.00)@@ -77,7 +77,7 @@ RSpec.describe Spree::Variants::Create do}end- it 'sets stock via upsert' do+ it 'sets stock levels' doexpect(result).to be_successvariant = result.value[:variant]si1 = variant.stock_items.find_by(stock_location: stock_location_1)@@ -107,40 +107,6 @@ RSpec.describe Spree::Variants::Create doendend- describe 'total_on_hand shortcut' do- before { Spree::StockLocation.update_all(propagate_all_variants: true) }-- let(:params) { { sku: 'TOH-V', option_type: option_type.name, option_value: 'toh', price: 10, total_on_hand: 42 } }-- it 'sets stock on first stock item' do- expect(result).to be_success- expect(result.value[:variant].total_on_hand).to eq(42)- end- end-- describe 'total_on_hand ignored when stock_items present' do- let!(:stock_location) { Spree::StockLocation.first || create(:stock_location) }-- let(:params) do- {- sku: 'BOTH-V',- option_type: option_type.name,- option_value: 'both',- price: 10,- total_on_hand: 99,- stock_items: [- { stock_location_id: stock_location.prefixed_id, count_on_hand: 5 }- ]- }- end-- it 'uses stock_items, not total_on_hand' do- expect(result).to be_success- variant = result.value[:variant]- expect(variant.stock_items.find_by(stock_location: stock_location).count_on_hand).to eq(5)- end- end-describe 'option type auto-creation' dolet(:params) { { sku: 'AUTO-OPT', price: 10, option_type: 'Material', option_value: 'Cotton' } }diff --git a/spree/core/spec/services/spree/variants/update_spec.rb b/spree/core/spec/services/spree/variants/update_spec.rbindex e8aad30986..018e75932c 100644--- a/spree/core/spec/services/spree/variants/update_spec.rb+++ b/spree/core/spec/services/spree/variants/update_spec.rb@@ -25,7 +25,7 @@ RSpec.describe Spree::Variants::Update doendend- describe 'upsert prices' do+ describe 'sync prices' dolet(:params) do{prices: [@@ -43,7 +43,7 @@ RSpec.describe Spree::Variants::Update doendend- describe 'upsert prices removes missing currencies' do+ describe 'sync prices removes missing currencies' dobefore dovariant.prices.create!(currency: 'EUR', amount: 20)variant.prices.create!(currency: 'GBP', amount: 15)@@ -67,7 +67,7 @@ RSpec.describe Spree::Variants::Update doendend- describe 'upsert stock_items' do+ describe 'sync stock_items' dolet!(:stock_location) { Spree::StockLocation.first || create(:stock_location) }let(:params) do@@ -86,7 +86,7 @@ RSpec.describe Spree::Variants::Update doendend- describe 'upsert stock_items removes missing locations' do+ describe 'sync stock_items removes missing locations' dolet!(:loc1) { Spree::StockLocation.first || create(:stock_location) }let!(:loc2) { create(:stock_location, name: 'Secondary') }@@ -117,16 +117,7 @@ RSpec.describe Spree::Variants::Update doit 'assigns new option value' doexpect(result).to be_success- expect(result.value[:variant].option_values.first.presentation).to eq('Blue')- end- end-- describe 'total_on_hand shortcut' do- let(:params) { { total_on_hand: 77 } }-- it 'sets stock on first stock item' do- expect(result).to be_success- expect(result.value[:variant].total_on_hand).to eq(77)+ expect(result.value[:variant].option_values.map(&:presentation)).to include('Blue')endend