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 product one write path for its variants and media

Damian Legawiec38c60ffa3e12
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.rb
index a773096926..3e379bedc3 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
@@ -232,7 +232,11 @@ module Spree
# Entries with `signed_id` create + attach a fresh upload; an
# external video creates with a URL and no file. Lets the
# dashboard ship media changes alongside the rest of the product
- # form. See `Spree::Product#media=`.
+ # form. See `Spree::Products::NestedAttributes`.
+ #
+ # `external_url` is deliberately not permitted here: it makes the
+ # server fetch a URL the caller chose, so it belongs to trusted
+ # importers rather than to a request body.
media: [*Spree::Media::WRITABLE_ATTRIBUTES, :id, :signed_id, { variant_ids: [] }],
product_publications: [:id, :channel_id, :published_at, :unpublished_at],
variants: [
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 033ef3e1fd..f36bbe1498 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -312,71 +312,6 @@ module Spree
super(manual_ids | collections.automatic.ids)
end
- # Sync media inline. Entries with `id` patch the existing asset
- # (alt/position/variant_ids); entries with `signed_id` create + attach a
- # fresh upload; missing items are left alone (delete still goes through
- # the dedicated DELETE /media endpoint to avoid accidental data loss when
- # a form ships stale state).
- #
- # Deferred: ActiveStorage attaches require a persisted record, so on new
- # records we stash the params — see +apply_deferred_nested_attributes+.
- # @param media_params [Array<Hash>]
- # @return [void]
- def media=(media_params)
- # Blank input is a no-op — never call `super` with an empty array,
- # because the ActiveRecord collection setter would replace media with
- # `[]` and trigger `dependent: :destroy` on every persisted asset.
- # Explicit deletes go through the dedicated DELETE /media endpoint.
- return if media_params.blank?
- return super if media_params.first.is_a?(Spree::Media)
-
- if new_record?
- @pending_media_params = media_params
- return
- end
-
- 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.
- # 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)
- return super if variants_params.blank? || variants_params.first.is_a?(Spree::Variant)
-
- # Store for deferred processing if product is not yet persisted
- if new_record?
- @pending_variants_params = variants_params
- return
- end
-
- apply_variants(variants_params)
- end
-
self.whitelisted_ransackable_attributes = %w[description name slug discontinue_on status available_on created_at updated_at seller_id]
self.whitelisted_ransackable_associations = %w[categories collections store channels variants default_variant tags labels
product_type product_categories option_types seller]
@@ -857,102 +792,6 @@ module Spree
nil
end
- def apply_media(media_params)
- media_params.each do |raw|
- attrs = raw.respond_to?(:to_h) ? raw.to_h : raw
- attrs = attrs.with_indifferent_access
-
- # Upsert path: entries with an `id` patch an existing asset (alt,
- # position, variant_ids, focal point, video URL). Entries with a
- # `signed_id` create+attach; external videos create with neither.
- # Omitting an entry leaves it alone — explicit DELETE on the dedicated
- # media endpoint is still the only way to remove an asset.
- asset_id = attrs.delete(:id)
- if asset_id.present?
- asset = media.find_by_param(asset_id) || next
- asset.update!(attrs.except(:signed_id))
- next
- end
-
- signed_id = attrs.delete(:signed_id)
- # An external video carries a URL instead of a file, so it's the one
- # kind of new row that legitimately arrives without a signed id.
- next if signed_id.blank? && attrs[:media_type] != 'external_video'
-
- asset = media.build(attrs.except(:id))
- asset.attachment.attach(signed_id) if signed_id.present?
- asset.save!
- end
- end
-
- def apply_variants(variants_params)
- variant_ids_in_payload = []
- mutated = false
-
- variants_params.each do |variant_data|
- variant_data = variant_data.to_h.with_indifferent_access
- variant_id = variant_data.delete(:id)
-
- variant =
- if variant_id.present?
- variants.find_by_param!(variant_id)
- elsif reuse_default_variant_for?(variant_data, variant_ids_in_payload)
- # An id-less, option-less entry targets the product's existing
- # option-less default variant (the simple-product case) — update it in
- # place rather than building a new row, so its id, order-line
- # references, and unspecified prices/stock survive.
- default_variant
- else
- variants.build
- end
-
- variant.assign_attributes(variant_data)
- variant.save!
-
- variant_ids_in_payload << variant.id
- mutated = true
- end
-
- # Full replacement: variants not in the payload are removed. The payload
- # is the writer's whole intent, and this write path is the operator's —
- # who sees and writes every seller's variants on a master product, so
- # nothing here narrows by seller. A seller's own write path (the seller
- # branch, Phase 3) scope-fetches through `current_seller` at the
- # controller, per docs/plans/6.0-multi-vendor-marketplace.md Decision 10;
- # it never reaches this method with a payload naming another seller's rows.
- if variant_ids_in_payload.any?
- removed = variants.where.not(id: variant_ids_in_payload).destroy_all
- mutated ||= removed.any?
- end
-
- sync_variant_state! if mutated
- end
-
- # True when an id-less variant payload should update the product's existing
- # option-less default variant instead of building a new one: the entry carries
- # no options, a default variant exists and is itself option-less, and it hasn't
- # already been claimed by an earlier entry in this payload.
- def reuse_default_variant_for?(variant_data, consumed_ids)
- variant_data[:options].blank? &&
- variant_data[:option_value_variants_attributes].blank? &&
- default_variant.present? &&
- default_variant.option_values.empty? &&
- consumed_ids.exclude?(default_variant.id)
- end
-
- # Re-syncs the in-memory derived variant state after `apply_variants`
- # mutates variants out-of-band. `variant_count` is bumped via
- # `Spree::Product.increment_counter` in a Variant callback, so the in-memory
- # attribute is stale; the `default_variant` association is also cached.
- # Without this, a freshly built/updated product serialized in the same
- # request returns a stale `variant_count` and `price`.
- # @return [void]
- def sync_variant_state!
- self[:variant_count] = self.class.where(id: id).pick(:variant_count)
- variants.reset
- association(:default_variant).reset
- end
-
# Additive, unlike the legacy prototype callback which replaced both sets —
# the type seeds the product when attached (creation, later assignment,
# reassignment) and never removes anything; detaching seeds nothing.
diff --git a/spree/core/app/workflows/spree/products/create.rb b/spree/core/app/workflows/spree/products/create.rb
index aee65c24b3..92eaa3d6e8 100644
--- a/spree/core/app/workflows/spree/products/create.rb
+++ b/spree/core/app/workflows/spree/products/create.rb
@@ -5,16 +5,16 @@ module Spree
# handler sees every product a store gains rather than only the ones
# typed into the dashboard.
#
- # 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.
+ # Nested data — variants and media — is applied here rather than by the
+ # model, because it cannot be written until the product has an id and
+ # because it is a reconciliation, not an assignment: the payload is the
+ # writer's whole intent and variants missing from it are removed.
#
- # :validate still runs before the insert, and therefore before any
- # variant or image exists, so a rejection leaves nothing to clean up.
+ # :validate runs before the insert, and therefore before any variant or
+ # image exists, so a rejection leaves nothing to clean up.
class Create < Spree::Workflow
+ include Spree::Products::NestedAttributes
+
hooks :validate, :after_create
# The unsaved record a :validate handler reads (with its `changes`).
@@ -37,7 +37,7 @@ module Spree
ApplicationRecord.transaction do
step :save_product
- step :apply_deferred_nested_attributes
+ step :apply_nested_attributes
run_hooks :after_create
end
@@ -53,17 +53,22 @@ module Spree
# against the wrong tenant, and every :validate handler reading
# `store` would be told the wrong thing.
@product.store = store
- @product.assign_attributes(attributes) if attributes.present?
+ return if attributes.blank?
+
+ # Held back from the record: these are reconciled after the insert,
+ # against a product that has an id.
+ @variants_params = attributes[:variants]
+ @media_params = attributes[:media]
+ @product.assign_attributes(attributes.except(:variants, :media))
end
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
+ def apply_nested_attributes
+ apply_variants(product, @variants_params)
+ apply_media(product, @media_params)
end
end
end
diff --git a/spree/core/app/workflows/spree/products/nested_attributes.rb b/spree/core/app/workflows/spree/products/nested_attributes.rb
new file mode 100644
index 0000000000..90264a5fd3
--- /dev/null
+++ b/spree/core/app/workflows/spree/products/nested_attributes.rb
@@ -0,0 +1,136 @@
+module Spree
+ module Products
+ # Applies the nested data a product write can carry: its variants and its
+ # media. Shared by Spree::Products::Create and ::Update so both write paths
+ # — and any host importing from an external system — reconcile them the
+ # same way.
+ #
+ # Both are full replacements. The payload is the writer's whole intent, so
+ # a variant absent from it is removed, and this is the operator's write
+ # path: it sees and writes every seller's variants on a shared listing, so
+ # nothing here narrows by seller. A seller's own path scope-fetches through
+ # `current_seller` at the controller
+ # (docs/plans/6.0-multi-vendor-marketplace.md, Decision 10) and never
+ # reaches here with a payload naming another seller's rows.
+ module NestedAttributes
+ extend ActiveSupport::Concern
+
+ private
+
+ # @param product [Spree::Product]
+ # @param variants_params [Array<Hash>, nil] nil leaves variants alone
+ # @return [void]
+ def apply_variants(product, variants_params)
+ return if variants_params.blank?
+
+ variant_ids_in_payload = []
+ mutated = false
+
+ variants_params.each do |raw|
+ 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_ids_in_payload << variant.id
+ mutated = true
+ end
+
+ if variant_ids_in_payload.any?
+ removed = product.variants.where.not(id: variant_ids_in_payload).destroy_all
+ mutated ||= removed.any?
+ end
+
+ sync_variant_state(product) if mutated
+ end
+
+ def resolve_variant(product, variant_data, variant_id, consumed_ids)
+ return product.variants.find_by_param!(variant_id) if variant_id.present?
+
+ # An id-less, option-less entry targets the product's existing
+ # 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
+ end
+
+ def reuse_default_variant?(product, variant_data, consumed_ids)
+ variant_data[:options].blank? &&
+ variant_data[:option_value_variants_attributes].blank? &&
+ product.default_variant.present? &&
+ product.default_variant.option_values.empty? &&
+ consumed_ids.exclude?(product.default_variant.id)
+ end
+
+ # variant_count is bumped by a counter cache in a Variant callback and the
+ # default_variant association is cached, so both are stale after writing
+ # variants out of band. Without this a product serialized in the same
+ # request reports the count and price it had before the write.
+ def sync_variant_state(product)
+ product[:variant_count] = product.class.where(id: product.id).pick(:variant_count)
+ product.variants.reset
+ product.association(:default_variant).reset
+ end
+
+ # Media entries come in four kinds: an `id` patches an existing asset, a
+ # `signed_id` attaches an already-uploaded blob, an `external_url` hands
+ # the fetch to a background job, and an external video carries a URL
+ # instead of a file. Omitting an entry leaves it alone — removal is the
+ # dedicated DELETE endpoint's job, so a form shipping stale state cannot
+ # destroy a merchant's images.
+ #
+ # @param product [Spree::Product]
+ # @param media_params [Array<Hash>, nil]
+ # @return [void]
+ def apply_media(product, media_params)
+ return if media_params.blank?
+
+ media_params.each do |raw|
+ attrs = (raw.respond_to?(:to_h) ? raw.to_h : raw).with_indifferent_access
+
+ asset_id = attrs.delete(:id)
+ if asset_id.present?
+ asset = product.media.find_by_param(asset_id) || next
+ asset.update!(attrs.except(:signed_id, :external_url))
+ next
+ end
+
+ external_url = attrs.delete(:external_url)
+ next enqueue_media_download(product, external_url, attrs) if external_url.present?
+
+ signed_id = attrs.delete(:signed_id)
+ next if signed_id.blank? && attrs[:media_type] != 'external_video'
+
+ asset = product.media.build(attrs)
+ asset.attachment.attach(signed_id) if signed_id.present?
+ asset.save!
+ end
+ end
+
+ # Downloading is a job rather than a step: it reaches out over the
+ # network, and the job already owns the parts that makes necessary —
+ # SSRF filtering, a size cap, and skipping a URL this product has
+ # already fetched.
+ #
+ # The asset is always attached to the product so one file is not
+ # downloaded once per variant; `variant_id` links the resulting asset to
+ # a variant afterwards.
+ def enqueue_media_download(product, external_url, attrs)
+ Spree::Images::SaveFromUrlJob.perform_later(
+ product.id,
+ 'Spree::Product',
+ external_url,
+ attrs[:external_id],
+ attrs[:position],
+ attrs[:variant_id]
+ )
+ 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 955ed72e3f..9ab21cd4fb 100644
--- a/spree/core/app/workflows/spree/products/update.rb
+++ b/spree/core/app/workflows/spree/products/update.rb
@@ -1,12 +1,15 @@
module Spree
module Products
- # Updates a product. Nested data is assigned by the model's own setters
- # (see Spree::Products::Create); this exists for the veto point.
+ # Updates a product, reconciling the variants and media the payload
+ # carries (see Spree::Products::NestedAttributes — both are full
+ # replacements).
#
# Handlers reading `product.changes` in :validate see the pending edit
# before it is written, which is what makes rules like "price may not
# drop below cost" expressible without a model validation.
class Update < Spree::Workflow
+ include Spree::Products::NestedAttributes
+
hooks :validate, :after_update
# `product` — the record with the pending attributes assigned, so a
@@ -23,7 +26,7 @@ module Spree
ApplicationRecord.transaction do
step :save_product
- step :apply_deferred_nested_attributes
+ step :apply_nested_attributes
run_hooks :after_update
end
@@ -33,17 +36,21 @@ module Spree
private
def assign_attributes
- product.assign_attributes(attributes)
+ # Held back: variants and media are reconciled after the save, so a
+ # :validate handler reads `product.changes` describing the edit itself
+ # rather than a half-applied collection.
+ @variants_params = attributes[:variants]
+ @media_params = attributes[:media]
+ product.assign_attributes(attributes.except(:variants, :media))
end
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
+ def apply_nested_attributes
+ apply_variants(product, @variants_params)
+ apply_media(product, @media_params)
end
end
end
diff --git a/spree/core/spec/models/spree/product/shared_catalog_spec.rb b/spree/core/spec/models/spree/product/shared_catalog_spec.rb
index c305f40a92..c7ec960310 100644
--- a/spree/core/spec/models/spree/product/shared_catalog_spec.rb
+++ b/spree/core/spec/models/spree/product/shared_catalog_spec.rb
@@ -8,7 +8,7 @@ describe Spree::Product, type: :model do
let(:seller) { create(:seller, :approved, store: store) }
let(:other_seller) { create(:seller, :approved, store: store) }
- describe '#variants= on a master product' do
+ describe 'nested variants on a master product' do
let(:product) { create(:product, store: store) }
let!(:mine) { create(:variant, product: product, seller: seller, sku: 'MINE-1') }
let!(:theirs) { create(:variant, product: product, seller: other_seller, sku: 'THEIRS-1') }
@@ -18,7 +18,9 @@ describe Spree::Product, type: :model do
# on purpose; a seller's own writes go through the seller branch, which
# scope-fetches at the controller (Decision 10).
it 'lets the operator edit and remove any seller\'s variant' do
- product.variants = [{ id: mine.prefixed_id, sku: 'MINE-2' }]
+ Spree.product_update_workflow.call(
+ product: product, attributes: { variants: [{ id: mine.prefixed_id, sku: 'MINE-2' }] }
+ )
expect(mine.reload.sku).to eq('MINE-2')
expect(product.variants.reload).not_to include(theirs)
diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rb
index 6a54f39f2c..041ad402b6 100644
--- a/spree/core/spec/models/spree/product_spec.rb
+++ b/spree/core/spec/models/spree/product_spec.rb
@@ -484,13 +484,16 @@ describe Spree::Product, type: :model do
context 'a product supplied with nested variants' do
let(:product) do
- build(:empty_product).tap do |p|
- p.variants = [
- { sku: 'TEE-S', options: [{ name: 'size', value: 'Small' }] },
- { sku: 'TEE-M', options: [{ name: 'size', value: 'Medium' }] }
- ]
- Spree.product_create_workflow.call(store: store, record: p)
- end
+ Spree.product_create_workflow.call(
+ store: store,
+ attributes: {
+ name: 'Tee',
+ variants: [
+ { sku: 'TEE-S', options: [{ name: 'size', value: 'Small' }] },
+ { sku: 'TEE-M', options: [{ name: 'size', value: 'Medium' }] }
+ ]
+ }
+ ).value
end
it 'creates exactly the supplied variants — no phantom default' do
@@ -610,7 +613,7 @@ describe Spree::Product, type: :model do
context 'with an id-less, option-less entry (simple-product update)' do
it 'updates the existing default variant in place instead of replacing it' do
- product.variants = [{ sku: 'UPDATED-SKU' }]
+ Spree.product_update_workflow.call(product: product, attributes: { variants: [{ sku: 'UPDATED-SKU' }] })
product.reload
# The original variant is upserted — same row, not replaced — so its id
@@ -623,7 +626,7 @@ describe Spree::Product, type: :model do
context 'with an option-bearing entry' do
it 'builds a new variant and drops the option-less placeholder' do
- product.variants = [{ sku: 'TEE-S', options: [{ name: 'size', value: 'Small' }] }]
+ Spree.product_update_workflow.call(product: product, attributes: { variants: [{ sku: 'TEE-S', options: [{ name: 'size', value: 'Small' }] }] })
product.reload
expect(product.variants.pluck(:sku)).to contain_exactly('TEE-S')
@@ -2011,15 +2014,15 @@ describe Spree::Product, type: :model do
end
end
- describe '#variants=' do
+ describe 'nested variants' do
let(:product) { create(:product) }
context 'with hash params' do
it 'creates new variants' do
- product.variants = [
+ Spree.product_update_workflow.call(product: product, attributes: { variants: [
{ sku: 'V1', prices: [{ amount: 10, currency: 'USD' }], options: [{ name: 'Size', value: 'S' }] },
{ sku: 'V2', prices: [{ amount: 20, currency: 'USD' }], options: [{ name: 'Size', value: 'M' }] }
- ]
+ ] })
expect(product.variants.count).to eq(2)
expect(product.variants.pluck(:sku)).to match_array(%w[V1 V2])
@@ -2027,7 +2030,7 @@ describe Spree::Product, type: :model do
it 'updates existing variants by prefixed id' do
variant = create(:variant, product: product)
- product.variants = [{ id: variant.prefixed_id, sku: 'UPDATED' }]
+ Spree.product_update_workflow.call(product: product, attributes: { variants: [{ id: variant.prefixed_id, sku: 'UPDATED' }] })
expect(variant.reload.sku).to eq('UPDATED')
end
@@ -2036,19 +2039,17 @@ describe Spree::Product, type: :model do
v1 = create(:variant, product: product)
v2 = create(:variant, product: product)
- product.variants = [{ id: v1.prefixed_id, sku: v1.sku }]
+ Spree.product_update_workflow.call(product: product, attributes: { variants: [{ id: v1.prefixed_id, sku: v1.sku }] })
expect(product.variants.reload).to include(v1)
expect(product.variants).not_to include(v2)
end
it 'defers creation on new records' do
- new_product = Spree::Product.new(
- name: 'Deferred',
+ new_product = Spree.product_create_workflow.call(
store: store,
- variants: [{ sku: 'DEF-1', options: [{ name: 'Color', value: 'Red' }] }]
- )
- Spree.product_create_workflow.call(store: store, record: new_product)
+ attributes: { name: 'Deferred', variants: [{ sku: 'DEF-1', options: [{ name: 'Color', value: 'Red' }] }] }
+ ).value
expect(new_product.variants.count).to eq(1)
expect(new_product.variants.first.sku).to eq('DEF-1')
@@ -2058,12 +2059,10 @@ describe Spree::Product, type: :model do
# Simple-product flow: the merchant edits SKU + weight on the default
# variant without adding options. The payload ships a single variant
# with options:[] and the backend creates exactly that one variant.
- new_product = Spree::Product.new(
- name: 'Simple SKU',
+ new_product = Spree.product_create_workflow.call(
store: store,
- variants: [{ sku: 'SIMPLE-1', weight: 2, options: [] }]
- )
- Spree.product_create_workflow.call(store: store, record: new_product)
+ attributes: { name: 'Simple SKU', variants: [{ sku: 'SIMPLE-1', weight: 2, options: [] }] }
+ ).value
expect(new_product.variants.count).to eq(1)
expect(new_product.default_variant.sku).to eq('SIMPLE-1')
@@ -2085,15 +2084,16 @@ describe Spree::Product, type: :model do
# same in-memory product it just saved.
context 'in-memory derived state after build + save (no reload)' do
it 'reflects new option-bearing variants in variant_count and default_variant' do
- new_product = Spree::Product.new(
- name: 'Fresh Variants',
+ new_product = Spree.product_create_workflow.call(
store: store,
- variants: [
- { sku: 'FV-1', prices: [{ amount: 10, currency: 'USD' }], options: [{ name: 'Size', value: 'S' }] },
- { sku: 'FV-2', prices: [{ amount: 20, currency: 'USD' }], options: [{ name: 'Size', value: 'M' }] }
- ]
- )
- Spree.product_create_workflow.call(store: store, record: new_product)
+ attributes: {
+ name: 'Fresh Variants',
+ variants: [
+ { sku: 'FV-1', prices: [{ amount: 10, currency: 'USD' }], options: [{ name: 'Size', value: 'S' }] },
+ { sku: 'FV-2', prices: [{ amount: 20, currency: 'USD' }], options: [{ name: 'Size', value: 'M' }] }
+ ]
+ }
+ ).value
expect(new_product.variant_count).to eq(2)
expect(new_product.default_variant.sku).to eq('FV-1')
@@ -2101,12 +2101,10 @@ describe Spree::Product, type: :model do
end
it 'reflects an options-less default variant in default_variant and price' do
- new_product = Spree::Product.new(
- name: 'Fresh Simple',
+ new_product = Spree.product_create_workflow.call(
store: store,
- variants: [{ sku: 'FS-1', prices: [{ amount: 15, currency: 'USD' }], options: [] }]
- )
- Spree.product_create_workflow.call(store: store, record: new_product)
+ attributes: { name: 'Fresh Simple', variants: [{ sku: 'FS-1', prices: [{ amount: 15, currency: 'USD' }], options: [] }] }
+ ).value
expect(new_product.variant_count).to eq(1)
expect(new_product.default_variant.sku).to eq('FS-1')
@@ -2115,7 +2113,7 @@ describe Spree::Product, type: :model do
end
end
- describe '#media=' do
+ describe 'nested media' do
let(:product) { create(:product) }
let(:fixture_path) { File.expand_path('../../fixtures/thinking-cat.jpg', __dir__) }
let(:blob) do
@@ -2129,7 +2127,7 @@ describe Spree::Product, type: :model do
context 'on a persisted record' do
it 'attaches a new media item from a signed_id' do
expect {
- product.media = [{ signed_id: blob.signed_id, alt: 'A cat', position: 1 }]
+ Spree.product_update_workflow.call(product: product, attributes: { media: [{ signed_id: blob.signed_id, alt: 'A cat', position: 1 }] })
}.to change(product.media, :count).by(1)
image = product.media.find_by(alt: 'A cat')
@@ -2144,7 +2142,7 @@ describe Spree::Product, type: :model do
existing.attachment.attach(io: File.open(fixture_path), filename: 'cat.jpg', content_type: 'image/jpeg')
existing.save!
- product.media = [{ id: existing.prefixed_id, alt: 'New alt', position: 5 }]
+ Spree.product_update_workflow.call(product: product, attributes: { media: [{ id: existing.prefixed_id, alt: 'New alt', position: 5 }] })
expect(existing.reload.alt).to eq('New alt')
expect(existing.position).to eq(5)
@@ -2158,22 +2156,22 @@ describe Spree::Product, type: :model do
variant = create(:variant, product: product)
product.reload # refresh the variants cache so the out-of-band variant resolves
- product.media = [{ id: existing.prefixed_id, variant_ids: [variant.id] }]
+ Spree.product_update_workflow.call(product: product, attributes: { media: [{ id: existing.prefixed_id, variant_ids: [variant.id] }] })
expect(existing.reload.variants).to include(variant)
end
it 'rejects an unknown media type' do
expect {
- product.media = [{ signed_id: blob.signed_id, media_type: 'audio' }]
+ Spree.product_update_workflow.call(product: product, attributes: { media: [{ signed_id: blob.signed_id, media_type: 'audio' }] })
}.to raise_error(ActiveRecord::RecordInvalid)
end
it 'adds an external video without a file' do
expect {
- product.media = [
+ Spree.product_update_workflow.call(product: product, attributes: { media: [
{ media_type: 'external_video', external_video_url: 'https://vimeo.com/123456789', position: 1 }
- ]
+ ] })
}.to change(product.media, :count).by(1)
video = product.media.find_by(media_type: 'external_video')
@@ -2183,9 +2181,9 @@ describe Spree::Product, type: :model do
it 'rejects an external video Spree cannot embed' do
expect {
- product.media = [
+ Spree.product_update_workflow.call(product: product, attributes: { media: [
{ media_type: 'external_video', external_video_url: 'https://example.com/clip.mp4' }
- ]
+ ] })
}.to raise_error(ActiveRecord::RecordInvalid)
end
@@ -2194,13 +2192,13 @@ describe Spree::Product, type: :model do
io: File.open(fixture_path), filename: 'poster.jpg', content_type: 'image/jpeg'
)
- product.media = [
+ Spree.product_update_workflow.call(product: product, attributes: { media: [
{
media_type: 'external_video',
external_video_url: 'https://vimeo.com/123456789',
poster_signed_id: poster.signed_id
}
- ]
+ ] })
video = product.media.find_by(media_type: 'external_video')
expect(video.poster).to be_attached
@@ -2212,20 +2210,20 @@ describe Spree::Product, type: :model do
existing.attachment.attach(io: File.open(fixture_path), filename: 'cat.jpg', content_type: 'image/jpeg')
existing.save!
- product.media = [{ id: existing.prefixed_id, focal_point_x: 0.25, focal_point_y: 0.75 }]
+ Spree.product_update_workflow.call(product: product, attributes: { media: [{ id: existing.prefixed_id, focal_point_x: 0.25, focal_point_y: 0.75 }] })
expect(existing.reload.focal_point).to eq({ x: 0.25, y: 0.75 })
end
it 'silently skips entries with neither id nor signed_id' do
expect {
- product.media = [{ alt: 'nothing-to-attach' }]
+ Spree.product_update_workflow.call(product: product, attributes: { media: [{ alt: 'nothing-to-attach' }] })
}.not_to change(product.media, :count)
end
it 'silently skips id entries that do not match an existing media item' do
expect {
- product.media = [{ id: 'asset_doesnotexist', alt: 'ignored' }]
+ Spree.product_update_workflow.call(product: product, attributes: { media: [{ id: 'asset_doesnotexist', alt: 'ignored' }] })
}.not_to change(product.media, :count)
end
@@ -2235,7 +2233,7 @@ describe Spree::Product, type: :model do
existing.save!
expect {
- product.media = [{ signed_id: blob.signed_id, alt: 'New entry', position: 2 }]
+ Spree.product_update_workflow.call(product: product, attributes: { media: [{ signed_id: blob.signed_id, alt: 'New entry', position: 2 }] })
}.to change(product.media, :count).by(1)
expect(product.media.find_by(id: existing.id)).to be_present
@@ -2244,14 +2242,13 @@ describe Spree::Product, type: :model do
context 'on a new record' do
it 'defers attachment until after the product is saved' do
- new_product = Spree::Product.new(
- name: 'Deferred Media',
- store: store,
- media: [{ signed_id: blob.signed_id, alt: 'Pending', position: 1 }]
- )
+ new_product = nil
expect {
- Spree.product_create_workflow.call(store: store, record: new_product)
+ new_product = Spree.product_create_workflow.call(
+ store: store,
+ attributes: { name: 'Deferred Media', media: [{ signed_id: blob.signed_id, alt: 'Pending', position: 1 }] }
+ ).value
}.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 886cf71c87..1105343524 100644
--- a/spree/core/spec/workflows/spree/products/status_transitions_spec.rb
+++ b/spree/core/spec/workflows/spree/products/status_transitions_spec.rb
@@ -1,32 +1,35 @@
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
+# Variants and media are reconciled by the workflow, not by the model: the
+# payload is the writer's whole intent, so it is a replacement rather than an
+# assignment. These guard the POST /products response, which serializes the
+# same in-memory product it just created.
+RSpec.describe 'Spree::Products 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' }] }]
+ it 'creates the variants the payload carries' do
+ result = Spree.product_create_workflow.call(
+ store: store,
+ attributes: {
+ name: 'Deferred',
+ 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')
+ expect(result.value.variants.count).to eq(1)
+ expect(result.value.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: [] }]
+ result = Spree.product_create_workflow.call(
+ store: store,
+ attributes: {
+ name: 'Fresh',
+ variants: [{ sku: 'FV-1', prices: [{ amount: 10, currency: 'USD' }], options: [] }]
+ }
)
-
- Spree.product_create_workflow.call(store: store, record: product)
+ product = result.value
expect(product.variant_count).to eq(1)
expect(product.default_variant.sku).to eq('FV-1')
@@ -39,17 +42,27 @@ RSpec.describe 'Spree::Products deferred nested attributes' 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
+ result = Spree.product_create_workflow.call(
+ store: store,
+ attributes: { name: 'Vetoed', variants: [{ sku: 'VETO-1', options: [] }] }
+ )
+ expect(result).not_to be_success
}.not_to change(Spree::Variant, :count)
ensure
Spree.hooks.clear!
end
+
+ it 'enqueues a download for media given as an external url' do
+ product = create(:product, store: store)
+
+ expect {
+ Spree.product_update_workflow.call(
+ product: product,
+ attributes: { media: [{ external_url: 'https://example.com/a.jpg', position: 1 }] }
+ )
+ }.to have_enqueued_job(Spree::Images::SaveFromUrlJob)
+ end
end
RSpec.describe 'Spree::Products status workflows' do