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 the dashboard CMD+K palette complete and extensible (#14186)

Damian Legawiec88cfdf5cdd80
diff --git a/packages/dashboard-core/src/hooks/use-global-search.ts b/packages/dashboard-core/src/hooks/use-global-search.ts
index a479c9ade0..b3e474f5fb 100644
--- a/packages/dashboard-core/src/hooks/use-global-search.ts
+++ b/packages/dashboard-core/src/hooks/use-global-search.ts
@@ -1,6 +1,9 @@
-import { useQuery } from '@tanstack/react-query'
+import { useQueries } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
-import { adminClient } from '../client'
+import { useAuth } from '../hooks/use-auth'
+import { type SearchEntry, useSearchEntries } from '../lib/search-registry'
+import { usePermissions } from '../providers/permission-provider'
+import { useStore } from '../providers/store-provider'
const RESULT_LIMIT = 5
const MIN_QUERY_LENGTH = 2
@@ -8,49 +11,59 @@ const DEBOUNCE_MS = 200
const GC_TIME_MS = 60_000
const STALE_TIME_MS = 30_000
+export interface SearchGroup {
+ entry: SearchEntry
+ items: unknown[]
+}
+
/**
- * Three parallel `?q[search]=…&limit=5` queries — one per resource. Each model
- * defines a `search` Ransack scope that does multi-field LIKE matching, so we
- * pass a single `search` param and let the server decide what to match.
+ * One parallel `?q[search]=…&limit=5` query per registered, permitted search
+ * entry — products, orders, customers, promotions, and anything a plugin adds.
+ * Each resource defines a `search` Ransack scope server-side that does
+ * multi-field LIKE matching, so we pass a single `search` param and let the
+ * server decide what to match.
*
* The query is debounced so a fast typist doesn't fan out a wave of in-flight
- * requests; results are cached briefly so backspace feels instant but they
- * don't pile up across long sessions.
+ * requests; results are cached briefly (and scoped by user + store) so backspace
+ * feels instant but they don't pile up or leak across users or stores.
*/
export function useGlobalSearch(rawQuery: string) {
- const query = useDebouncedValue(rawQuery, DEBOUNCE_MS)
- const enabled = query.trim().length >= MIN_QUERY_LENGTH
+ // Trim once: the cache key and the server query must match what `enabled`
+ // gates on, or " hello" and "hello" fan out as separate cache entries and the
+ // stray space leaks into the `cont` predicate (`LIKE %hello %`), missing rows.
+ const query = useDebouncedValue(rawQuery, DEBOUNCE_MS).trim()
+ const enabled = query.length >= MIN_QUERY_LENGTH
+ const entries = useSearchEntries()
+ const { permissions, isLoading: permissionsLoading } = usePermissions()
+ const { storeId } = useStore()
+ const { user } = useAuth()
- const products = useQuery({
- queryKey: ['cmdk', 'products', query],
- queryFn: () => adminClient.products.list({ search: query, limit: RESULT_LIMIT }),
- enabled,
- gcTime: GC_TIME_MS,
- staleTime: STALE_TIME_MS,
- })
+ const permitted = entries.filter((e) => !e.subject || permissions.can('read', e.subject))
- const orders = useQuery({
- queryKey: ['cmdk', 'orders', query],
- queryFn: () => adminClient.orders.list({ search: query, limit: RESULT_LIMIT }),
- enabled,
- gcTime: GC_TIME_MS,
- staleTime: STALE_TIME_MS,
+ const results = useQueries({
+ queries: permitted.map((entry) => ({
+ // Scope by user so a logout→login on the same store can't serve the
+ // previous user's cached results from React Query.
+ queryKey: ['cmdk', user?.id, storeId, entry.key, query],
+ queryFn: () => entry.fetch(query, RESULT_LIMIT),
+ enabled,
+ gcTime: GC_TIME_MS,
+ staleTime: STALE_TIME_MS,
+ })),
})
- const customers = useQuery({
- queryKey: ['cmdk', 'customers', query],
- queryFn: () => adminClient.customers.list({ search: query, limit: RESULT_LIMIT }),
- enabled,
- gcTime: GC_TIME_MS,
- staleTime: STALE_TIME_MS,
- })
+ const groups: SearchGroup[] = permitted
+ .map((entry, i) => ({ entry, items: results[i]?.data ?? [] }))
+ .filter((g) => g.items.length > 0)
return {
- products: products.data?.data ?? [],
- orders: orders.data?.data ?? [],
- customers: customers.data?.data ?? [],
- isLoading: enabled && (products.isLoading || orders.isLoading || customers.isLoading),
+ groups,
+ // Treat the permission fetch as loading: until rules land, every gated
+ // entry is filtered out and no queries run, so without this the palette
+ // would flash "no results" before search has effectively started.
+ isLoading: enabled && (permissionsLoading || results.some((r) => r.isLoading)),
isEnabled: enabled,
+ hasResults: groups.length > 0,
}
}
diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.ts
index 9495b1d724..f7860cf086 100644
--- a/packages/dashboard-core/src/index.ts
+++ b/packages/dashboard-core/src/index.ts
@@ -67,6 +67,7 @@ export * from './lib/nav-registry'
export * from './lib/permissions'
export * from './lib/query-client'
export * from './lib/query-keys'
+export * from './lib/search-registry'
export * from './lib/settings-nav-registry'
export * from './lib/slot-registry'
export * from './lib/table-registry'
diff --git a/packages/dashboard-core/src/lib/search-registry.ts b/packages/dashboard-core/src/lib/search-registry.ts
new file mode 100644
index 0000000000..c6c71491ca
--- /dev/null
+++ b/packages/dashboard-core/src/lib/search-registry.ts
@@ -0,0 +1,129 @@
+import type { ReactNode } from 'react'
+import { useSyncExternalStore } from 'react'
+import type { SubjectName } from './permissions'
+
+/**
+ * Registry for the command-palette global resource search. Mirrors
+ * `nav-registry.ts`: a module-singleton populated at app boot by side-effect
+ * modules (see `@/search/default` in the dashboard app), read reactively via
+ * `useSearchEntries`.
+ *
+ * Each entry teaches the palette how to search one resource type: how to fetch
+ * matches, how to render a result row, and where a row navigates. Adding a new
+ * searchable resource is one `searchRegistry.add(...)` call — no edits to the
+ * palette component or the search hook. Plugins extend search the same way they
+ * extend the nav.
+ *
+ * The result type is erased at the registry boundary (`unknown`): the palette
+ * never inspects a result directly, it only hands each one back to the entry's
+ * own `renderRow`/`getRoute`/`getKey`, which are typed against the resource.
+ * Use `defineSearchEntry` to keep that wiring type-safe at the call site.
+ */
+
+export interface SearchResultRow {
+ /** cmdk value — must be unique across the whole list; prefix with the entry key. */
+ value: string
+ /** Row contents rendered inside the `CommandItem`. */
+ content: ReactNode
+}
+
+export interface SearchEntry<T = unknown> {
+ /** Stable identifier — register/remove key, React key, and result-value prefix. */
+ key: string
+ /** i18n key for the group heading (resolved with `t` at render time). */
+ headingKey: string
+ /** CanCanCan subject gating both the query and the rendered group. Omit for always-on. */
+ subject?: SubjectName
+ /**
+ * Lower numbers render first. Built-ins use 100/200/300… so plugins can slot
+ * between them. Also orders the parallel queries, purely cosmetically.
+ */
+ position?: number
+ /**
+ * Fetch up to `limit` matches for `query`. Returns the raw resource records;
+ * the palette passes each back through this entry's `renderRow`/`getRoute`.
+ */
+ fetch: (query: string, limit: number) => Promise<T[]>
+ /** Stable React key for a single result (typically the prefixed `id`). */
+ getKey: (item: T) => string
+ /** Render one result row's inner content (icon/thumbnail + label + badges). */
+ renderRow: (item: T) => ReactNode
+ /** Resolve the destination for a clicked result, given the active store. */
+ getRoute: (item: T, storeId: string) => { to: string }
+}
+
+interface SearchMutator {
+ /** Register an entry. Throws if the key is already registered. */
+ add<T>(entry: SearchEntry<T>): void
+ /** Remove an entry by key. No-op when missing. */
+ remove(key: string): void
+ /** Patch an existing entry. Throws if the key is missing. */
+ update<T>(key: string, patch: Partial<Omit<SearchEntry<T>, 'key'>>): void
+}
+
+const entries: SearchEntry[] = []
+const listeners = new Set<() => void>()
+let snapshotCache: SearchEntry[] | null = null
+
+function notify() {
+ snapshotCache = null
+ for (const l of listeners) l()
+}
+
+export const searchRegistry: SearchMutator = {
+ add(entry) {
+ if (entries.some((e) => e.key === entry.key)) {
+ throw new Error(
+ `Search entry "${entry.key}" already registered. Use searchRegistry.update().`,
+ )
+ }
+ entries.push(entry as SearchEntry)
+ notify()
+ },
+ remove(key) {
+ const i = entries.findIndex((e) => e.key === key)
+ if (i === -1) return
+ entries.splice(i, 1)
+ notify()
+ },
+ update(key, patch) {
+ const e = entries.find((x) => x.key === key)
+ if (!e) throw new Error(`Search entry "${key}" not found.`)
+ Object.assign(e, patch)
+ notify()
+ },
+}
+
+function subscribe(listener: () => void): () => void {
+ listeners.add(listener)
+ return () => {
+ listeners.delete(listener)
+ }
+}
+
+function getSnapshot(): SearchEntry[] {
+ if (!snapshotCache) {
+ snapshotCache = [...entries].sort((a, b) => (a.position ?? 100) - (b.position ?? 100))
+ }
+ return snapshotCache
+}
+
+/** Reactively read the sorted search entries. Re-renders on registry mutation. */
+export function useSearchEntries(): SearchEntry[] {
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
+}
+
+/**
+ * Identity helper that infers `T` from `fetch`/`getKey`/`renderRow`/`getRoute`
+ * so the callbacks are typed against the resource at the registration site,
+ * while the registry stores the erased `SearchEntry`.
+ */
+export function defineSearchEntry<T>(entry: SearchEntry<T>): SearchEntry<T> {
+ return entry
+}
+
+/** Test-only: clear the registry. */
+export function __resetSearchRegistry(): void {
+ entries.length = 0
+ notify()
+}
diff --git a/packages/dashboard/src/components/spree/command-palette/command-palette.tsx b/packages/dashboard/src/components/spree/command-palette/command-palette.tsx
index df12954c9d..6c13089fd6 100644
--- a/packages/dashboard/src/components/spree/command-palette/command-palette.tsx
+++ b/packages/dashboard/src/components/spree/command-palette/command-palette.tsx
@@ -1,4 +1,16 @@
-import { useAuth, useCommandPalette, useGlobalSearch, useTranslation } from '@spree/dashboard-core'
+import {
+ type NavEntry,
+ type Permissions,
+ type SearchGroup,
+ type SettingsNavEntry,
+ useAuth,
+ useCommandPalette,
+ useGlobalSearch,
+ useNavEntries,
+ usePermissions,
+ useSettingsNav,
+ useTranslation,
+} from '@spree/dashboard-core'
import {
Command,
CommandEmpty,
@@ -12,19 +24,10 @@ import {
DialogDescription,
DialogHeader,
DialogTitle,
- StatusBadge,
} from '@spree/dashboard-ui'
import { useNavigate, useParams } from '@tanstack/react-router'
-import {
- HomeIcon,
- Loader2Icon,
- LogOutIcon,
- PackageIcon,
- ShoppingCartIcon,
- TagIcon,
- UsersIcon,
-} from 'lucide-react'
-import { type ReactNode, useState } from 'react'
+import { Loader2Icon, LogOutIcon, type LucideIcon, PackageIcon, SettingsIcon } from 'lucide-react'
+import { type ReactNode, useMemo, useState } from 'react'
export function CommandPalette() {
const { open, setOpen } = useCommandPalette()
@@ -41,25 +44,34 @@ function CommandPaletteContent({ setOpen }: { setOpen: (open: boolean) => void }
const storeId = rawStoreId ?? 'default'
const navigate = useNavigate()
const { logout } = useAuth()
+ const { permissions } = usePermissions()
+ const { main, bottom } = useNavEntries()
+ const settingsNav = useSettingsNav()
const [input, setInput] = useState('')
- const { products, orders, customers, isLoading, isEnabled } = useGlobalSearch(input)
+ const { groups, hasResults, isLoading, isEnabled } = useGlobalSearch(input)
const close = () => {
setOpen(false)
setInput('')
}
+ // Flatten every nav + settings entry the user can reach into one searchable
+ // list so the palette stays in lockstep with the sidebars — no hardcoded
+ // subset to drift out of date. Permission filtering mirrors app-sidebar.tsx
+ // and settings-sidebar.tsx. Recomputed only when the registries, permissions,
+ // store, or translations change — not on every keystroke.
+ const gotoCommands = useMemo(
+ () => buildGotoCommands({ main, bottom, settingsNav, permissions, storeId, t }),
+ [main, bottom, settingsNav, permissions, storeId, t],
+ )
+
const q = input.trim().toLowerCase()
const matches = (label: string) => !q || label.toLowerCase().includes(q)
- const gotoItems = [
- { label: t('admin.nav.home'), icon: HomeIcon, to: '/$storeId' as const },
- { label: t('admin.nav.products'), icon: PackageIcon, to: '/$storeId/products' as const },
- { label: t('admin.nav.orders'), icon: ShoppingCartIcon, to: '/$storeId/orders' as const },
- { label: t('admin.nav.customers'), icon: UsersIcon, to: '/$storeId/customers' as const },
- ].filter((c) => matches(t('admin.components.command_palette.goto_label', { label: c.label })))
+ const gotoItems = gotoCommands.filter((c) =>
+ matches(t('admin.components.command_palette.goto_label', { label: c.label })),
+ )
const showLogout = matches(t('admin.auth.logout'))
- const hasResults = products.length > 0 || orders.length > 0 || customers.length > 0
return (
<Dialog
@@ -80,7 +92,7 @@ function CommandPaletteContent({ setOpen }: { setOpen: (open: boolean) => void }
// link, painting it with a misleading focus ring.
finalFocus={false}
>
- {/* Server's `search` Ransack scope filters resources; static commands
+ {/* The server filters resource results via Ransack; static commands
are pre-filtered in JS. Either way, cmdk shouldn't filter again. */}
<Command shouldFilter={false}>
<CommandInput
@@ -92,92 +104,36 @@ function CommandPaletteContent({ setOpen }: { setOpen: (open: boolean) => void }
<SearchStatus
isEnabled={isEnabled}
isLoading={isLoading}
- hasResults={hasResults}
+ // "No results" must account for goto/logout commands too, not just
+ // resource search — a query can match a nav command while the API
+ // search returns nothing.
+ hasResults={hasResults || gotoItems.length > 0 || showLogout}
query={input}
/>
- {products.length > 0 && (
- <CommandGroup heading={t('admin.nav.products')}>
- {products.map((p) => (
- <CommandItem
- key={p.id}
- value={`product-${p.id}`}
- onSelect={() => {
- close()
- navigate({
- to: '/$storeId/products/$productId',
- params: { storeId, productId: p.id },
- })
- }}
- >
- <ProductIconOrThumbnail thumbnailUrl={p.primary_media?.mini_url ?? null} />
- <span className="flex-1 truncate">{p.name}</span>
- <StatusBadge status={p.status} />
- </CommandItem>
- ))}
- </CommandGroup>
- )}
-
- {orders.length > 0 && (
- <CommandGroup heading={t('admin.nav.orders')}>
- {orders.map((o) => (
- <CommandItem
- key={o.id}
- value={`order-${o.id}`}
- onSelect={() => {
- close()
- navigate({
- to: '/$storeId/orders/$orderId',
- params: { storeId, orderId: o.id },
- })
- }}
- >
- <ShoppingCartIcon />
- <span className="flex-1 truncate">
- <span className="font-mono">{o.number}</span>
- {o.email && <span className="ml-2 text-muted-foreground">{o.email}</span>}
- </span>
- {o.payment_status && <StatusBadge status={o.payment_status} />}
- </CommandItem>
- ))}
- </CommandGroup>
- )}
-
- {customers.length > 0 && (
- <CommandGroup heading={t('admin.nav.customers')}>
- {customers.map((c) => (
- <CommandItem
- key={c.id}
- value={`customer-${c.id}`}
- onSelect={() => {
- close()
- navigate({
- to: '/$storeId/customers/$customerId',
- params: { storeId, customerId: c.id },
- })
- }}
- >
- <UsersIcon />
- <span className="flex-1 truncate">
- {c.full_name || c.email}
- {c.full_name && <span className="ml-2 text-muted-foreground">{c.email}</span>}
- </span>
- </CommandItem>
- ))}
- </CommandGroup>
- )}
+ {groups.map((group) => (
+ <ResourceGroup
+ key={group.entry.key}
+ group={group}
+ storeId={storeId}
+ onNavigate={(to) => {
+ close()
+ navigate({ to })
+ }}
+ />
+ ))}
{hasResults && (gotoItems.length > 0 || showLogout) && <CommandSeparator />}
{gotoItems.length > 0 && (
<CommandGroup heading={t('admin.components.command_palette.goto')}>
- {gotoItems.map(({ label, icon: Icon, to }) => (
+ {gotoItems.map(({ key, label, icon: Icon, url }) => (
<CommandItem
- key={to}
- value={`goto-${label}`}
+ key={key}
+ value={`goto-${key}`}
onSelect={() => {
close()
- navigate({ to, params: { storeId } })
+ navigate({ to: url })
}}
>
<Icon />
@@ -214,6 +170,125 @@ function CommandPaletteContent({ setOpen }: { setOpen: (open: boolean) => void }
// Helpers
// ---------------------------------------------------------------------------
+interface GotoCommand {
+ /** Stable key — registry entry key, used as the React key + cmdk value. */
+ key: string
+ /** Resolved, translated label shown in the list. */
+ label: string
+ /** Icon — falls back to a section-appropriate default when the entry has none. */
+ icon: LucideIcon
+ /** Fully-built href including `/$storeId`, ready to hand to `navigate`. */
+ url: string
+}
+
+/** True when the user may `read` the entry's subject (no subject ⇒ always visible). */
+function canRead(subject: NavEntry['subject'], permissions: Permissions): boolean {
+ return !subject || permissions.can('read', subject)
+}
+
+/**
+ * Flatten the main nav (with children), the bottom nav, and every settings
+ * entry into a single permission-filtered command list. Mirrors the path
+ * building and permission rules used by the two sidebars so the palette can
+ * reach every page they can.
+ */
+function buildGotoCommands({
+ main,
+ bottom,
+ settingsNav,
+ permissions,
+ storeId,
+ t,
+}: {
+ main: NavEntry[]
+ bottom: NavEntry[]
+ settingsNav: ReturnType<typeof useSettingsNav>
+ permissions: Permissions
+ storeId: string
+ t: ReturnType<typeof useTranslation>['t']
+}): GotoCommand[] {
+ const commands: GotoCommand[] = []
+ const pathFor = (path: string) => (path === '/' ? `/${storeId}` : `/${storeId}${path}`)
+
+ // Main + bottom nav, including nested children. Keys are namespaced per
+ // registry because raw keys are only unique within their own registry —
+ // merging them risks duplicate React keys / cmdk values across sections.
+ for (const entry of [...main, ...bottom]) {
+ // Mirror the sidebar: when the parent subject is denied, the whole subtree
+ // (parent + children) is hidden, so don't surface its children either.
+ if (!canRead(entry.subject, permissions)) continue
+ commands.push({
+ key: `nav:${entry.key}`,
+ label: entry.label,
+ icon: entry.icon ?? PackageIcon,
+ url: pathFor(entry.path),
+ })
+ for (const child of entry.children ?? []) {
+ if (!canRead(child.subject, permissions)) continue
+ commands.push({
+ key: `nav:${entry.key}:${child.key}`,
+ label: child.label,
+ // Children render no icon in the sidebar; inherit the parent's so the
+ // palette row still has a glyph.
+ icon: entry.icon ?? PackageIcon,
+ url: pathFor(child.path),
+ })
+ }
+ }
+
+ // Settings pages live under `/$storeId/settings`. Labels resolve from
+ // `labelKey` (built-ins) or the literal `label` (plugins).
+ for (const entry of settingsNav.all) {
+ // `comingSoon` pages are disabled in the sidebar — keep them unreachable
+ // from the palette too.
+ if (entry.comingSoon) continue
+ if (!canRead(entry.subject, permissions)) continue
+ commands.push({
+ key: `settings:${entry.key}`,
+ label: settingsLabel(entry, t),
+ icon: entry.icon ?? SettingsIcon,
+ url: `/${storeId}/settings${entry.path}`,
+ })
+ }
+
+ return commands
+}
+
+function settingsLabel(entry: SettingsNavEntry, t: ReturnType<typeof useTranslation>['t']): string {
+ return entry.labelKey ? t(entry.labelKey) : (entry.label ?? entry.key)
+}
+
+/**
+ * Renders one resource's search results. The heading, row contents, result key,
+ * and destination all come from the registered `SearchEntry`, so the palette
+ * stays agnostic to which resources are searchable.
+ */
+function ResourceGroup({
+ group,
+ storeId,
+ onNavigate,
+}: {
+ group: SearchGroup
+ storeId: string
+ onNavigate: (to: string) => void
+}): ReactNode {
+ const { t } = useTranslation()
+ const { entry, items } = group
+ return (
+ <CommandGroup heading={t(entry.headingKey)}>
+ {items.map((item) => (
+ <CommandItem
+ key={`${entry.key}-${entry.getKey(item)}`}
+ value={`${entry.key}-${entry.getKey(item)}`}
+ onSelect={() => onNavigate(entry.getRoute(item, storeId).to)}
+ >
+ {entry.renderRow(item)}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ )
+}
+
function SearchStatus({
isEnabled,
isLoading,
@@ -244,15 +319,3 @@ function SearchStatus({
}
return null
}
-
-function ProductIconOrThumbnail({ thumbnailUrl }: { thumbnailUrl: string | null }): ReactNode {
- if (!thumbnailUrl) return <TagIcon />
- return (
- <img
- src={thumbnailUrl}
- alt=""
- className="size-5 shrink-0 rounded object-cover"
- loading="lazy"
- />
- )
-}
diff --git a/packages/dashboard/src/main.tsx b/packages/dashboard/src/main.tsx
index b2fa681968..9ee0c85edd 100644
--- a/packages/dashboard/src/main.tsx
+++ b/packages/dashboard/src/main.tsx
@@ -4,12 +4,14 @@ import { RouterProvider } from '@tanstack/react-router'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
// Side-effect imports: bootstrap i18next via dashboard-core (base namespace)
-// and merge the app's resource bundle; register the app's nav entries against
-// the nav-registry. Both must run before any chrome component reads from those
-// registries — i.e. before @/router. (Plugin entries follow the same pattern.)
+// and merge the app's resource bundle; register the app's nav and command-palette
+// search entries against their registries. All must run before any chrome
+// component reads from those registries — i.e. before @/router. (Plugin entries
+// follow the same pattern.)
import '@/i18n-setup'
import '@/nav/default'
import '@/nav/settings'
+import '@/search/default'
import { AuthProvider, PermissionProvider, queryClient } from '@spree/dashboard-core'
import { ThemeProvider } from '@spree/dashboard-ui'
import { router } from '@/router'
diff --git a/packages/dashboard/src/search/default.tsx b/packages/dashboard/src/search/default.tsx
new file mode 100644
index 0000000000..ea862757a3
--- /dev/null
+++ b/packages/dashboard/src/search/default.tsx
@@ -0,0 +1,108 @@
+import type { Customer, Order, Product, Promotion } from '@spree/admin-sdk'
+import { adminClient, defineSearchEntry, Subject, searchRegistry } from '@spree/dashboard-core'
+import { StatusBadge } from '@spree/dashboard-ui'
+import { ShoppingCartIcon, TagIcon, TicketPercentIcon, UsersIcon } from 'lucide-react'
+
+// Each entry teaches the command palette how to search one resource: how to
+// fetch matches, render a result row, and where a row navigates. Resources are
+// matched server-side via Ransack predicates — no dedicated backend `search`
+// scope required; the predicate is declared right here in `fetch`. Plugins add
+// searchable resources the same way (import `searchRegistry`, call `add`).
+
+searchRegistry.add(
+ defineSearchEntry<Product>({
+ key: 'products',
+ headingKey: 'admin.nav.products',
+ subject: Subject.Product,
+ position: 100,
+ fetch: (search, limit) => adminClient.products.list({ search, limit }).then((r) => r.data),
+ getKey: (p) => p.id,
+ getRoute: (p, storeId) => ({ to: `/${storeId}/products/${p.id}` }),
+ renderRow: (p) => (
+ <>
+ <ProductIconOrThumbnail thumbnailUrl={p.primary_media?.mini_url ?? null} />
+ <span className="flex-1 truncate">{p.name}</span>
+ <StatusBadge status={p.status} />
+ </>
+ ),
+ }),
+)
+
+searchRegistry.add(
+ defineSearchEntry<Order>({
+ key: 'orders',
+ headingKey: 'admin.nav.orders',
+ subject: Subject.Order,
+ position: 200,
+ fetch: (search, limit) => adminClient.orders.list({ search, limit }).then((r) => r.data),
+ getKey: (o) => o.id,
+ getRoute: (o, storeId) => ({ to: `/${storeId}/orders/${o.id}` }),
+ renderRow: (o) => (
+ <>
+ <ShoppingCartIcon />
+ <span className="flex-1 truncate">
+ <span className="font-mono">{o.number}</span>
+ {o.email && <span className="ml-2 text-muted-foreground">{o.email}</span>}
+ </span>
+ {o.payment_status && <StatusBadge status={o.payment_status} />}
+ </>
+ ),
+ }),
+)
+
+searchRegistry.add(
+ defineSearchEntry<Customer>({
+ key: 'customers',
+ headingKey: 'admin.nav.customers',
+ subject: Subject.Customer,
+ position: 300,
+ fetch: (search, limit) => adminClient.customers.list({ search, limit }).then((r) => r.data),
+ getKey: (c) => c.id,
+ getRoute: (c, storeId) => ({ to: `/${storeId}/customers/${c.id}` }),
+ renderRow: (c) => (
+ <>
+ <UsersIcon />
+ <span className="flex-1 truncate">
+ {c.full_name || c.email}
+ {c.full_name && <span className="ml-2 text-muted-foreground">{c.email}</span>}
+ </span>
+ </>
+ ),
+ }),
+)
+
+searchRegistry.add(
+ defineSearchEntry<Promotion>({
+ key: 'promotions',
+ headingKey: 'admin.nav.promotions',
+ subject: Subject.Promotion,
+ position: 400,
+ // No backend `search` scope — match name or coupon code via a Ransack
+ // `cont` predicate (both columns are whitelisted on Spree::Promotion).
+ fetch: (query, limit) =>
+ adminClient.promotions.list({ name_or_code_cont: query, limit }).then((r) => r.data),
+ getKey: (p) => p.id,
+ getRoute: (p, storeId) => ({ to: `/${storeId}/promotions/${p.id}` }),
+ renderRow: (p) => (
+ <>
+ <TicketPercentIcon />
+ <span className="flex-1 truncate">{p.name}</span>
+ {p.code && (
+ <span className="ml-2 shrink-0 font-mono text-xs text-muted-foreground">{p.code}</span>
+ )}
+ </>
+ ),
+ }),
+)
+
+function ProductIconOrThumbnail({ thumbnailUrl }: { thumbnailUrl: string | null }) {
+ if (!thumbnailUrl) return <TagIcon />
+ return (
+ <img
+ src={thumbnailUrl}
+ alt=""
+ className="size-5 shrink-0 rounded object-cover"
+ loading="lazy"
+ />
+ )
+}
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb
index ca27841ecf..587a2b60f5 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/promotions_controller_spec.rb
@@ -17,6 +17,19 @@ RSpec.describe Spree::Api::V3::Admin::PromotionsController, type: :controller do
expect(json_response['data']).to be_an(Array)
expect(json_response['data'].map { |p| p['id'] }).to include(promotion.prefixed_id)
end
+
+ # Backs the admin command-palette search, which queries promotions via the
+ # `name_or_code_cont` Ransack predicate.
+ it 'filters by name or code via name_or_code_cont' do
+ summer = create(:promotion, name: 'Summer Sale', code: 'SUMMER10')
+ winter = create(:promotion, name: 'Winter Sale', code: 'WINTER20')
+
+ get :index, params: { q: { name_or_code_cont: 'summer' } }, as: :json
+
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).to include(summer.prefixed_id)
+ expect(ids).not_to include(winter.prefixed_id)
+ end
end
describe 'GET #show' do
diff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rb
index e0dc062568..5dbaad570a 100644
--- a/spree/core/app/models/spree/promotion.rb
+++ b/spree/core/app/models/spree/promotion.rb
@@ -86,7 +86,9 @@ module Spree
#
# Ransack
#
- self.whitelisted_ransackable_attributes = ['path', 'promotion_category_id', 'code', 'starts_at', 'expires_at']
+ # `name` is whitelisted so the admin global search / command palette can
+ # filter via the `name_or_code_cont` predicate without a dedicated scope.
+ self.whitelisted_ransackable_attributes = ['name', 'path', 'promotion_category_id', 'code', 'starts_at', 'expires_at']
self.whitelisted_ransackable_associations = %w[coupon_codes]
def self.with_coupon_code(coupon_code)
diff --git a/spree/core/spec/models/spree/promotion_spec.rb b/spree/core/spec/models/spree/promotion_spec.rb
index b8bde71b7e..7b7834e0b5 100644
--- a/spree/core/spec/models/spree/promotion_spec.rb
+++ b/spree/core/spec/models/spree/promotion_spec.rb
@@ -152,6 +152,19 @@ describe Spree::Promotion, type: :model do
end
end
+ describe 'Ransack' do
+ # `name` backs the admin global search's `name_or_code_cont` predicate.
+ it 'allows filtering by name' do
+ summer = create(:promotion, name: 'Summer Sale', code: 'SUMMER10')
+ winter = create(:promotion, name: 'Winter Sale', code: 'WINTER20')
+
+ result = described_class.ransack('name_or_code_cont' => 'summer').result
+
+ expect(result).to include(summer)
+ expect(result).not_to include(winter)
+ end
+ end
+
describe '#destroy' do
let(:promotion) { create(:promotion, name: 'delete me', kind: :automatic) }