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.

Fix product_publications API writer: idempotent upsert, empty-array detach

Damian Legawiec393a7d783248
diff --git a/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb b/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb
index 4421a3d96a..9118cd99dd 100644
--- a/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb
+++ b/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb
@@ -3,7 +3,7 @@
packages/dashboard/src/components/spree/products/publishing-card.tsx.
All channel attach/detach AND per-channel scheduling submit through the
- same nested-attributes form (+product_publications_attributes+). Each row
+ same nested-attributes form (+legacy_product_publications_attributes+). Each row
in the Manage panel toggles the +_destroy+ flag on the corresponding
publication; unchecked rows for unattached channels send blank attrs that
the model's +reject_if+ discards.
@@ -50,7 +50,7 @@
<div class="d-none flex flex-col gap-2 mb-3" data-product-publishing-target="manage">
<p class="text-xs text-muted mb-1"><%= Spree.t('admin.publishing.manage_description') %></p>
<% channel_rows.each_with_index do |(channel, publication), index| %>
- <%= f.fields_for :product_publications, publication, child_index: index do |pf| %>
+ <%= f.fields_for :legacy_product_publications, publication, child_index: index do |pf| %>
<%= pf.hidden_field :id if publication.persisted? %>
<%= pf.hidden_field :channel_id, value: channel.id %>
<% checked_by_default = publication.persisted? || (@product.new_record? && channel.default?) %>
@@ -80,7 +80,7 @@
<% else %>
<% channel_rows.each_with_index do |(channel, publication), index| %>
<% next unless publication.persisted? %>
- <%= f.fields_for :product_publications, publication, child_index: index do |pf| %>
+ <%= f.fields_for :legacy_product_publications, publication, child_index: index do |pf| %>
<details class="publication-row group rounded -mx-2 px-2 hover:bg-gray-50">
<summary class="flex items-start justify-between gap-3 py-2 cursor-pointer" style="list-style: none;">
<div class="flex min-w-0 flex-1 flex-col gap-0.5">
diff --git a/spree/admin/spec/controllers/spree/admin/products_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/products_controller_spec.rb
index c026f05ae7..d5b3f348f2 100644
--- a/spree/admin/spec/controllers/spree/admin/products_controller_spec.rb
+++ b/spree/admin/spec/controllers/spree/admin/products_controller_spec.rb
@@ -1172,7 +1172,7 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
end
end
- describe 'publishing card (product_publications_attributes)' do
+ describe 'publishing card (legacy_product_publications_attributes)' do
let!(:pos_channel) { create(:channel, store: store, name: 'POS', code: 'pos') }
let!(:wholesale_channel) { create(:channel, store: store, name: 'Wholesale', code: 'wholesale') }
let(:default_channel) { store.default_channel }
@@ -1181,7 +1181,7 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
let(:product_params) do
{
- product_publications_attributes: {
+ legacy_product_publications_attributes: {
'0' => { id: default_publication.id, channel_id: default_channel.id, _destroy: '0', published_at: '', unpublished_at: '' },
'1' => { id: '', channel_id: pos_channel.id, _destroy: '0', published_at: '', unpublished_at: '' },
'2' => { id: wholesale_publication.id, channel_id: wholesale_channel.id, _destroy: '1', published_at: '', unpublished_at: '' }
@@ -1198,19 +1198,21 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
end
it 'persists the published_at window on an existing publication' do
- future = 2.days.from_now.change(usec: 0)
- product_params[:product_publications_attributes]['0'][:published_at] = future.iso8601
+ Timecop.freeze do
+ future = 2.days.from_now.change(usec: 0)
+ product_params[:legacy_product_publications_attributes]['0'][:published_at] = future.iso8601
- send_request
+ send_request
- expect(default_publication.reload.published_at).to be_within(1.second).of(future)
+ expect(default_publication.reload.published_at).to be_within(1.second).of(future)
+ end
end
it 'is idempotent when no publications change' do
# Re-submit exactly the current state — both publications kept, no
# new attach, no detach.
- product_params[:product_publications_attributes]['2'][:_destroy] = '0'
- product_params[:product_publications_attributes].delete('1')
+ product_params[:legacy_product_publications_attributes]['2'][:_destroy] = '0'
+ product_params[:legacy_product_publications_attributes].delete('1')
expect { send_request }
.not_to change { product.product_publications.reload.pluck(:channel_id).sort }
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
index defbe17481..2161dfc682 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
@@ -515,6 +515,82 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
end
end
+ context 'with product_publications' do
+ let!(:pos_channel) { create(:channel, store: store, code: 'pos', name: 'POS') }
+ let!(:wholesale_channel) { create(:channel, store: store, code: 'wholesale', name: 'Wholesale') }
+ let(:default_channel) { store.default_channel }
+ let!(:existing_publication) do
+ product.product_publications.find_by(channel: default_channel) ||
+ product.product_publications.create!(channel: default_channel)
+ end
+
+ it 'attaches a new channel via product_publications' do
+ patch :update, params: {
+ id: product.prefixed_id,
+ product_publications: [
+ { channel_id: default_channel.prefixed_id },
+ { channel_id: pos_channel.prefixed_id }
+ ]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(product.reload.channels).to contain_exactly(default_channel, pos_channel)
+ end
+
+ it 'is idempotent when re-submitting an existing channel by channel_id' do
+ patch :update, params: {
+ id: product.prefixed_id,
+ product_publications: [{ channel_id: default_channel.prefixed_id }]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(product.reload.product_publications.where(channel_id: default_channel.id).pluck(:id))
+ .to eq([existing_publication.id])
+ end
+
+ it 'detaches every channel when given an empty array' do
+ product.product_publications.create!(channel: pos_channel)
+
+ patch :update, params: {
+ id: product.prefixed_id,
+ product_publications: []
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(product.reload.product_publications).to be_empty
+ end
+
+ it 'persists the published_at window submitted with the channel' do
+ Timecop.freeze do
+ future = 2.days.from_now.change(usec: 0)
+
+ patch :update, params: {
+ id: product.prefixed_id,
+ product_publications: [
+ { channel_id: default_channel.prefixed_id, published_at: future.iso8601 },
+ { channel_id: wholesale_channel.prefixed_id }
+ ]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ publication = product.reload.product_publications.find_by(channel: default_channel)
+ expect(publication.published_at).to be_within(1.second).of(future)
+ end
+ end
+
+ it 'removes channels absent from the payload' do
+ product.product_publications.create!(channel: pos_channel)
+
+ patch :update, params: {
+ id: product.prefixed_id,
+ product_publications: [{ channel_id: default_channel.prefixed_id }]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(product.reload.channels).to contain_exactly(default_channel)
+ end
+ end
+
context 'with invalid params' do
it 'returns validation errors' do
patch :update, params: { id: product.prefixed_id, name: '' }, as: :json
diff --git a/spree/core/app/models/spree/product/channels.rb b/spree/core/app/models/spree/product/channels.rb
index 1467936abb..c469bdad0c 100644
--- a/spree/core/app/models/spree/product/channels.rb
+++ b/spree/core/app/models/spree/product/channels.rb
@@ -16,11 +16,14 @@ module Spree
has_many :product_publications, class_name: 'Spree::ProductPublication', autosave: true
has_many :channels, -> { distinct }, through: :product_publications, class_name: 'Spree::Channel'
- # +accepts_nested_attributes_for+ enables the legacy Rails admin form
- # to submit publication windows via +product_publications_attributes=+.
- # The SPA's API path uses the explicit hash-array setter defined below
- # (+product_publications=+); the two coexist on different keys.
- accepts_nested_attributes_for :product_publications,
+ # Legacy Rails admin alias. The admin form submits
+ # +legacy_product_publications_attributes+ (with +_destroy+ flags and
+ # +reject_if+ semantics); the v3 API submits +product_publications+
+ # and goes through the custom writer below. Two names, one table —
+ # no +dependent:+ for the same +acts_as_paranoid+ reason as above.
+ has_many :legacy_product_publications, class_name: 'Spree::ProductPublication',
+ foreign_key: :product_id, autosave: true
+ accepts_nested_attributes_for :legacy_product_publications,
allow_destroy: true,
reject_if: ->(attrs) { attrs[:channel_id].blank? }
@@ -63,12 +66,14 @@ module Spree
end
# Syncs product publications from an array of hashes.
- # Creates new publications, updates existing ones (matched by :id), and removes
- # ones absent from the payload. Mirrors +Product#variants=+.
+ # Creates new publications, updates existing ones (matched by +:id+ or
+ # +:channel_id+), and removes ones absent from the payload. An empty
+ # array detaches the product from every channel.
# @param publications_params [Array<Hash>] array of publication attribute hashes
# @return [void]
def product_publications=(publications_params)
- return super if publications_params.blank? || publications_params.first.is_a?(Spree::ProductPublication)
+ return super if publications_params.nil?
+ return super if publications_params.respond_to?(:first) && publications_params.first.is_a?(Spree::ProductPublication)
if new_record?
@pending_publications_params = publications_params
@@ -95,20 +100,13 @@ module Spree
@pending_publications_params = nil
end
- # SPA write contract for +product.product_publications=+: the caller
- # sends the FULL desired set of publications. Rows present become
- # creates/updates; rows absent get destroyed. Mass-delete is safe
- # because the only caller (+<PublishingCard>+ in the dashboard) drives
- # the array via +useFieldArray+ and always submits the complete state.
- # The Rails admin uses +product_publications_attributes=+ (nested
- # attributes) instead — that path uses explicit +_destroy: '1'+ flags
- # and never reaches this method.
def apply_product_publications(publications_params)
publication_ids_in_payload = []
publications_params.each do |publication_data|
publication_data = publication_data.to_h.with_indifferent_access
publication_id = publication_data.delete(:id)
+ channel_id = decode_publication_channel_id(publication_data[:channel_id])
if publication_id.present?
decoded_id = Spree::PrefixedId.prefixed_id?(publication_id) ?
@@ -117,21 +115,28 @@ module Spree
publication = product_publications.find_by(id: decoded_id)
next unless publication
- # Channel is immutable on a publication — silently drop any
- # caller attempt to rebind it. Re-publish on a different channel
- # is a destroy + create, not an update.
+ # Channel is immutable; ignore any rebind attempt.
publication.update!(publication_data.slice(:published_at, :unpublished_at))
publication_ids_in_payload << publication.id
- elsif publication_data[:channel_id].present?
- new_publication = product_publications.create!(
- publication_data.slice(:channel_id, :published_at, :unpublished_at)
- )
- publication_ids_in_payload << new_publication.id
+ elsif channel_id.present?
+ # Upsert by channel_id so repeat submissions are idempotent
+ # against the unique (product_id, channel_id) index.
+ publication = product_publications.find_or_initialize_by(channel_id: channel_id)
+ publication.assign_attributes(publication_data.slice(:published_at, :unpublished_at))
+ publication.save!
+ publication_ids_in_payload << publication.id
end
end
product_publications.where.not(id: publication_ids_in_payload).destroy_all
end
+
+ def decode_publication_channel_id(value)
+ return nil if value.blank?
+ return value unless Spree::PrefixedId.prefixed_id?(value)
+
+ Spree::PrefixedId.decode_prefixed_id(value) || value
+ end
end
end
end
diff --git a/spree/core/lib/spree/permitted_attributes.rb b/spree/core/lib/spree/permitted_attributes.rb
index d18355f463..9100d76339 100644
--- a/spree/core/lib/spree/permitted_attributes.rb
+++ b/spree/core/lib/spree/permitted_attributes.rb
@@ -193,7 +193,7 @@ module Spree
option_type_ids: [],
taxon_ids: [],
product_option_types_attributes: [:id, :option_type_id, :position, :_destroy],
- product_publications_attributes: [:id, :channel_id, :published_at, :unpublished_at, :_destroy]
+ legacy_product_publications_attributes: [:id, :channel_id, :published_at, :unpublished_at, :_destroy]
}
]
diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rb
index ee92c7d97f..10b96e8eee 100644
--- a/spree/core/spec/models/spree/product_spec.rb
+++ b/spree/core/spec/models/spree/product_spec.rb
@@ -2031,6 +2031,26 @@ describe Spree::Product, type: :model do
expect(fresh.product_publications).to include(pub)
end
end
+
+ context 'idempotency and detach' do
+ it 'is idempotent when re-sending an existing channel by channel_id' do
+ existing = product.product_publications.create!(channel: pos_channel)
+
+ expect {
+ product.product_publications = [{ channel_id: pos_channel.prefixed_id }]
+ }.not_to raise_error
+
+ expect(product.product_publications.where(channel_id: pos_channel.id).pluck(:id)).to eq([existing.id])
+ end
+
+ it 'detaches every channel when given an empty array' do
+ product.product_publications.create!(channel: pos_channel)
+
+ product.product_publications = []
+
+ expect(product.product_publications.reload).to be_empty
+ end
+ end
end
end
end