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.

Make deleting variants in rails admin safer (#14299)

Damian Legawiecb402c0c09dec
diff --git a/spree/admin/app/javascript/spree/admin/controllers/variants_form_controller.js b/spree/admin/app/javascript/spree/admin/controllers/variants_form_controller.js
index a4c43a0695..ec9b9327b1 100644
--- a/spree/admin/app/javascript/spree/admin/controllers/variants_form_controller.js
+++ b/spree/admin/app/javascript/spree/admin/controllers/variants_form_controller.js
@@ -72,6 +72,10 @@ export default class extends CheckboxSelectAll {
}
this.inventoryFormTarget = document.querySelector('.inventory-form');
+
+ // Drop stale removal inputs (e.g. restored from the Turbo cache) so a fresh
+ // session never re-submits removals the user didn't make in it.
+ this.syncRemovedVariantIdInputs()
}
toggleQuantityTracked() {
@@ -119,6 +123,37 @@ export default class extends CheckboxSelectAll {
}
}
+ // The set of persisted variant ids the user removed from the matrix. Submitted as
+ // `product[removed_variant_ids][]` — the server only ever destroys ids listed there,
+ // never variants that are merely missing from the re-submitted form.
+ get removedVariantIds() {
+ if (!this._removedVariantIds) this._removedVariantIds = new Set()
+
+ return this._removedVariantIds
+ }
+
+ markVariantRemoved(internalName) {
+ const variantId = this.variantIdsValue[internalName]
+ if (variantId) this.removedVariantIds.add(String(variantId))
+ }
+
+ markVariantKept(internalName) {
+ const variantId = this.variantIdsValue[internalName]
+ if (variantId) this.removedVariantIds.delete(String(variantId))
+ }
+
+ syncRemovedVariantIdInputs() {
+ this.element.querySelectorAll('input[name="product[removed_variant_ids][]"]').forEach((input) => input.remove())
+
+ this.removedVariantIds.forEach((variantId) => {
+ const input = document.createElement('input')
+ input.type = 'hidden'
+ input.name = 'product[removed_variant_ids][]'
+ input.value = variantId
+ this.element.appendChild(input)
+ })
+ }
+
deleteSelected() {
const newStockValue = this.stockValue
const newPricesValue = this.pricesValue
@@ -126,6 +161,7 @@ export default class extends CheckboxSelectAll {
const internalName = checkbox.value
this.ignoredVariants.add(internalName)
+ this.markVariantRemoved(internalName)
const variant = this.variantsContainerTarget.querySelector(`[data-variant-name="${internalName}"]`)
const nestingLevel = internalName.split('/').length
@@ -157,7 +193,8 @@ export default class extends CheckboxSelectAll {
delete newStockValue[internalName]
delete newPricesValue[internalName]
- variant.remove()
+ // the row may already be gone when deleting an option value re-rendered the matrix
+ variant?.remove()
})
this.stockValue = newStockValue
@@ -166,6 +203,7 @@ export default class extends CheckboxSelectAll {
this.checkboxAllTarget.checked = false
this.refresh()
this.refreshParentInputs()
+ this.syncRemovedVariantIdInputs()
}
reorderOptions(event) {
@@ -498,6 +536,14 @@ export default class extends CheckboxSelectAll {
}
currentVariants.add(internalName)
+ // Reconcile the removal ledger with what this render keeps: leaf rows
+ // re-submit their variant id, parent (grouping) rows never do.
+ if (i === nestingLevel - 1) {
+ this.markVariantKept(internalName)
+ } else if (i === 0 && nestingLevel > 1) {
+ this.markVariantRemoved(internalName)
+ }
+
const existingVariant = this.variantsContainerTarget.querySelector(`[data-variant-name="${internalName}"]`)
if (existingVariant) {
if (i === 0) {
@@ -599,6 +645,7 @@ export default class extends CheckboxSelectAll {
this.variantsContainerTarget.querySelectorAll('[data-variants-form-target="variant"]').forEach((variant) => {
const variantName = variant.dataset.variantName
if (!currentVariants.has(variantName)) {
+ this.markVariantRemoved(variantName)
variant.remove()
}
})
@@ -609,6 +656,7 @@ export default class extends CheckboxSelectAll {
}
this.refreshParentInputs()
+ this.syncRemovedVariantIdInputs()
}
refreshParentInputs() {
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 8f04436626..ffab0d0e46 100644
--- a/spree/admin/spec/controllers/spree/admin/products_controller_spec.rb
+++ b/spree/admin/spec/controllers/spree/admin/products_controller_spec.rb
@@ -1128,9 +1128,10 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
end
end
- context 'when variant is no longer present in the params' do
+ context 'when variant is explicitly removed' do
before do
product_params[:variants_attributes].delete('0')
+ product_params[:removed_variant_ids] = [variant1.id.to_s]
end
it 'removes the variant' do
@@ -1140,18 +1141,44 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
end
end
- context 'when all variants are removed' do
+ context 'when variant is no longer present in the params but not explicitly removed' do
+ before do
+ product_params[:variants_attributes].delete('0')
+ end
+
+ it 'keeps the variant' do
+ send_request
+
+ expect(product.reload.variant_ids).to match_array([variant1.id, variant2.id, variant3.id])
+ end
+ end
+
+ context 'when all variants are explicitly removed' do
before do
product_params.delete(:variants_attributes)
+ product_params[:removed_variant_ids] = [variant1.id.to_s, variant2.id.to_s, variant3.id.to_s]
end
- it 'removes the product variants' do
+ it 'removes the product variants and option types' do
send_request
expect(product.reload.variant_ids).to be_empty
expect(product.option_types).to be_empty
end
end
+
+ context 'when variants_attributes are missing without explicit removals' do
+ before do
+ product_params.delete(:variants_attributes)
+ end
+
+ it 'keeps the product variants and option types' do
+ send_request
+
+ expect(product.reload.variant_ids).to match_array([variant1.id, variant2.id, variant3.id])
+ expect(product.option_types).not_to be_empty
+ end
+ end
end
context 'setting track_inventory to false' do
diff --git a/spree/core/app/services/spree/products/prepare_nested_attributes.rb b/spree/core/app/services/spree/products/prepare_nested_attributes.rb
index e0b0f8a60b..99a9422c99 100644
--- a/spree/core/app/services/spree/products/prepare_nested_attributes.rb
+++ b/spree/core/app/services/spree/products/prepare_nested_attributes.rb
@@ -7,6 +7,12 @@ module Spree
# from other stores are preserved. This prevents accidental data loss when a store
# admin updates product categories in their store without affecting other stores.
#
+ # Variant removal is opt-in: only variants explicitly listed in the
+ # `removed_variant_ids` param are marked for destruction (or collected for
+ # discontinuation when they have completed orders). Variants merely absent from
+ # `variants_attributes` are left untouched, so a partially rendered or broken
+ # form can never silently mass-delete variants.
+ #
# @example
# service = Spree::Products::PrepareNestedAttributes.new(
# product,
@@ -28,10 +34,13 @@ module Spree
end
def call
+ extract_removed_variant_ids
+
if params[:variants_attributes]
params[:variants_attributes].each do |key, variant_params|
existing_variant = variant_params[:id].presence && @product.variants.find_by(id: variant_params[:id])
- variants_to_remove.delete(variant_params[:id]) if variant_params[:id].present?
+ # a re-submitted variant always wins over a removal request
+ variants_to_remove.delete(variant_params[:id].to_s) if variant_params[:id].present?
variant_params.delete(:price) # remove legacy price param
@@ -72,17 +81,20 @@ module Spree
# ensure the product is owned by a store
params[:store_id] = store.id if params[:store_id].blank? && product.store_id.blank?
- # Add empty list for option_type_ids and mark variants as removed if there are no variants and options
- if params[:variants_attributes].blank? && variants_to_remove.any? && !params.key?(:option_type_ids)
- params[:option_type_ids] = []
- params[:variants_attributes] = {}
+ # The variants matrix was emptied: no variant rows re-submitted, removals sent instead.
+ # Option types are detached only when the removal list covers every variant, so a
+ # partial (possibly broken) submission never turns the product into a simple one.
+ # Variants kept alive by discontinuation still count as removed from the matrix,
+ # so the detachment can't hinge on any of them yielding a `_destroy` row.
+ if params[:variants_attributes].blank? && variants_to_remove.any? && can_remove_variants?
+ attributes = removed_variants_attributes
- populate_variants_to_discontinue
- variant_ids_to_destroy.each_with_index do |variant_id, index|
- params[:variants_attributes][index.to_s] = { id: variant_id, _destroy: '1' }
- end
+ params[:option_type_ids] = [] if removing_all_variants? && !params.key?(:option_type_ids)
- params[:variants_attributes].permit!
+ if attributes.any?
+ params[:variants_attributes] = attributes
+ params[:variants_attributes].permit!
+ end
end
params
@@ -116,8 +128,24 @@ module Spree
@product_option_types_to_remove ||= product.product_option_type_ids
end
+ # Pulls `removed_variant_ids` out of the params so it never reaches Product#update.
+ # Must run before any `variants_to_remove` access.
+ def extract_removed_variant_ids
+ @removed_variant_ids = Array(params.delete(:removed_variant_ids)).map(&:to_s)
+ end
+
+ # Only variants the client explicitly asked to remove, and only ones that
+ # actually belong to this product.
def variants_to_remove
- @variants_to_remove ||= product.variant_ids.map(&:to_s)
+ @variants_to_remove ||= (@removed_variant_ids || []).uniq & all_variant_ids
+ end
+
+ def all_variant_ids
+ @all_variant_ids ||= product.variant_ids.map(&:to_s)
+ end
+
+ def removing_all_variants?
+ (all_variant_ids - variants_to_remove).empty?
end
def can_update_prices?
@@ -142,7 +170,7 @@ module Spree
populate_variants_to_discontinue
attributes = {}
- last_index = params[:variants_attributes].keys.map(&:to_i).max
+ last_index = params[:variants_attributes].presence&.keys&.map(&:to_i)&.max || -1
variant_ids_to_destroy.each_with_index do |variant_id, index|
attributes[(last_index + 1 + index).to_s] = { id: variant_id, _destroy: '1' }
end
diff --git a/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb b/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb
index 627d3e8592..dc59f57a36 100644
--- a/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb
+++ b/spree/core/lib/spree/core/controller_helpers/strong_parameters.rb
@@ -33,6 +33,7 @@ module Spree
def permitted_product_attributes
permitted_attributes.product_attributes + [
+ removed_variant_ids: [],
variants_attributes: permitted_variant_attributes + ['id', :_destroy],
master_attributes: permitted_variant_attributes + ['id']
]
diff --git a/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb b/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb
index 09e68e5c0b..06d46b5c5f 100644
--- a/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb
+++ b/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb
@@ -112,22 +112,86 @@ RSpec.describe Spree::Products::PrepareNestedAttributes do
describe 'variant removal handling' do
let(:option_type) { create(:option_type) }
- let(:option_value) { create(:option_value, option_type: option_type) }
let(:variant) { create(:variant, product: product) }
- context 'when variant has completed orders' do
- before do
- create(:completed_order_with_totals, variants: [variant])
+ let(:new_option_value) { create(:option_value, option_type: option_type) }
+ let(:new_variant) { create(:variant, product: product) }
+ let(:variants_attributes) do
+ {
+ '0' => {
+ id: new_variant.id.to_s,
+ options: [
+ {
+ id: option_type.id,
+ name: option_type.name,
+ position: '0',
+ option_value_name: new_option_value.name,
+ option_value_presentation: new_option_value.presentation
+ }
+ ]
+ }
+ }
+ end
+
+ context 'when a variant is only omitted from variants_attributes' do
+ before { variant } # ensure variant exists before service runs
+
+ let(:raw_params) { { variants_attributes: variants_attributes } }
+
+ it 'does not mark the omitted variant for destruction' do
+ removed = prepared_params[:variants_attributes].values.find { |v| v[:id] == variant.id.to_s }
+ expect(removed).to be_nil
end
- context 'via variants_attributes' do
- let(:new_option_value) { create(:option_value, option_type: option_type) }
- let(:new_variant) { create(:variant, product: product) }
+ it 'does not collect the omitted variant for discontinuation' do
+ prepared_params
+ expect(service.variants_to_discontinue).to be_empty
+ end
+ end
+
+ context 'when no variants_attributes and no removals are submitted' do
+ before { variant } # ensure variant exists before service runs
+
+ let(:raw_params) { { name: 'Updated Product' } }
+
+ it 'leaves the variants untouched' do
+ expect(prepared_params[:variants_attributes]).to be_nil
+ end
+
+ it 'does not clear the option types' do
+ expect(prepared_params).not_to have_key(:option_type_ids)
+ end
+ end
+
+ context 'when a variant is explicitly removed' do
+ let(:raw_params) do
+ {
+ removed_variant_ids: [variant.id.to_s],
+ variants_attributes: variants_attributes
+ }
+ end
+
+ it 'marks the variant for destruction' do
+ removed = prepared_params[:variants_attributes].values.find { |v| v[:id] == variant.id.to_s }
+ expect(removed[:_destroy]).to eq('1')
+ end
+
+ it 'does not collect the variant for discontinuation' do
+ prepared_params
+ expect(service.variants_to_discontinue).not_to include(variant)
+ end
+
+ it 'consumes the removed_variant_ids param' do
+ expect(prepared_params).not_to have_key(:removed_variant_ids)
+ end
+
+ context 'when the variant is also re-submitted in variants_attributes' do
let(:raw_params) do
{
- variants_attributes: {
- '0' => {
- id: new_variant.id.to_s,
+ removed_variant_ids: [variant.id.to_s],
+ variants_attributes: variants_attributes.merge(
+ '1' => {
+ id: variant.id.to_s,
options: [
{
id: option_type.id,
@@ -138,92 +202,138 @@ RSpec.describe Spree::Products::PrepareNestedAttributes do
}
]
}
- }
+ )
}
end
- it 'collects the variant for discontinuation' do
- prepared_params
- expect(service.variants_to_discontinue).to include(variant)
+ it 'keeps the variant' do
+ removed = prepared_params[:variants_attributes].values.find { |v| v[:id] == variant.id.to_s && v[:_destroy].present? }
+ expect(removed).to be_nil
end
+ end
- it 'does not include the variant in removal attributes' do
+ context 'when the user cannot destroy variants' do
+ before do
+ ability.cannot :destroy, Spree::Variant
+ end
+
+ it 'ignores the removals' do
removed = prepared_params[:variants_attributes].values.find { |v| v[:id] == variant.id.to_s }
expect(removed).to be_nil
end
end
+ end
- context 'via fallback removal (no variants_attributes)' do
- let(:raw_params) { { name: 'Updated Product' } }
+ context 'when a removed variant belongs to another product' do
+ let(:other_variant) { create(:variant) }
+ let(:raw_params) do
+ {
+ removed_variant_ids: [other_variant.id.to_s],
+ variants_attributes: variants_attributes
+ }
+ end
- it 'collects the variant for discontinuation' do
- prepared_params
- expect(service.variants_to_discontinue).to include(variant)
+ it 'ignores the foreign variant id' do
+ removed = prepared_params[:variants_attributes].values.find { |v| v[:id] == other_variant.id.to_s }
+ expect(removed).to be_nil
+ end
+ end
+
+ context 'when all variants are removed without variants_attributes' do
+ let(:raw_params) { { name: 'Updated Product', removed_variant_ids: [variant.id.to_s] } }
+
+ it 'marks the variant for destruction' do
+ removed = prepared_params[:variants_attributes].values.find { |v| v[:id] == variant.id.to_s }
+ expect(removed[:_destroy]).to eq('1')
+ end
+
+ it 'clears the option types' do
+ expect(prepared_params[:option_type_ids]).to eq([])
+ end
+
+ context 'when the user cannot destroy variants' do
+ before do
+ ability.cannot :destroy, Spree::Variant
end
- it 'does not include the variant in destruction attributes' do
- removed = prepared_params[:variants_attributes]&.values&.find { |v| v[:id] == variant.id.to_s }
- expect(removed).to be_nil
+ it 'ignores the removals and keeps the option types' do
+ expect(prepared_params[:variants_attributes]).to be_nil
+ expect(prepared_params).not_to have_key(:option_type_ids)
end
end
end
- context 'when variant has no completed orders' do
- before { variant } # ensure variant exists before service runs
+ context 'when only some variants are removed without variants_attributes' do
+ before { new_variant } # ensure the second variant exists before service runs
+
+ let(:raw_params) { { name: 'Updated Product', removed_variant_ids: [variant.id.to_s] } }
+
+ it 'marks only the removed variant for destruction' do
+ expect(prepared_params[:variants_attributes].values.map { |v| v[:id] }).to eq([variant.id.to_s])
+ end
+
+ it 'does not clear the option types' do
+ expect(prepared_params).not_to have_key(:option_type_ids)
+ end
+ end
+
+ context 'when a removed variant has completed orders' do
+ before do
+ create(:completed_order_with_totals, variants: [variant])
+ end
context 'via variants_attributes' do
- let(:new_option_value) { create(:option_value, option_type: option_type) }
- let(:new_variant) { create(:variant, product: product) }
let(:raw_params) do
{
- variants_attributes: {
- '0' => {
- id: new_variant.id.to_s,
- options: [
- {
- id: option_type.id,
- name: option_type.name,
- position: '0',
- option_value_name: new_option_value.name,
- option_value_presentation: new_option_value.presentation
- }
- ]
- }
- }
+ removed_variant_ids: [variant.id.to_s],
+ variants_attributes: variants_attributes
}
end
- it 'marks the variant for destruction' do
+ it 'collects the variant for discontinuation' do
+ prepared_params
+ expect(service.variants_to_discontinue).to include(variant)
+ end
+
+ it 'does not include the variant in removal attributes' do
removed = prepared_params[:variants_attributes].values.find { |v| v[:id] == variant.id.to_s }
- expect(removed[:_destroy]).to eq('1')
+ expect(removed).to be_nil
end
+ end
+
+ context 'without variants_attributes' do
+ let(:raw_params) { { name: 'Updated Product', removed_variant_ids: [variant.id.to_s] } }
- it 'does not collect the variant for discontinuation' do
+ it 'collects the variant for discontinuation' do
prepared_params
- expect(service.variants_to_discontinue).not_to include(variant)
+ expect(service.variants_to_discontinue).to include(variant)
end
- end
- context 'via fallback removal (no variants_attributes)' do
- let(:raw_params) { { name: 'Updated Product' } }
+ it 'does not include the variant in destruction attributes' do
+ removed = prepared_params[:variants_attributes]&.values&.find { |v| v[:id] == variant.id.to_s }
+ expect(removed).to be_nil
+ end
- it 'marks the variant for destruction' do
- removed = prepared_params[:variants_attributes].values.find { |v| v[:id] == variant.id.to_s }
- expect(removed[:_destroy]).to eq('1')
+ it 'still clears the option types' do
+ expect(prepared_params[:option_type_ids]).to eq([])
end
end
end
- context 'when product has mix of variants with and without completed orders' do
+ context 'when removing a mix of variants with and without completed orders' do
let(:variant_with_order) { create(:variant, product: product) }
let(:variant_without_order) { create(:variant, product: product) }
before do
- variant_without_order # ensure variant exists before service runs
create(:completed_order_with_totals, variants: [variant_with_order])
end
- let(:raw_params) { { name: 'Updated Product' } }
+ let(:raw_params) do
+ {
+ name: 'Updated Product',
+ removed_variant_ids: [variant_with_order.id.to_s, variant_without_order.id.to_s]
+ }
+ end
it 'collects the variant with completed orders for discontinuation' do
prepared_params