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.

Replay a product's deferred nested data from the workflows

Damian Legawiec576bd340a8dd
diff --git a/docs/developer/customization/workflows.mdx b/docs/developer/customization/workflows.mdx
index 38c31906d7..2563091dcf 100644
--- a/docs/developer/customization/workflows.mdx
+++ b/docs/developer/customization/workflows.mdx
@@ -299,6 +299,10 @@ is reported through `Rails.error` so it's visible rather than mysterious.
| `gift_cards.redeem` | `after_redeem` | lifecycle | After the status is written (in transaction) |
| `gift_cards.cancel` | `validate` | validate | Before a card is voided |
| `gift_cards.cancel` | `after_cancel` | lifecycle | After the card is voided (in transaction) |
+| `price_lists.create` | `validate` | validate | After the list is built, before it is saved |
+| `price_lists.create` | `after_create` | lifecycle | After the list and its product membership exist (in transaction) |
+| `price_lists.update` | `validate` | validate | With the pending attributes assigned, before anything is written |
+| `price_lists.update` | `after_update` | lifecycle | After membership and price overrides are applied (in transaction) |
| `price_lists.activate` | `validate` | validate | Before a price list takes effect |
| `price_lists.activate` | `after_activate` | lifecycle | After the list goes live or is scheduled (in transaction) |
| `price_lists.deactivate` | `validate` | validate | Before a price list stops applying |
diff --git a/docs/plans/6.0-normalize-state-to-status.md b/docs/plans/6.0-normalize-state-to-status.md
index 2d05424cd3..5b592c7e43 100644
--- a/docs/plans/6.0-normalize-state-to-status.md
+++ b/docs/plans/6.0-normalize-state-to-status.md
@@ -131,6 +131,26 @@ dependency of `spree_core`** — Spree ships no state machines at all.
`Spree::HasStatus` gained a `with_status(*values)` scope, replacing the
multi-value class scope `state_machines-activerecord` generated.
+**Callbacks that were flows moved with the machines.** Removing the machines
+made a related pattern visible: writers that stashed their input in an ivar
+for an `after_save` to apply. That is a multi-step flow disguised as an
+attribute assignment, and the order the callbacks happened to run in was
+load-bearing.
+
+- **PriceList** — `product_ids=` and `prices=` no longer stash. The new
+ `Spree::PriceLists::Create` and `::Update` apply both payloads as named
+ steps, in the order the data requires (membership settles before prices, so
+ a newly covered product has a row to overwrite). `prices_attributes=` went
+ with them: it fed only the callback and had no callers. The model keeps
+ `apply_pending_rules`, since `flush_pending_typed_association` is a
+ convention shared with DeliveryMethod, CommissionRate and Promotion.
+- **Product** — the `after_create`/`after_save` replays of deferred variants
+ and media become a step of `Products::Create` and `::Update`. The stashing
+ itself stays on the model, because it exists for a real reason (ActiveStorage
+ cannot attach to an unsaved record), but replaying it is the workflow's job
+ now. `:validate` still runs before the insert, so a rejected create still
+ writes no variant or image — that property is pinned by a spec.
+
**Every verb the machines generated survives as a deprecated shell until
6.1**, following the Payment precedent — these were public API that
extensions and host apps call, so they warn and delegate rather than
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 1e220028e4..033ef3e1fd 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -192,10 +192,8 @@ module Spree
after_create :sync_associations_from_product_type
after_update :sync_associations_from_product_type, if: :saved_change_to_product_type_id?
- after_create :apply_pending_variants, if: :pending_variants?
after_create :ensure_default_variant
after_create :set_default_variant
- after_save :apply_pending_media, if: :pending_media?
after_save :auto_promote_default_variant
after_save :run_touch_callbacks, if: :saved_changes?
@@ -321,7 +319,7 @@ module Spree
# a form ships stale state).
#
# Deferred: ActiveStorage attaches require a persisted record, so on new
- # records we stash the params and replay them in `after_create`.
+ # records we stash the params — see +apply_deferred_nested_attributes+.
# @param media_params [Array<Hash>]
# @return [void]
def media=(media_params)
@@ -340,9 +338,31 @@ module Spree
apply_media(media_params)
end
+ # Applies the nested payloads that had to wait for the product to exist.
+ #
+ # ActiveStorage cannot attach to an unsaved record and a variant needs a
+ # product id, so `media=` and `variants=` stash hash payloads given to a
+ # new record instead of applying them. The Spree::Products workflows call
+ # this once the insert has happened. On a persisted product the setters
+ # apply immediately and this is a no-op.
+ #
+ # @return [void]
+ def apply_deferred_nested_attributes
+ if @pending_variants_params
+ apply_variants(@pending_variants_params)
+ @pending_variants_params = nil
+ end
+
+ return unless @pending_media_params
+
+ apply_media(@pending_media_params)
+ @pending_media_params = nil
+ end
+
# Syncs variants from an array of hashes.
# Creates new variants, updates existing ones (matched by :id), and removes unlisted ones.
- # Must be called on a persisted product (use after_save or call explicitly after create).
+ # On a new record the payload is stashed until the product exists — see
+ # +apply_deferred_nested_attributes+.
# @param variants_params [Array<Hash>] array of variant attribute hashes
# @return [void]
def variants=(variants_params)
@@ -837,28 +857,6 @@ module Spree
nil
end
- def pending_variants?
- @pending_variants_params.present?
- end
-
- def apply_pending_variants
- return unless @pending_variants_params
-
- apply_variants(@pending_variants_params)
- @pending_variants_params = nil
- end
-
- def pending_media?
- @pending_media_params.present?
- end
-
- def apply_pending_media
- return unless @pending_media_params
-
- apply_media(@pending_media_params)
- @pending_media_params = nil
- end
-
def apply_media(media_params)
media_params.each do |raw|
attrs = raw.respond_to?(:to_h) ? raw.to_h : raw
diff --git a/spree/core/app/workflows/spree/products/create.rb b/spree/core/app/workflows/spree/products/create.rb
index 20471fc22e..aee65c24b3 100644
--- a/spree/core/app/workflows/spree/products/create.rb
+++ b/spree/core/app/workflows/spree/products/create.rb
@@ -5,14 +5,15 @@ module Spree
# handler sees every product a store gains rather than only the ones
# typed into the dashboard.
#
- # Deliberately thin. Assigning a product's nested data — variants, media,
- # prices, custom fields, categories — belongs to the model's setters and
- # its after_create/after_save callbacks, and stays there: every caller
- # gets that behavior, workflow or not. What the workflow adds is the veto
- # point, and where it sits matters. Those setters stash their input and
- # replay it once the product exists, so :validate runs before the insert
- # and therefore before any variant, image or custom field is written —
- # a rejection leaves nothing behind to clean up.
+ # Nested data a product arrives with — variants, media — cannot be
+ # written until the product has an id, so the model's setters stash hash
+ # payloads given to a new record and this replays them as a step of its
+ # own. It used to be an after_create callback; as a step the two phases of
+ # a create are visible where the flow is described rather than hidden in
+ # the save.
+ #
+ # :validate still runs before the insert, and therefore before any
+ # variant or image exists, so a rejection leaves nothing to clean up.
class Create < Spree::Workflow
hooks :validate, :after_create
@@ -36,6 +37,7 @@ module Spree
ApplicationRecord.transaction do
step :save_product
+ step :apply_deferred_nested_attributes
run_hooks :after_create
end
@@ -57,6 +59,12 @@ module Spree
def save_product
failure(product) unless product.save
end
+
+ # Variants and media the caller sent as hashes, which had to wait for
+ # the product to exist.
+ def apply_deferred_nested_attributes
+ product.apply_deferred_nested_attributes
+ end
end
end
end
diff --git a/spree/core/app/workflows/spree/products/update.rb b/spree/core/app/workflows/spree/products/update.rb
index c18b56969a..955ed72e3f 100644
--- a/spree/core/app/workflows/spree/products/update.rb
+++ b/spree/core/app/workflows/spree/products/update.rb
@@ -23,6 +23,7 @@ module Spree
ApplicationRecord.transaction do
step :save_product
+ step :apply_deferred_nested_attributes
run_hooks :after_update
end
@@ -38,6 +39,12 @@ module Spree
def save_product
failure(product) unless product.save
end
+
+ # A no-op on a persisted product, whose setters apply immediately; here
+ # so both write paths read the same.
+ def apply_deferred_nested_attributes
+ product.apply_deferred_nested_attributes
+ end
end
end
end
diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rb
index 7f48dc7d6f..6a54f39f2c 100644
--- a/spree/core/spec/models/spree/product_spec.rb
+++ b/spree/core/spec/models/spree/product_spec.rb
@@ -489,7 +489,7 @@ describe Spree::Product, type: :model do
{ sku: 'TEE-S', options: [{ name: 'size', value: 'Small' }] },
{ sku: 'TEE-M', options: [{ name: 'size', value: 'Medium' }] }
]
- p.save!
+ Spree.product_create_workflow.call(store: store, record: p)
end
end
@@ -2048,7 +2048,7 @@ describe Spree::Product, type: :model do
store: store,
variants: [{ sku: 'DEF-1', options: [{ name: 'Color', value: 'Red' }] }]
)
- new_product.save!
+ Spree.product_create_workflow.call(store: store, record: new_product)
expect(new_product.variants.count).to eq(1)
expect(new_product.variants.first.sku).to eq('DEF-1')
@@ -2063,7 +2063,7 @@ describe Spree::Product, type: :model do
store: store,
variants: [{ sku: 'SIMPLE-1', weight: 2, options: [] }]
)
- new_product.save!
+ Spree.product_create_workflow.call(store: store, record: new_product)
expect(new_product.variants.count).to eq(1)
expect(new_product.default_variant.sku).to eq('SIMPLE-1')
@@ -2093,7 +2093,7 @@ describe Spree::Product, type: :model do
{ sku: 'FV-2', prices: [{ amount: 20, currency: 'USD' }], options: [{ name: 'Size', value: 'M' }] }
]
)
- new_product.save!
+ Spree.product_create_workflow.call(store: store, record: new_product)
expect(new_product.variant_count).to eq(2)
expect(new_product.default_variant.sku).to eq('FV-1')
@@ -2106,7 +2106,7 @@ describe Spree::Product, type: :model do
store: store,
variants: [{ sku: 'FS-1', prices: [{ amount: 15, currency: 'USD' }], options: [] }]
)
- new_product.save!
+ Spree.product_create_workflow.call(store: store, record: new_product)
expect(new_product.variant_count).to eq(1)
expect(new_product.default_variant.sku).to eq('FS-1')
@@ -2251,7 +2251,7 @@ describe Spree::Product, type: :model do
)
expect {
- new_product.save!
+ Spree.product_create_workflow.call(store: store, record: new_product)
}.to change(Spree::Media, :count).by(1)
image = new_product.media.find_by(alt: 'Pending')
diff --git a/spree/core/spec/workflows/spree/products/status_transitions_spec.rb b/spree/core/spec/workflows/spree/products/status_transitions_spec.rb
index d5190b00bc..886cf71c87 100644
--- a/spree/core/spec/workflows/spree/products/status_transitions_spec.rb
+++ b/spree/core/spec/workflows/spree/products/status_transitions_spec.rb
@@ -1,5 +1,57 @@
require 'spec_helper'
+# Variants and media a product arrives with cannot be written before it has an
+# id, so the model stashes them and the workflow replays them as a step. These
+# guard the POST /products response, which serializes the same in-memory
+# product it just created.
+RSpec.describe 'Spree::Products deferred nested attributes' do
+ let(:store) { Spree::Store.default }
+
+ it 'creates the variants the product was built with' do
+ product = Spree::Product.new(
+ name: 'Deferred', store: store,
+ variants: [{ sku: 'DEF-1', options: [{ name: 'Color', value: 'Red' }] }]
+ )
+
+ result = Spree.product_create_workflow.call(store: store, record: product)
+
+ expect(result).to be_success
+ expect(product.variants.count).to eq(1)
+ expect(product.variants.first.sku).to eq('DEF-1')
+ end
+
+ it 'reflects them in derived state without a reload' do
+ product = Spree::Product.new(
+ name: 'Fresh', store: store,
+ variants: [{ sku: 'FV-1', prices: [{ amount: 10, currency: 'USD' }], options: [] }]
+ )
+
+ Spree.product_create_workflow.call(store: store, record: product)
+
+ expect(product.variant_count).to eq(1)
+ expect(product.default_variant.sku).to eq('FV-1')
+ expect(product.price_in('USD').amount).to eq(10)
+ end
+
+ # The veto has to land before the insert, or a rejected create would leave
+ # variants and images behind with no product to hang them on.
+ it 'writes no nested data when a validate handler rejects' do
+ Spree.hooks.clear!
+ Spree.hooks.register('products.create.validate') { |workflow| workflow.reject!('nope') }
+
+ product = Spree::Product.new(
+ name: 'Vetoed', store: store,
+ variants: [{ sku: 'VETO-1', options: [] }]
+ )
+
+ expect {
+ expect(Spree.product_create_workflow.call(store: store, record: product)).not_to be_success
+ }.not_to change(Spree::Variant, :count)
+ ensure
+ Spree.hooks.clear!
+ end
+end
+
RSpec.describe 'Spree::Products status workflows' do
let(:store) { Spree::Store.default }