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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Address CodeRabbit review on categories
Damian Legawiec1c58dcee580e
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex 3068285565..9152691ac2 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -371,8 +371,8 @@ export interface ProductVariantInput {export interface CategoryCreateParams {name: string- /** Prefixed ID of the parent category. Omit for a top-level category. */- parent_id?: string+ /** Prefixed ID of the parent category. Omit or null for a top-level category. */+ parent_id?: string | nulldescription?: stringpermalink?: stringmeta_title?: string@@ -387,18 +387,18 @@ export interface CategoryCreateParams {export interface CategoryUpdateParams {name?: string- /** Prefixed ID of the parent category (moves the category in the tree). */- parent_id?: string+ /** Prefixed ID of the parent category, or null to move it to the top level. */+ parent_id?: string | nulldescription?: stringpermalink?: stringmeta_title?: stringmeta_description?: stringmeta_keywords?: stringhide_from_nav?: boolean- /** ActiveStorage signed_id of a directly-uploaded landscape image. */- image?: string- /** ActiveStorage signed_id of a directly-uploaded square image. */- square_image?: string+ /** ActiveStorage signed_id of a directly-uploaded landscape image, or null to remove it. */+ image?: string | null+ /** ActiveStorage signed_id of a directly-uploaded square image, or null to remove it. */+ square_image?: string | null}export interface CategoryRepositionParams {diff --git a/packages/dashboard-core/src/components/image-upload-field.tsx b/packages/dashboard-core/src/components/image-upload-field.tsxindex 811b8181a3..9e866a63e3 100644--- a/packages/dashboard-core/src/components/image-upload-field.tsx+++ b/packages/dashboard-core/src/components/image-upload-field.tsx@@ -1,6 +1,6 @@import { Button, cn, Field, FieldDescription, FieldLabel } from '@spree/dashboard-ui'import { ImageIcon, UploadCloudIcon } from 'lucide-react'-import { useEffect, useRef, useState } from 'react'+import { useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'import { useDirectUpload } from '../hooks/use-direct-upload'@@ -63,19 +63,10 @@ export function ImageUploadField({const currentPreview = value.previewUrl ?? (value.cleared ? null : (serverUrl ?? null))const hasImage = !!currentPreview- // Revoke the previous object URL when it changes / on unmount.- const previewUrlRef = useRef<string | null>(null)- useEffect(() => {- const previous = previewUrlRef.current- if (previous && previous !== value.previewUrl) URL.revokeObjectURL(previous)- previewUrlRef.current = value.previewUrl ?? null- }, [value.previewUrl])- useEffect(() => {- return () => {- if (previewUrlRef.current) URL.revokeObjectURL(previewUrlRef.current)- }- }, [])-+ // The object URL lives in caller-owned state (the form), so its lifetime is+ // the caller's responsibility — the field must not revoke it on unmount, or a+ // hidden-then-shown card (e.g. the store-logo card) would remount with a dead+ // URL. We only revoke a URL we're replacing in-place below, within this field.async function onFileChange(e: React.ChangeEvent<HTMLInputElement>) {const file = e.target.files?.[0]if (!file) returndiff --git a/packages/dashboard-core/src/components/resource-picker-sheet.tsx b/packages/dashboard-core/src/components/resource-picker-sheet.tsxindex 61b2387535..bf035cdac5 100644--- a/packages/dashboard-core/src/components/resource-picker-sheet.tsx+++ b/packages/dashboard-core/src/components/resource-picker-sheet.tsx@@ -43,6 +43,8 @@ export interface ResourcePickerSheetProps<T extends PickerOption> {description?: stringsearchPlaceholder?: stringconfirmLabel?: string+ /** Called if `onConfirm` rejects. The sheet stays open with the staged selection. */+ onConfirmError?: (error: unknown) => void}/**@@ -69,6 +71,7 @@ export function ResourcePickerSheet<T extends PickerOption>({description,searchPlaceholder,confirmLabel,+ onConfirmError,}: ResourcePickerSheetProps<T>) {const { t } = useTranslation()@@ -109,6 +112,11 @@ export function ResourcePickerSheet<T extends PickerOption>({setStaged(new Map())setInput('')onOpenChange(false)+ } catch (error) {+ // The mutation reports its own error toast; swallow so the click handler+ // doesn't reject, and keep the sheet open with the staged selection so the+ // user can retry. Callers can observe failures via onConfirmError.+ onConfirmError?.(error)} finally {setSubmitting(false)}diff --git a/packages/dashboard/src/components/spree/categories/category-form.tsx b/packages/dashboard/src/components/spree/categories/category-form.tsxindex 5d92832d8d..b413cf18ba 100644--- a/packages/dashboard/src/components/spree/categories/category-form.tsx+++ b/packages/dashboard/src/components/spree/categories/category-form.tsx@@ -74,6 +74,7 @@ export function CategoryMain({/>)}/>+ <FieldError errors={[errors.description]} /></Field></FieldGroup></CardContent>@@ -92,6 +93,7 @@ export function CategorySidebar({category?: Category}) {const { t } = useTranslation()+ const { errors } = form.formStatereturn (<>@@ -131,6 +133,7 @@ export function CategorySidebar({/>)}/>+ <FieldError errors={[errors.parent_id]} /></Field></CardContent></Card>@@ -142,6 +145,7 @@ export function CategorySidebar({function CategorySEOCard({ form }: { form: UseFormReturn<CategoryFormValues> }) {const { t } = useTranslation()+ const { errors } = form.formStateconst name = form.watch('name')const permalink = form.watch('permalink')const metaTitle = form.watch('meta_title')@@ -166,13 +170,23 @@ function CategorySEOCard({ form }: { form: UseFormReturn<CategoryFormValues> })<Field><FieldLabel htmlFor="category-permalink">{t('admin.fields.slug.label')}</FieldLabel>- <Input id="category-permalink" {...form.register('permalink')} />+ <Input+ id="category-permalink"+ aria-invalid={!!errors.permalink || undefined}+ {...form.register('permalink')}+ />+ <FieldError errors={[errors.permalink]} /></Field><Field><FieldLabel htmlFor="category-meta-title">{t('admin.fields.meta_title.label')}</FieldLabel>- <Input id="category-meta-title" {...form.register('meta_title')} />+ <Input+ id="category-meta-title"+ aria-invalid={!!errors.meta_title || undefined}+ {...form.register('meta_title')}+ />+ <FieldError errors={[errors.meta_title]} /></Field><Field><FieldLabel htmlFor="category-meta-description">@@ -181,8 +195,10 @@ function CategorySEOCard({ form }: { form: UseFormReturn<CategoryFormValues> })<Textareaid="category-meta-description"rows={3}+ aria-invalid={!!errors.meta_description || undefined}{...form.register('meta_description')}/>+ <FieldError errors={[errors.meta_description]} /></Field></CardContent></Card>diff --git a/packages/dashboard/src/components/spree/categories/category-products-card.tsx b/packages/dashboard/src/components/spree/categories/category-products-card.tsxindex 4e4ef045dd..60da69004f 100644--- a/packages/dashboard/src/components/spree/categories/category-products-card.tsx+++ b/packages/dashboard/src/components/spree/categories/category-products-card.tsx@@ -91,14 +91,32 @@ export function CategoryProductsCard({ categoryId }: { categoryId: string }) {useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),)+ const ids = useMemo(() => order.map((p) => p.id), [order])++ // Client-side quick filter over the assigned products. While a filter is+ // active, drag-reorder is disabled — reordering a filtered subset would+ // compute positions against the wrong neighbours.+ const trimmedQuery = query.trim().toLowerCase()+ const filtering = trimmedQuery.length > 0+ const visible = useMemo(+ () =>+ filtering ? order.filter((p) => (p.name ?? '').toLowerCase().includes(trimmedQuery)) : order,+ [order, filtering, trimmedQuery],+ )+ const visibleIds = useMemo(() => visible.map((p) => p.id), [visible])+function handleDragEnd(event: DragEndEvent) {const { active, over } = eventif (!over || active.id === over.id) returnconst from = order.findIndex((p) => p.id === active.id)const to = order.findIndex((p) => p.id === over.id)if (from === -1 || to === -1) return- setOrder((prev) => arrayMove(prev, from, to)) // optimistic- reposition.mutate({ productId: String(active.id), new_position: to })+ const previousOrder = order+ setOrder(arrayMove(order, from, to)) // optimistic+ reposition.mutate(+ { productId: String(active.id), new_position: to },+ { onError: () => setOrder(previousOrder) }, // roll back if the move fails+ )}function toggleSelected(id: string) {@@ -110,10 +128,17 @@ export function CategoryProductsCard({ categoryId }: { categoryId: string }) {})}+ // Operate only on the currently-visible (filtered) rows so "select all" never+ // pulls in hidden products that a later bulk-remove would delete unseen.function toggleAll() {- setSelected((prev) =>- prev.size === order.length ? new Set() : new Set(order.map((p) => p.id)),- )+ setSelected((prev) => {+ if (visibleIds.length > 0 && visibleIds.every((id) => prev.has(id))) {+ const next = new Set(prev)+ for (const id of visibleIds) next.delete(id)+ return next+ }+ return new Set([...prev, ...visibleIds])+ })}async function handleBulkRemove() {@@ -123,20 +148,7 @@ export function CategoryProductsCard({ categoryId }: { categoryId: string }) {setSelected(new Set())}- const ids = useMemo(() => order.map((p) => p.id), [order])-- // Client-side quick filter over the assigned products. While a filter is- // active, drag-reorder is disabled — reordering a filtered subset would- // compute positions against the wrong neighbours.- const trimmedQuery = query.trim().toLowerCase()- const filtering = trimmedQuery.length > 0- const visible = useMemo(- () =>- filtering ? order.filter((p) => (p.name ?? '').toLowerCase().includes(trimmedQuery)) : order,- [order, filtering, trimmedQuery],- )-- const allSelected = order.length > 0 && selected.size === order.length+ const allSelected = visibleIds.length > 0 && visibleIds.every((id) => selected.has(id))const hasSelection = selected.size > 0return (diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 7d31a2cefb..cdc1118cc6 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -2487,7 +2487,8 @@"column_product": "المنتج","filter_placeholder": "تصفية المنتجات…","no_matches": "لا توجد منتجات تطابق عامل التصفية."- }+ },+ "load_failed": "فشل تحميل الفئات. يرجى المحاولة مرة أخرى."}}}diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 2cbb419a04..5b6fc4ac86 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -2487,7 +2487,8 @@"column_product": "Produkt","filter_placeholder": "Produkte filtern…","no_matches": "Keine Produkte entsprechen dem Filter."- }+ },+ "load_failed": "Kategorien konnten nicht geladen werden. Bitte erneut versuchen."}}}diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 4340c5c915..c932f03061 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -2487,7 +2487,8 @@"column_product": "Product","filter_placeholder": "Filter products…","no_matches": "No products match your filter."- }+ },+ "load_failed": "Failed to load categories. Please try again."}}}diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex ed6e368f09..f55ec134eb 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -2487,7 +2487,8 @@"column_product": "Produit","filter_placeholder": "Filtrer les produits…","no_matches": "Aucun produit ne correspond au filtre."- }+ },+ "load_failed": "Échec du chargement des catégories. Veuillez réessayer."}}}diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 45247195b4..ca1ec6a4c4 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -2519,7 +2519,8 @@"column_product": "Produkt","filter_placeholder": "Filtruj produkty…","no_matches": "Żaden produkt nie pasuje do filtra."- }+ },+ "load_failed": "Nie udało się załadować kategorii. Spróbuj ponownie."}}}diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex f4e9494739..0d6ead614c 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -2487,7 +2487,8 @@"column_product": "商品","filter_placeholder": "筛选商品…","no_matches": "没有商品匹配筛选条件。"- }+ },+ "load_failed": "加载分类失败。请重试。"}}}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsxindex cc8fa75df7..c9064d9e12 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/$categoryId.tsx@@ -2,6 +2,7 @@ import { zodResolver } from '@hookform/resolvers/zod'import { SpreeError } from '@spree/admin-sdk'import { adminClient, mapSpreeErrorsToForm, PageHeader } from '@spree/dashboard-core'import {+ ErrorState,FormActions,ResourceLayout,Skeleton,@@ -28,10 +29,20 @@ export const Route = createFileRoute('/_authenticated/$storeId/products/categori})function CategoryDetailPage() {+ const { t } = useTranslation()const { storeId, categoryId } = Route.useParams()- const { data: category, isLoading } = useCategory(categoryId)+ const { data: category, isLoading, error, refetch } = useCategory(categoryId)- if (isLoading || !category) return <CategorySkeleton />+ if (isLoading) return <CategorySkeleton />+ if (error || !category) {+ return (+ <ErrorState+ title={t('admin.categories.load_failed')}+ error={error as Error | undefined}+ onRetry={() => refetch()}+ />+ )+ }return <CategoryDetail key={category.id} categoryId={categoryId} storeId={storeId} />}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsxindex a9e84c0312..c082ee9e09 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/categories/index.tsx@@ -31,7 +31,7 @@ function CategoriesPage() {const { t } = useTranslation()const { storeId } = Route.useParams()const navigate = useNavigate()- const { data, isLoading } = useCategories()+ const { data, isLoading, error } = useCategories()const deleteMutation = useDeleteCategory()const repositionMutation = useRepositionCategory()@@ -40,7 +40,12 @@ function CategoriesPage() {const [search, setSearch] = useState('')const deferredSearch = useDeferredValue(search)const searching = deferredSearch.trim().length > 0- const { data: searchData, isLoading: searchLoading } = useCategorySearch(deferredSearch)+ const {+ data: searchData,+ isLoading: searchLoading,+ error: searchError,+ } = useCategorySearch(deferredSearch)+ const activeError = searching ? searchError : errorfunction openCategory(category: Category) {navigate({@@ -96,7 +101,11 @@ function CategoriesPage() {</div></div><CardContent className="p-0">- {searching ? (+ {activeError ? (+ <p className="p-6 text-destructive" role="alert">+ {t('admin.categories.load_failed')}+ </p>+ ) : searching ? (searchLoading ? (<p className="p-6 text-muted-foreground">{t('admin.common.loading')}</p>) : (diff --git a/packages/dashboard/src/schemas/category.ts b/packages/dashboard/src/schemas/category.tsindex 9e178c81fb..e01965881f 100644--- a/packages/dashboard/src/schemas/category.ts+++ b/packages/dashboard/src/schemas/category.ts@@ -65,7 +65,9 @@ export function categoryToForm(category: Category): CategoryFormValues {export function categoryToParams(values: CategoryFormValues) {return {name: values.name,- parent_id: values.parent_id ?? undefined,+ // null keeps an existing child category at the top level on update; create+ // treats null/undefined the same (no parent).+ parent_id: values.parent_id,description: values.description,permalink: values.permalink,meta_title: values.meta_title,diff --git a/spree/api/app/controllers/spree/api/v3/admin/categories/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/categories/products_controller.rbindex f18f062ada..5cea675251 100644--- a/spree/api/app/controllers/spree/api/v3/admin/categories/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/categories/products_controller.rb@@ -36,7 +36,10 @@ module Spree# @product is already constrained to the category's scope, so a# classification always exists.def reposition- classification_for(@product).insert_at(params[:new_position].to_i + 1)+ position = integer_param(:new_position)+ return render_invalid_position if position.nil?++ classification_for(@product).insert_at(position + 1)head :no_contentenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rbindex 4b2a34bf54..8c5f682e00 100644--- a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb@@ -18,6 +18,9 @@ module Spreecategory = find_resourceauthorize! :update, category+ position = integer_param(:new_position)+ return render_invalid_position if position.nil?+# Operate on a base Taxon instance (unscoped): the Category default# i18n scope interferes with awesome_nested_set's lft/rgt reads, so# the move silently no-ops on a scoped instance.@@ -26,9 +29,9 @@ module Spreeif parent# move_to_child_with_index positions among the parent's children.- node.move_to_child_with_index(scope.find(parent.id), reposition_index(category, siblings_of(parent)))+ node.move_to_child_with_index(scope.find(parent.id), reposition_index(category, position, siblings_of(parent)))else- move_to_root_at_index(node, reposition_index(category, siblings_of(nil)))+ move_to_root_at_index(node, reposition_index(category, position, siblings_of(nil)))endrender json: serialize_resource(category.reload)rescue CollectiveIdea::Acts::NestedSet::Move::ImpossibleMove => e@@ -87,9 +90,9 @@ module Spree# sibling. The category can occupy indices 0..N where N is the count of# its *other* siblings; index N places it last.# @return [Integer]- def reposition_index(category, siblings)+ def reposition_index(category, position, siblings)others = siblings.where.not(id: category.id).count- params[:new_position].to_i.clamp(0, others)+ position.clamp(0, others)end# Positions the node at +index+ among the store's root categories.diff --git a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rbindex 15d364717e..7b2730e8a2 100644--- a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb@@ -39,6 +39,23 @@ module SpreeSpree::PrefixedId.prefixed_id?(id) ? Spree::PrefixedId.decode_prefixed_id(id) : idendend++ # Parses a strictly-integer param, returning nil for missing/blank/+ # non-integer values (so callers can reject rather than coerce to 0).+ # @return [Integer, nil]+ def integer_param(name)+ value = params[name]+ Integer(value, exception: false) if value.is_a?(Integer) || value.to_s.match?(/\A-?\d+\z/)+ end++ # Renders a 422 for a missing/invalid +new_position+.+ def render_invalid_position+ render_error(+ code: ERROR_CODES[:validation_error],+ message: Spree.t('api.errors.invalid_position', default: 'new_position must be an integer'),+ status: :unprocessable_content+ )+ endendendenddiff --git a/spree/api/config/locales/en.yml b/spree/api/config/locales/en.ymlindex 781bc7edfb..7cfa1ab00f 100644--- a/spree/api/config/locales/en.yml+++ b/spree/api/config/locales/en.yml@@ -20,6 +20,7 @@ en:payment:credit_over_limit: This payment can only be credited up to %{limit}. Please specify an amount less than or equal to this number.update_forbidden: This payment cannot be updated because it is %{state}.+ invalid_position: new_position must be an integerrecord_not_found: "%{model} not found"redirect_url_not_allowed: The redirect URL is not from an allowed origin for this store.resource_not_found: The resource you were looking for could not be found.diff --git a/spree/api/spec/controllers/spree/api/v3/admin/categories/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/categories/products_controller_spec.rbindex 27faff43a1..41b0e5ac6a 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/categories/products_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/categories/products_controller_spec.rb@@ -103,5 +103,15 @@ RSpec.describe Spree::Api::V3::Admin::Categories::ProductsController, type: :conexpect(response).to have_http_status(:no_content)expect(classified_ids).to eq([third.id, first.id, second.id])end++ it 'returns 422 for a missing new_position' do+ patch :reposition, params: { category_id: category.prefixed_id, id: third.prefixed_id }, as: :json+ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'returns 422 for a non-integer new_position' do+ patch :reposition, params: { category_id: category.prefixed_id, id: third.prefixed_id, new_position: 'abc' }, as: :json+ expect(response).to have_http_status(:unprocessable_content)+ endendenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rbindex 83075b43d7..e5dc2c5c1e 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rb@@ -251,5 +251,17 @@ RSpec.describe Spree::Api::V3::Admin::CategoriesController, type: :controller doexpect(ordered_trio.last).to eq(first.id)endend++ context 'invalid new_position' do+ it 'returns 422 for a missing new_position' do+ patch :reposition, params: { id: first.prefixed_id }, as: :json+ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'returns 422 for a non-integer new_position' do+ patch :reposition, params: { id: first.prefixed_id, new_position: 'abc' }, as: :json+ expect(response).to have_http_status(:unprocessable_content)+ end+ endendenddiff --git a/spree/core/app/models/spree/taxon.rb b/spree/core/app/models/spree/taxon.rbindex 09358c55e3..20ca7dbe36 100644--- a/spree/core/app/models/spree/taxon.rb+++ b/spree/core/app/models/spree/taxon.rb@@ -56,10 +56,16 @@ module Spree## Validations#- validates :name, presence: true, uniqueness: { scope: %i[parent_id taxonomy_id], case_sensitive: false }+ validates :name, presence: truevalidates :taxonomy, presence: true, if: :requires_taxonomy?validates :store, presence: true- validates :permalink, uniqueness: { case_sensitive: false, scope: %i[parent_id taxonomy_id] }+ # Taxonomy-backed taxons are unique within their taxonomy; taxonomy-less+ # categories (store-owned) are unique within their store, so two stores can+ # each have a top-level "Shoes".+ validates :name, uniqueness: { scope: %i[parent_id taxonomy_id], case_sensitive: false }, if: :requires_taxonomy?+ validates :permalink, uniqueness: { scope: %i[parent_id taxonomy_id], case_sensitive: false }, if: :requires_taxonomy?+ validates :name, uniqueness: { scope: %i[parent_id store_id], case_sensitive: false }, unless: :requires_taxonomy?+ validates :permalink, uniqueness: { scope: %i[parent_id store_id], case_sensitive: false }, unless: :requires_taxonomy?validates :hide_from_nav, inclusion: { in: [true, false] }validate :check_for_root, on: :createvalidate :parent_belongs_to_same_taxonomy@@ -88,6 +94,12 @@ module Spree# Capture the old parent before the move; recompute both chains after.before_move :capture_parent_before_moveafter_move :recalculate_products_count_after_move+ # Destroying a taxon drops its subtree's products from every ancestor's+ # inclusive count. Recompute the ancestors here (while the doomed subtree's+ # rows still exist) excluding that subtree, since the Classification destroy+ # callbacks can't help: classifications are removed via destroy_async, so+ # they outlive this callback and their taxon may already be gone.+ before_destroy :recalculate_ancestors_before_destroy, prepend: true## Scopes@@ -454,6 +466,19 @@ module Spreeself.class.recalculate_products_count(affected)end+ # Recomputes each ancestor's inclusive products_count as if this subtree were+ # already gone (its classifications are destroyed asynchronously, so they're+ # still present here). Excludes self_and_descendants from the count.+ def recalculate_ancestors_before_destroy+ doomed_ids = self_and_descendants.ids+ ancestors.each do |ancestor|+ remaining = Spree::Classification.+ where(taxon_id: ancestor.self_and_descendants.where.not(id: doomed_ids).select(:id)).+ distinct.count(:product_id)+ ancestor.update_column(:products_count, remaining) if ancestor.products_count != remaining+ end+ end+def check_for_rootreturn unless taxonomy.try(:root).present? && parent_id.nil?diff --git a/spree/core/lib/tasks/taxons.rake b/spree/core/lib/tasks/taxons.rakeindex ce063525f0..2a1a9deef4 100644--- a/spree/core/lib/tasks/taxons.rake+++ b/spree/core/lib/tasks/taxons.rake@@ -1,6 +1,6 @@namespace :spree donamespace :taxons do- desc 'Backfill spree_taxons.store_id from each taxon\'s taxonomy'+ desc 'Backfill spree_taxons.store_id from each taxon\'s taxonomy (or parent)'task backfill_store_id: :environment do |_t, _args|puts 'Backfilling taxon store_id from taxonomy...'@@ -9,6 +9,19 @@ namespace :spree doprint '.'end+ # Mirror Spree::Taxon#set_store: taxonomy-less rows inherit their parent's+ # store. Loop so a chain of unbackfilled ancestors resolves top-down.+ taxons = Spree::Taxon.arel_table+ parents = Spree::Taxon.arel_table.alias('parents')+ loop do+ updated = Spree::Taxon.unscoped.where(store_id: nil).where.not(parent_id: nil).+ joins("INNER JOIN #{taxons.name} #{parents.name} ON #{parents.name}.id = #{taxons.name}.parent_id").+ where.not(parents[:store_id].eq(nil)).+ update_all("store_id = #{parents.name}.store_id")+ print '.'+ break if updated.zero?+ end+puts "\nDone!"enddiff --git a/spree/core/spec/models/spree/category_spec.rb b/spree/core/spec/models/spree/category_spec.rbindex 8d2c203ff2..7d538b939e 100644--- a/spree/core/spec/models/spree/category_spec.rb+++ b/spree/core/spec/models/spree/category_spec.rb@@ -3,6 +3,49 @@ require 'spec_helper'RSpec.describe Spree::Category, type: :model dolet(:store) { @default_store }+ describe 'uniqueness across stores' do+ it 'allows the same top-level name/permalink in different stores' do+ other = create(:store)+ described_class.create!(name: 'Shoes', store: store)+ duplicate = described_class.new(name: 'Shoes', store: other)++ expect(duplicate).to be_valid+ end++ it 'still rejects a duplicate name within the same store' do+ described_class.create!(name: 'Shoes', store: store)+ duplicate = described_class.new(name: 'Shoes', store: store)++ expect(duplicate).not_to be_valid+ end+ end++ describe 'products_count on destroy' do+ it 'decrements ancestors when a subcategory is destroyed' do+ parent = described_class.create!(name: 'Electronics', store: store)+ child = described_class.create!(name: 'Phones', parent: parent)+ Spree::Classification.create!(taxon: child, product: create(:product, stores: [store]))+ expect(parent.reload.products_count).to eq(1)++ child.destroy++ expect(parent.reload.products_count).to eq(0)+ end++ it 'keeps the count from surviving siblings' do+ parent = described_class.create!(name: 'Electronics', store: store)+ phones = described_class.create!(name: 'Phones', parent: parent)+ laptops = described_class.create!(name: 'Laptops', parent: parent)+ Spree::Classification.create!(taxon: phones, product: create(:product, stores: [store]))+ Spree::Classification.create!(taxon: laptops, product: create(:product, stores: [store]))+ expect(parent.reload.products_count).to eq(2)++ phones.destroy++ expect(parent.reload.products_count).to eq(1)+ end+ end+describe 'creation without a taxonomy' doit 'creates a parentless, store-owned top-level category' docategory = described_class.new(name: 'Kitchen', store: store)