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
Move the price list bulk payloads into workflows
Damian Legawiecafd8ab4ac958
diff --git a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rbindex 5142d6e5c2..5af1034afb 100644--- a/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/price_lists_controller.rb@@ -70,6 +70,30 @@ module Spreeendend+ # POST /api/v3/admin/price_lists+ def create+ authorize! :create, model_class++ result = Spree.price_list_create_workflow.call(store: current_store, attributes: permitted_params)++ if result.success?+ render json: serialize_resource(result.value), status: :created+ else+ render_result_error(result)+ end+ end++ # PATCH /api/v3/admin/price_lists/:id+ def update+ result = Spree.price_list_update_workflow.call(price_list: @resource, attributes: permitted_params)++ if result.success?+ render json: serialize_resource(result.value)+ else+ render_result_error(result)+ end+ end+# GET /api/v3/admin/price_lists/:id/prices## The spreadsheet editor's data source. Returns every Price rowdiff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rbindex 7010035008..0d8e220b66 100644--- a/spree/core/app/models/spree/price_list.rb+++ b/spree/core/app/models/spree/price_list.rb@@ -18,20 +18,7 @@ module Spreehas_many :products, -> { distinct }, through: :variants, source: :productalias price_list_products products- # Override default nested attributes to use bulk_update_prices for performance- attr_reader :prices_attributes-- # Sets the prices attributes for bulk update- # @param attributes [Array<Hash>] array of price attributes with :id, :amount, :compare_at_amount- # @return [Array<Hash>] array of price attributes with :id, :amount, :compare_at_amount- def prices_attributes=(attributes)- @prices_attributes = attributes.values- end-- after_update :process_bulk_prices_updateafter_save :apply_pending_rules- after_save :apply_pending_product_ids- after_save :apply_pending_prices# @return [Array<String>] prefixed product ids in this list,# encoded inline to avoid hydrating N Product records.@@ -40,36 +27,6 @@ module Spreeproduct_ids.sort.map { |pk| "#{prefix}_#{Spree::PrefixedId::SQIDS.encode([pk])}" }end- # Reconciles list membership. Removes prices for products no longer- # in `ids` and adds placeholder prices for the new ones.- #- # @param ids [Array<String>] raw product PKs (prefixed strings are- # resolved upstream by `Spree::Base#assign_attributes`).- # @return [void]- def product_ids=(ids)- @pending_product_ids = Array(ids).compact.uniq- end-- # Flat-payload writer for `prices`. Bulk-upserts the listed rows in- # `after_save` so newly-added products have their placeholder rows- # materialized first. Nullability contract:- # - `nil` → no-op- # - `[]` → clear every override on this list- # - `[…]` → upsert listed rows, leave the rest alone- #- # @param rows [Array<Hash>, Array<Spree::Price>, nil]- # @return [void]- def prices=(rows)- first = Array(rows).first- return super(rows) if first.is_a?(Spree::Price)- return if rows.nil?-- @pending_prices = Array(rows).map do |row|- row.respond_to?(:to_unsafe_h) ? row.to_unsafe_h.with_indifferent_access : row.with_indifferent_access- end- @pending_prices_clear = rows.empty?- end-# Flat-payload writer for `rules`. See# {Spree::TypedAssociations#assign_typed_association}.def rules=(rows)@@ -293,80 +250,10 @@ module Spreeprivate- # Processes the bulk prices update- # @return [void]- def process_bulk_prices_update- return if @prices_attributes.blank?-- bulk_update_prices(@prices_attributes)- @prices_attributes = nil- end-def apply_pending_rulesflush_pending_typed_association(:price_rules)end- def apply_pending_product_ids- return unless @pending_product_ids-- desired = @pending_product_ids- @pending_product_ids = nil-- current = product_ids- to_remove = current - desired- to_add = desired - current-- return unless to_remove.any? || to_add.any?-- remove_products(to_remove) if to_remove.any?- add_products(to_add) if to_add.any?-- # Membership is changed via raw `upsert_all`/`delete_all` on `prices`,- # which bypasses the `variants`/`products` association caches (and the- # `product_ids` ids-reader memo `current` populated above). Reset them so- # a same-request read — e.g. the serializer's `product_ids` — reflects the- # new membership instead of the pre-change set.- association(:variants).reset- association(:products).reset- end-- def apply_pending_prices- pending = @pending_prices- cleared = @pending_prices_clear- return if pending.nil?-- @pending_prices = nil- @pending_prices_clear = nil-- if cleared- variant_ids = prices.distinct.pluck(:variant_id)- prices.update_all(amount: nil, compare_at_amount: nil, updated_at: Time.current)- touch_variants(variant_ids)- return- end-- rows = pending.filter_map do |row|- # `variant_id` may arrive as a prefixed string (legacy callers,- # console) or already decoded (the controller's `permitted_params`- # runs through `normalize_params`). Handle both.- raw = row[:variant_id]- variant_id = Spree::PrefixedId.prefixed_id?(raw) ? Spree::PrefixedId.decode_prefixed_id(raw) : raw- next if variant_id.blank? || row[:currency].blank?-- {- variant_id: variant_id,- currency: row[:currency],- price_list_id: id,- amount: row[:amount],- compare_at_amount: row[:compare_at_amount]- }- end- return if rows.empty?-- Spree::Prices::BulkUpsert.call(rows: rows)- touch_variants(rows.map { |r| r[:variant_id] }.uniq)- end-# Touches the variants in a background job# @param variant_ids [Array<String>] array of variant ids# @return [void]diff --git a/spree/core/app/workflows/spree/price_lists/create.rb b/spree/core/app/workflows/spree/price_lists/create.rbnew file mode 100644index 0000000000..948d54792a--- /dev/null+++ b/spree/core/app/workflows/spree/price_lists/create.rb@@ -0,0 +1,51 @@+module Spree+ module PriceLists+ # Creates a price list. The bulk payloads a list can arrive with — which+ # products it covers, and their price overrides — are applied by+ # Spree::PriceLists::Update once the row exists, since both paths reconcile+ # them the same way and membership has to settle before prices.+ class Create < Spree::Workflow+ hooks :validate, :after_create++ attr_reader :price_list++ # @param store [Spree::Store]+ # @param attributes [Hash] may carry `product_ids` and `prices`+ # @return [Spree::ServiceModule::Result] value is the price list+ def perform(store:, attributes: {})+ super++ step :build_price_list+ run_hooks :validate++ ApplicationRecord.transaction do+ step :save_price_list+ step :apply_bulk_payloads+ run_hooks :after_create+ end++ success(price_list)+ end++ private++ # Held back from the new record so it saves as a plain row; the+ # collections are reconciled once it has an id.+ def build_price_list+ @bulk_payloads = attributes.slice(:product_ids, :prices)+ @price_list = store.price_lists.new(attributes.except(:product_ids, :prices))+ end++ def save_price_list+ failure(price_list) unless price_list.save+ end++ def apply_bulk_payloads+ return if @bulk_payloads.empty?++ result = Spree.price_list_update_workflow.call(price_list: price_list, attributes: @bulk_payloads)+ failure(price_list, result.error) unless result.success?+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/price_lists/update.rb b/spree/core/app/workflows/spree/price_lists/update.rbnew file mode 100644index 0000000000..74214f0ef8--- /dev/null+++ b/spree/core/app/workflows/spree/price_lists/update.rb@@ -0,0 +1,118 @@+module Spree+ module PriceLists+ # Updates a price list and applies the bulk payloads that ride with it:+ # which products the list covers, and the individual price overrides.+ #+ # Those used to be attribute writers that stashed their input and+ # after_save callbacks that applied it — a multi-step flow disguised as an+ # assignment, where the order the callbacks happened to run in was+ # load-bearing (membership has to settle before prices, so a newly added+ # product has a row to overwrite). Here that order is the step order, and a+ # handler can veto the whole edit before any of it is written.+ class Update < Spree::Workflow+ hooks :validate, :after_update++ # @param price_list [Spree::PriceList]+ # @param attributes [Hash] may carry `product_ids` and `prices`+ # @return [Spree::ServiceModule::Result] value is the price list+ def perform(price_list:, attributes: {})+ super++ step :assign_attributes+ run_hooks :validate++ ApplicationRecord.transaction do+ step :save_price_list+ step :apply_product_ids+ step :apply_prices+ run_hooks :after_update+ end++ success(price_list)+ end++ private++ # The bulk payloads are held back rather than assigned, so the record+ # saves as a plain row and the collections are reconciled afterwards.+ def assign_attributes+ @product_ids = attributes.key?(:product_ids) ? Array(attributes[:product_ids]).compact.uniq : nil+ @prices = attributes.key?(:prices) ? attributes[:prices] : nil++ price_list.assign_attributes(attributes.except(:product_ids, :prices))+ end++ def save_price_list+ failure(price_list) unless price_list.save+ end++ def apply_product_ids+ return if @product_ids.nil?++ current = price_list.product_ids+ to_remove = current - @product_ids+ to_add = @product_ids - current+ return if to_remove.empty? && to_add.empty?++ price_list.remove_products(to_remove) if to_remove.any?+ price_list.add_products(to_add) if to_add.any?++ # Membership changes through raw upsert_all/delete_all on prices, which+ # leaves the variants and products caches holding the old set — a+ # same-request read, such as the serializer's product_ids, would still+ # report the membership from before the edit.+ price_list.association(:variants).reset+ price_list.association(:products).reset+ end++ def apply_prices+ return if @prices.nil?++ # An empty array means "clear every override on this list", which is a+ # different thing from sending no prices at all.+ return clear_prices if @prices.empty?++ rows = price_rows+ return if rows.empty?++ Spree::Prices::BulkUpsert.call(rows: rows)+ touch_variants(rows.map { |row| row[:variant_id] }.uniq)+ end++ def clear_prices+ variant_ids = price_list.prices.distinct.pluck(:variant_id)+ price_list.prices.update_all(amount: nil, compare_at_amount: nil, updated_at: Time.current)+ touch_variants(variant_ids)+ end++ def price_rows+ Array(@prices).filter_map do |raw|+ row = raw.respond_to?(:to_unsafe_h) ? raw.to_unsafe_h.with_indifferent_access : raw.with_indifferent_access++ # variant_id arrives prefixed from the console and legacy callers,+ # already decoded from a controller that ran normalize_params.+ variant_id = if Spree::PrefixedId.prefixed_id?(row[:variant_id])+ Spree::PrefixedId.decode_prefixed_id(row[:variant_id])+ else+ row[:variant_id]+ end+ next if variant_id.blank? || row[:currency].blank?++ {+ variant_id: variant_id,+ currency: row[:currency],+ price_list_id: price_list.id,+ amount: row[:amount],+ compare_at_amount: row[:compare_at_amount]+ }+ end+ end++ def touch_variants(variant_ids)+ return if variant_ids.blank?++ Spree::Variants::TouchJob.perform_later(variant_ids)+ end+ end+ end+enddiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex 55c70e23a0..185aa41a0f 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -134,6 +134,8 @@ module Spreeproduct_draft_workflow: 'Spree::Products::Draft',# price lists+ price_list_create_workflow: 'Spree::PriceLists::Create',+ price_list_update_workflow: 'Spree::PriceLists::Update',price_list_activate_workflow: 'Spree::PriceLists::Activate',price_list_deactivate_workflow: 'Spree::PriceLists::Deactivate',diff --git a/spree/core/spec/models/spree/price_list_spec.rb b/spree/core/spec/models/spree/price_list_spec.rbindex b9a410e2f5..7c8b63dc0b 100644--- a/spree/core/spec/models/spree/price_list_spec.rb+++ b/spree/core/spec/models/spree/price_list_spec.rb@@ -160,19 +160,20 @@ describe Spree::PriceList, type: :model doendend- describe '#product_ids=' do+ describe 'product membership' dolet(:store) { create(:store, supported_currencies: 'USD,EUR,GBP') }let(:price_list) { create(:price_list, store: store) }let(:product1) { create(:product) }let(:product2) { create(:product) }- # Guards the POST/PATCH /price_lists response: membership is reconciled in- # an after_save via raw upsert_all/delete_all (bypassing the products- # association cache), so `product_ids` / `product_prefixed_ids` — which the+ # Guards the POST/PATCH /price_lists response: membership is reconciled+ # through raw upsert_all/delete_all, which bypasses the products+ # association cache, so `product_ids` / `product_prefixed_ids` — which the# serializer renders — must reflect the change WITHOUT a reload.it 'reflects assigned products in product_ids without reload' do- price_list.product_ids = [product1.id, product2.id]- price_list.save!+ Spree.price_list_update_workflow.call(+ price_list: price_list, attributes: { product_ids: [product1.id, product2.id] }+ )expect(price_list.product_ids).to match_array([product1.id, product2.id])expect(price_list.product_prefixed_ids).to match_array(@@ -181,11 +182,12 @@ describe Spree::PriceList, type: :model doendit 'reflects a partial removal in product_ids without reload' do- price_list.product_ids = [product1.id, product2.id]- price_list.save!-- price_list.product_ids = [product1.id]- price_list.save!+ Spree.price_list_update_workflow.call(+ price_list: price_list, attributes: { product_ids: [product1.id, product2.id] }+ )+ Spree.price_list_update_workflow.call(+ price_list: price_list, attributes: { product_ids: [product1.id] }+ )expect(price_list.product_ids).to eq([product1.id])enddiff --git a/spree/core/spec/workflows/spree/price_lists/write_spec.rb b/spree/core/spec/workflows/spree/price_lists/write_spec.rbnew file mode 100644index 0000000000..0b2b30fc2d--- /dev/null+++ b/spree/core/spec/workflows/spree/price_lists/write_spec.rb@@ -0,0 +1,104 @@+require 'spec_helper'++RSpec.describe 'Spree::PriceLists write workflows' do+ let(:store) { @default_store }+ let(:product) { create(:product, store: store) }+ let(:variant) { product.default_variant }++ describe Spree::PriceLists::Create do+ it 'creates the list' do+ result = described_class.call(store: store, attributes: { name: 'Wholesale' })++ expect(result).to be_success+ expect(result.value.name).to eq('Wholesale')+ expect(result.value.status).to eq('draft')+ end++ it 'applies the product membership it was created with' do+ result = described_class.call(+ store: store, attributes: { name: 'Wholesale', product_ids: [product.id] }+ )++ expect(result.value.product_ids).to eq([product.id])+ end++ it 'fails on an invalid list without applying membership' do+ result = described_class.call(store: store, attributes: { product_ids: [product.id] })++ expect(result).not_to be_success+ end+ end++ describe Spree::PriceLists::Update do+ let(:price_list) { create(:price_list, store: store) }++ it 'updates plain attributes' do+ result = described_class.call(price_list: price_list, attributes: { name: 'Renamed' })++ expect(result).to be_success+ expect(price_list.reload.name).to eq('Renamed')+ end++ it 'adds and removes products' do+ other = create(:product, store: store)++ described_class.call(price_list: price_list, attributes: { product_ids: [product.id, other.id] })+ expect(price_list.product_ids).to match_array([product.id, other.id])++ described_class.call(price_list: price_list, attributes: { product_ids: [product.id] })+ expect(price_list.product_ids).to eq([product.id])+ end++ it 'upserts the price overrides it is given' do+ described_class.call(price_list: price_list, attributes: { product_ids: [product.id] })++ described_class.call(+ price_list: price_list,+ attributes: { prices: [{ variant_id: variant.id, currency: 'USD', amount: 5 }] }+ )++ price = price_list.prices.find_by(variant_id: variant.id, currency: 'USD')+ expect(price.amount).to eq(5)+ end++ # An empty array means "clear every override", which is a different+ # instruction from sending no prices at all.+ it 'clears every override when given an empty prices array' do+ described_class.call(price_list: price_list, attributes: { product_ids: [product.id] })+ described_class.call(+ price_list: price_list,+ attributes: { prices: [{ variant_id: variant.id, currency: 'USD', amount: 5 }] }+ )++ described_class.call(price_list: price_list, attributes: { prices: [] })++ expect(price_list.prices.where.not(amount: nil)).to be_empty+ end++ it 'leaves prices alone when the payload carries none' do+ described_class.call(price_list: price_list, attributes: { product_ids: [product.id] })+ described_class.call(+ price_list: price_list,+ attributes: { prices: [{ variant_id: variant.id, currency: 'USD', amount: 5 }] }+ )++ described_class.call(price_list: price_list, attributes: { name: 'Renamed' })++ expect(price_list.prices.find_by(variant_id: variant.id, currency: 'USD').amount).to eq(5)+ end++ context 'hooks' do+ before { Spree.hooks.clear! }+ after { Spree.hooks.clear! }++ it 'can be vetoed before anything is written' do+ Spree.hooks.register('price_lists.update.validate') { |workflow| workflow.reject!('nope') }++ result = described_class.call(price_list: price_list, attributes: { name: 'Renamed' })++ expect(result).not_to be_success+ expect(price_list.reload.name).not_to eq('Renamed')+ end+ end+ end+end