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.

Address review feedback on the Collections UI

Damian Legawiecc5ed9702efdb
diff --git a/packages/dashboard/src/components/spree/categories/category-products-card.tsx b/packages/dashboard/src/components/spree/categories/category-products-card.tsx
index e4fe03036e..242ad1653d 100644
--- a/packages/dashboard/src/components/spree/categories/category-products-card.tsx
+++ b/packages/dashboard/src/components/spree/categories/category-products-card.tsx
@@ -144,8 +144,13 @@ export function CategoryProductsCard({ categoryId }: { categoryId: string }) {
async function handleBulkRemove() {
const ids = [...selected]
if (ids.length === 0) return
- await removeProducts.mutateAsync(ids)
- setSelected(new Set())
+ try {
+ await removeProducts.mutateAsync(ids)
+ setSelected(new Set())
+ } catch {
+ // The mutation toasts its own error; swallow the rethrow so the click
+ // handler doesn't reject, and keep the selection so the user can retry.
+ }
}
const allSelected = visibleIds.length > 0 && visibleIds.every((id) => selected.has(id))
diff --git a/packages/dashboard/src/components/spree/collections/collection-products-card.tsx b/packages/dashboard/src/components/spree/collections/collection-products-card.tsx
index 8016b4c170..7f47de89c4 100644
--- a/packages/dashboard/src/components/spree/collections/collection-products-card.tsx
+++ b/packages/dashboard/src/components/spree/collections/collection-products-card.tsx
@@ -151,8 +151,13 @@ export function CollectionProductsCard({
async function handleBulkRemove() {
const ids = [...selected]
if (ids.length === 0) return
- await removeProducts.mutateAsync(ids)
- setSelected(new Set())
+ try {
+ await removeProducts.mutateAsync(ids)
+ setSelected(new Set())
+ } catch {
+ // The mutation toasts its own error; swallow the rethrow so the click
+ // handler doesn't reject, and keep the selection so the user can retry.
+ }
}
const allSelected = visibleIds.length > 0 && visibleIds.every((id) => selected.has(id))
diff --git a/packages/dashboard/src/components/spree/collections/collection-rules-card.tsx b/packages/dashboard/src/components/spree/collections/collection-rules-card.tsx
index d02dac91ef..7f7e128ccc 100644
--- a/packages/dashboard/src/components/spree/collections/collection-rules-card.tsx
+++ b/packages/dashboard/src/components/spree/collections/collection-rules-card.tsx
@@ -49,6 +49,13 @@ export function CollectionRulesCard({ form }: { form: UseFormReturn<CollectionFo
value: ruleType.type,
label: typeLabel('collection_rule_types', ruleType.type, ruleType.label),
}))
+
+ // Seed a new row from the registry so the Select always shows a real option,
+ // even on a deployment that doesn't register the schema's default kind.
+ const newRule = () => ({
+ ...blankCollectionRule(),
+ ...(typeOptions[0] ? { type: typeOptions[0].value } : {}),
+ })
const matchPolicyOptions = COLLECTION_RULE_MATCH_POLICIES.map((value) => ({
value,
label: t(`admin.collections.rule_match_policies.${value}`),
@@ -77,7 +84,7 @@ export function CollectionRulesCard({ form }: { form: UseFormReturn<CollectionFo
field.onChange(checked)
// Give an automatic collection something to fill in rather
// than an empty rule list that matches nothing.
- if (checked && rules.fields.length === 0) rules.append(blankCollectionRule())
+ if (checked && rules.fields.length === 0) rules.append(newRule())
}}
/>
)}
@@ -210,7 +217,7 @@ export function CollectionRulesCard({ form }: { form: UseFormReturn<CollectionFo
variant="outline"
size="sm"
className="self-start"
- onClick={() => rules.append(blankCollectionRule())}
+ onClick={() => rules.append(newRule())}
>
<PlusIcon className="size-4" />
{t('admin.collections.rules.add')}
diff --git a/packages/dashboard/src/schemas/collection.ts b/packages/dashboard/src/schemas/collection.ts
index 56604c62f2..d7624e9b39 100644
--- a/packages/dashboard/src/schemas/collection.ts
+++ b/packages/dashboard/src/schemas/collection.ts
@@ -46,6 +46,18 @@ const DEFAULT_RULE_TYPE = 'tag'
* rules with their STI class name but accepts (and advertises) the shorthand,
* so normalize on the way in.
*/
+/**
+ * Narrows a server-supplied match policy to one this build knows. The rule
+ * registry is server-driven, so an unrecognized policy falls back to the
+ * default rather than rendering an empty Select and failing validation on save.
+ */
+function knownMatchPolicy(value: string | null): CollectionRuleFormValues['match_policy'] {
+ const policies: readonly string[] = COLLECTION_RULE_MATCH_POLICIES
+ return policies.includes(value ?? '')
+ ? (value as CollectionRuleFormValues['match_policy'])
+ : 'is_equal_to'
+}
+
function ruleTypeShorthand(type: string) {
const leaf = type.split('::').pop() ?? type
return leaf.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()
@@ -144,7 +156,7 @@ export function collectionToForm(collection: Collection): CollectionFormValues {
id: rule.id,
type: ruleTypeShorthand(rule.type),
value: rule.value ?? '',
- match_policy: rule.match_policy as CollectionRuleFormValues['match_policy'],
+ match_policy: knownMatchPolicy(rule.match_policy),
})) ?? [],
custom_fields:
collection.custom_fields?.map((cf) => ({
diff --git a/packages/dashboard/src/tables/collections.tsx b/packages/dashboard/src/tables/collections.tsx
index 6c6d4fde48..ebbd9d0f82 100644
--- a/packages/dashboard/src/tables/collections.tsx
+++ b/packages/dashboard/src/tables/collections.tsx
@@ -46,7 +46,13 @@ defineTable<Collection>('collections', {
key: 'sort_order',
label: i18n.t('admin.collections.columns.sort_order'),
default: true,
- render: (collection) => i18n.t(sortOrderLabelKey(collection.sort_order ?? 'manual')),
+ render: (collection) => {
+ // `sort_order` is an open string on the wire, so a value this build
+ // doesn't know would otherwise render its raw translation key.
+ const value = collection.sort_order ?? 'manual'
+ const key = sortOrderLabelKey(value)
+ return i18n.exists(key) ? i18n.t(key) : value
+ },
},
{
key: 'products_count',
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 0a30d9e71a..dc035cbb85 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
@@ -181,9 +181,9 @@ module Spree
:promotionable, :digital,
tags: [],
category_ids: [],
- # Collection membership. Assigning an automatic collection here
- # persists, but its next rule regeneration overwrites the member
- # list — so the dashboard only offers manual collections.
+ # Manual collection membership. Automatic collections are dropped
+ # by the model setter (their members come from their rules), the
+ # same way the bulk endpoints scope to `.manual`.
collection_ids: [],
metadata: {},
prices: [:amount, :compare_at_amount, :currency],
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 699b14908a..06b05cabcb 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
@@ -824,6 +824,46 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
end
end
+ context 'with collection_ids' do
+ let!(:manual_collection) { create(:collection, store: store) }
+
+ it 'assigns manual collections via prefixed IDs' do
+ patch :update, params: {
+ id: product.prefixed_id,
+ collection_ids: [manual_collection.prefixed_id]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(product.reload.collections).to eq([manual_collection])
+ end
+
+ # Automatic membership is materialized from rules, so a hand-set member
+ # would vanish on the next regeneration — mirrors the bulk endpoints.
+ it 'ignores automatic collections' do
+ automatic = create(:automatic_collection, store: store)
+
+ patch :update, params: {
+ id: product.prefixed_id,
+ collection_ids: [manual_collection.prefixed_id, automatic.prefixed_id]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(product.reload.collections).to eq([manual_collection])
+ end
+
+ it "ignores a collection that belongs to another store" do
+ foreign = create(:collection, store: create(:store))
+
+ patch :update, params: {
+ id: product.prefixed_id,
+ collection_ids: [manual_collection.prefixed_id, foreign.prefixed_id]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(product.reload.collections).to eq([manual_collection])
+ end
+ end
+
context 'with category_ids' do
it 'assigns categories via prefixed IDs' do
patch :update, params: {
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index b933348eb7..fc344d170c 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -263,14 +263,20 @@ module Spree
super(Spree::Category.for_store(assignable_store).where(id: decoded_ids).ids)
end
- # Accepts both prefixed IDs and raw integer IDs. Only collections belonging
- # to the product's own store are assigned; this overrides the generated setter
- # and calls super.
+ # Accepts both prefixed IDs and raw integer IDs. Only manual collections
+ # belonging to the product's own store are assigned; this overrides the
+ # generated setter and calls super.
+ #
+ # Automatic collections are dropped rather than assigned: their membership
+ # is materialized from their rules, so a hand-set member would silently
+ # disappear on the next regeneration. This matches the bulk endpoints
+ # (`Spree::Api::V3::Admin::ProductsController#apply_collections`), which
+ # scope to `.manual` for the same reason.
def collection_ids=(ids)
decoded_ids = Array(ids).filter_map do |id|
id.to_s.include?('_') ? Spree::Collection.decode_prefixed_id(id) : id
end
- super(Spree::Collection.for_store(assignable_store).where(id: decoded_ids).ids)
+ super(Spree::Collection.for_store(assignable_store).manual.where(id: decoded_ids).ids)
end
# Sync media inline. Entries with `id` patch the existing asset
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index f6575b3699..8b1f2cdb4a 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -740,8 +740,6 @@ en:
close: Close
closed: Closed
code: Code
- color_code: Color Code
- colors: Colors
collection_rule_types:
available_on:
description: Products published within the last N days
@@ -752,6 +750,8 @@ en:
tag:
description: Products carrying a matching tag
name: Tag
+ color_code: Color Code
+ colors: Colors
company: Company
compare_at_amount: Compare at amount
compare_at_price: Compare at price