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 catalog product picker: pagination, select-all, exclude existing members (#14550)

Damian Legawiec236f52a0f5ba
diff --git a/packages/dashboard-core/src/components/resource-picker-sheet.tsx b/packages/dashboard-core/src/components/resource-picker-sheet.tsx
index 9ef1b1837a..541ef454c7 100644
--- a/packages/dashboard-core/src/components/resource-picker-sheet.tsx
+++ b/packages/dashboard-core/src/components/resource-picker-sheet.tsx
@@ -1,6 +1,7 @@
import {
Button,
Checkbox,
+ type PaginationMeta,
SearchInput,
Sheet,
SheetContent,
@@ -12,13 +13,21 @@ import {
} from '@spree/dashboard-ui'
import { Loader2Icon } from '@spree/dashboard-ui/icons'
import { useQuery } from '@tanstack/react-query'
-import { useDeferredValue, useMemo, useState } from 'react'
+import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
export interface PickerOption {
id: string
}
+/** One page of async picker search results, optionally with list pagination metadata. */
+export interface ResourcePickerSearchResult<T extends PickerOption> {
+ /** Rows returned for the requested page. */
+ data: T[]
+ /** Total match count and page cursors when the search is paginated. */
+ meta?: PaginationMeta
+}
+
export interface ResourcePickerSheetProps<T extends PickerOption> {
open: boolean
onOpenChange: (open: boolean) => void
@@ -26,8 +35,8 @@ export interface ResourcePickerSheetProps<T extends PickerOption> {
selectedIds: string[]
/** Called with the freshly-picked IDs (excludes `selectedIds`) when the user confirms. */
onConfirm: (ids: string[], options: T[]) => void | Promise<void>
- /** Paginated async search. Called with the trimmed query (empty = initial list). */
- search: (query: string) => Promise<{ data: T[] }>
+ /** Paginated async search. Called with the trimmed query (empty = initial list) and page. */
+ search: (query: string, page: number) => Promise<ResourcePickerSearchResult<T>>
getOptionLabel: (option: T) => string
/** Optional thumbnail URL shown as an avatar. */
getOptionImageUrl?: (option: T) => string | null | undefined
@@ -75,20 +84,53 @@ export function ResourcePickerSheet<T extends PickerOption>({
const deferredInput = useDeferredValue(input)
const trimmedQuery = deferredInput.trim()
+ const [page, setPage] = useState(1)
+ const [loadedResults, setLoadedResults] = useState<T[]>([])
+ const [currentPageResults, setCurrentPageResults] = useState<T[]>([])
+ const [meta, setMeta] = useState<PaginationMeta | undefined>()
+ const selectAllGenerationRef = useRef(0)
+ const selectAllSessionRef = useRef({ query: trimmedQuery, open })
+
+ if (
+ selectAllSessionRef.current.query !== trimmedQuery ||
+ (selectAllSessionRef.current.open && !open)
+ ) {
+ selectAllGenerationRef.current += 1
+ selectAllSessionRef.current = { query: trimmedQuery, open }
+ }
+
// Staging selection (ids picked in this session) + a label cache so the
// "selected" chips keep their text even after the search results change.
const [staged, setStaged] = useState<Map<string, T>>(new Map())
const alreadyIn = useMemo(() => new Set(selectedIds), [selectedIds])
const [submitting, setSubmitting] = useState(false)
+ const [selectingAll, setSelectingAll] = useState(false)
const { data, isFetching } = useQuery({
- queryKey: [queryKey, 'picker-search', trimmedQuery],
- queryFn: () => search(trimmedQuery),
+ queryKey: [queryKey, 'picker-search', trimmedQuery, page],
+ queryFn: () => search(trimmedQuery, page),
enabled: open,
staleTime: 30_000,
})
- const results = data?.data ?? []
+ useEffect(() => {
+ if (!data) return
+ setMeta(data.meta)
+ setCurrentPageResults(data.data)
+ setLoadedResults((previous) => {
+ if (page === 1) return data.data
+ const seen = new Set(previous.map((option) => option.id))
+ const appended = data.data.filter((option) => !seen.has(option.id))
+ return appended.length === 0 ? previous : [...previous, ...appended]
+ })
+ }, [data, page])
+
+ const results = loadedResults
+ const hasMore = meta?.next != null
+ const matchCount = meta?.count ?? results.length
+ const selectableOnPage = currentPageResults.filter((option) => !alreadyIn.has(option.id))
+ const allOnPageSelected =
+ selectableOnPage.length > 0 && selectableOnPage.every((option) => staged.has(option.id))
function toggle(option: T) {
if (alreadyIn.has(option.id)) return
@@ -100,6 +142,53 @@ export function ResourcePickerSheet<T extends PickerOption>({
})
}
+ function togglePageSelection() {
+ setStaged((prev) => {
+ const next = new Map(prev)
+ if (allOnPageSelected) {
+ for (const option of selectableOnPage) next.delete(option.id)
+ } else {
+ for (const option of selectableOnPage) next.set(option.id, option)
+ }
+ return next
+ })
+ }
+
+ async function selectAllMatching() {
+ if (matchCount === 0 || selectingAll) return
+ const generation = selectAllGenerationRef.current
+ setSelectingAll(true)
+ try {
+ const collected = new Map<string, T>()
+ let nextPage = 1
+ let lastMeta: PaginationMeta | undefined
+
+ while (true) {
+ const response = await search(trimmedQuery, nextPage)
+ if (generation !== selectAllGenerationRef.current) return
+ lastMeta = response.meta
+ for (const option of response.data) {
+ if (!alreadyIn.has(option.id)) collected.set(option.id, option)
+ }
+ if (!response.meta || nextPage >= response.meta.pages) break
+ nextPage += 1
+ }
+
+ if (generation !== selectAllGenerationRef.current) return
+
+ setStaged((prev) => {
+ const next = new Map(prev)
+ for (const [id, option] of collected) next.set(id, option)
+ return next
+ })
+ if (lastMeta) setMeta(lastMeta)
+ } catch (error) {
+ onConfirmError?.(error)
+ } finally {
+ setSelectingAll(false)
+ }
+ }
+
async function confirm() {
if (staged.size === 0) return
setSubmitting(true)
@@ -107,6 +196,10 @@ export function ResourcePickerSheet<T extends PickerOption>({
await onConfirm(Array.from(staged.keys()), Array.from(staged.values()))
setStaged(new Map())
setInput('')
+ setPage(1)
+ setLoadedResults([])
+ setCurrentPageResults([])
+ setMeta(undefined)
onOpenChange(false)
} catch (error) {
// The mutation reports its own error toast; swallow so the click handler
@@ -120,12 +213,20 @@ export function ResourcePickerSheet<T extends PickerOption>({
function handleOpenChange(next: boolean) {
if (!next) {
+ selectAllGenerationRef.current += 1
setStaged(new Map())
setInput('')
+ setPage(1)
+ setLoadedResults([])
+ setCurrentPageResults([])
+ setMeta(undefined)
}
onOpenChange(next)
}
+ const initialLoading = isFetching && results.length === 0
+ const loadingMore = isFetching && page > 1
+
return (
<Sheet open={open} onOpenChange={handleOpenChange}>
<SheetContent className="w-full gap-0 p-0 sm:max-w-lg">
@@ -137,7 +238,13 @@ export function ResourcePickerSheet<T extends PickerOption>({
<div className="border-b border-border p-4">
<SearchInput
value={input}
- onValueChange={setInput}
+ onValueChange={(value) => {
+ setInput(value)
+ setPage(1)
+ setLoadedResults([])
+ setCurrentPageResults([])
+ setMeta(undefined)
+ }}
// Enter has no action here; swallow it so it can't submit a host form.
onKeyDown={(e) => e.key === 'Enter' && e.preventDefault()}
placeholder={searchPlaceholder ?? t('admin.resource_picker.search_placeholder')}
@@ -151,7 +258,7 @@ export function ResourcePickerSheet<T extends PickerOption>({
</div>
<div className="min-h-0 flex-1 overflow-y-auto">
- {isFetching && results.length === 0 ? (
+ {initialLoading ? (
<div className="flex items-center justify-center py-10 text-muted-foreground">
<Loader2Icon className="size-5 animate-spin" />
</div>
@@ -160,44 +267,93 @@ export function ResourcePickerSheet<T extends PickerOption>({
{t('admin.resource_picker.empty')}
</p>
) : (
- <ul className="divide-y divide-border">
- {results.map((option) => {
- const inList = alreadyIn.has(option.id)
- const checked = inList || staged.has(option.id)
- const imageUrl = getOptionImageUrl?.(option)
- const subtitle = getOptionSubtitle?.(option)
- return (
- <li key={option.id}>
- <button
+ <>
+ {matchCount > 0 && (
+ <div className="flex items-center justify-between gap-3 border-b border-border px-4 py-2">
+ <button
+ type="button"
+ disabled={selectableOnPage.length === 0 || selectingAll}
+ onClick={togglePageSelection}
+ className="flex min-w-0 flex-1 items-center gap-3 text-left hover:bg-accent/50 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ <Checkbox
+ checked={allOnPageSelected}
+ disabled={selectableOnPage.length === 0 || selectingAll}
+ className="pointer-events-none"
+ />
+ <span className="truncate text-sm">
+ {t('admin.resource_picker.select_page', { count: selectableOnPage.length })}
+ </span>
+ </button>
+ {matchCount > 0 &&
+ (hasMore || !allOnPageSelected || matchCount > selectableOnPage.length) ? (
+ <Button
type="button"
- disabled={inList}
- onClick={() => toggle(option)}
- className="flex w-full items-center gap-3 px-4 py-2.5 text-left hover:bg-accent/50 disabled:cursor-not-allowed disabled:opacity-60"
+ variant="link"
+ size="sm"
+ className="h-auto shrink-0 px-0"
+ disabled={selectingAll}
+ onClick={selectAllMatching}
>
- <Checkbox
- checked={checked}
+ {selectingAll && <Loader2Icon className="size-3.5 animate-spin" />}
+ {t('admin.resource_picker.select_all_matching', { count: matchCount })}
+ </Button>
+ ) : null}
+ </div>
+ )}
+ <ul className="divide-y divide-border">
+ {results.map((option) => {
+ const inList = alreadyIn.has(option.id)
+ const checked = inList || staged.has(option.id)
+ const imageUrl = getOptionImageUrl?.(option)
+ const subtitle = getOptionSubtitle?.(option)
+ return (
+ <li key={option.id}>
+ <button
+ type="button"
disabled={inList}
- className="pointer-events-none"
- />
- {getOptionImageUrl && <Thumbnail src={imageUrl} size="sm" />}
- <span className="min-w-0 flex-1">
- <span className="block truncate text-sm">{getOptionLabel(option)}</span>
- {subtitle && (
- <span className="block truncate text-muted-foreground text-xs">
- {subtitle}
+ onClick={() => toggle(option)}
+ className="flex w-full items-center gap-3 px-4 py-2.5 text-left hover:bg-accent/50 disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ <Checkbox
+ checked={checked}
+ disabled={inList}
+ className="pointer-events-none"
+ />
+ {getOptionImageUrl && <Thumbnail src={imageUrl} size="sm" />}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm">{getOptionLabel(option)}</span>
+ {subtitle && (
+ <span className="block truncate text-muted-foreground text-xs">
+ {subtitle}
+ </span>
+ )}
+ </span>
+ {inList && (
+ <span className="shrink-0 text-muted-foreground text-xs">
+ {t('admin.resource_picker.already_added')}
</span>
)}
- </span>
- {inList && (
- <span className="shrink-0 text-muted-foreground text-xs">
- {t('admin.resource_picker.already_added')}
- </span>
- )}
- </button>
- </li>
- )
- })}
- </ul>
+ </button>
+ </li>
+ )
+ })}
+ </ul>
+ {hasMore && (
+ <div className="border-t border-border p-4">
+ <Button
+ type="button"
+ variant="outline"
+ className="w-full"
+ disabled={loadingMore}
+ onClick={() => setPage((current) => current + 1)}
+ >
+ {loadingMore && <Loader2Icon className="size-4 animate-spin" />}
+ {t('admin.resource_picker.load_more')}
+ </Button>
+ </div>
+ )}
+ </>
)}
</div>
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.json
index e6a2066135..2ce88db3d0 100644
--- a/packages/dashboard-core/src/locales/ar.json
+++ b/packages/dashboard-core/src/locales/ar.json
@@ -1221,7 +1221,12 @@
"add_count_other": "إضافة {{count}}",
"already_added": "مُضاف",
"empty": "لم يتم العثور على نتائج.",
+ "load_more": "تحميل المزيد",
"search_placeholder": "بحث…",
+ "select_all_matching_one": "تحديد كل {{count}} نتيجة مطابقة",
+ "select_all_matching_other": "تحديد كل {{count}} نتائج مطابقة",
+ "select_page_one": "تحديد {{count}} في هذه الصفحة",
+ "select_page_other": "تحديد كل {{count}} في هذه الصفحة",
"selected_count_one": "تم تحديد {{count}}",
"selected_count_other": "تم تحديد {{count}}",
"title": "إضافة منتجات"
diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.json
index eb15397857..fbe7e789fd 100644
--- a/packages/dashboard-core/src/locales/de.json
+++ b/packages/dashboard-core/src/locales/de.json
@@ -1221,7 +1221,12 @@
"add_count_other": "{{count}} hinzufügen",
"already_added": "Hinzugefügt",
"empty": "Keine Ergebnisse gefunden.",
+ "load_more": "Mehr laden",
"search_placeholder": "Suchen…",
+ "select_all_matching_one": "Alle {{count}} Treffer auswählen",
+ "select_all_matching_other": "Alle {{count}} Treffer auswählen",
+ "select_page_one": "{{count}} auf dieser Seite auswählen",
+ "select_page_other": "Alle {{count}} auf dieser Seite auswählen",
"selected_count_one": "{{count}} ausgewählt",
"selected_count_other": "{{count}} ausgewählt",
"title": "Produkte hinzufügen"
diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.json
index 85090239de..f296a02fae 100644
--- a/packages/dashboard-core/src/locales/en.json
+++ b/packages/dashboard-core/src/locales/en.json
@@ -1223,7 +1223,12 @@
"add_count_other": "Add {{count}}",
"already_added": "Added",
"empty": "No results found.",
+ "load_more": "Load more",
"search_placeholder": "Search…",
+ "select_all_matching_one": "Select all {{count}} match",
+ "select_all_matching_other": "Select all {{count}} matches",
+ "select_page_one": "Select {{count}} on this page",
+ "select_page_other": "Select all {{count}} on this page",
"selected_count_one": "{{count}} selected",
"selected_count_other": "{{count}} selected",
"title": "Add products"
diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.json
index 73e6ee3537..f1ac22f580 100644
--- a/packages/dashboard-core/src/locales/fr.json
+++ b/packages/dashboard-core/src/locales/fr.json
@@ -1221,7 +1221,12 @@
"add_count_other": "Ajouter {{count}}",
"already_added": "Ajouté",
"empty": "Aucun résultat trouvé.",
+ "load_more": "Charger plus",
"search_placeholder": "Rechercher…",
+ "select_all_matching_one": "Sélectionner le résultat correspondant {{count}}",
+ "select_all_matching_other": "Sélectionner les {{count}} résultats correspondants",
+ "select_page_one": "Sélectionner {{count}} élément sur cette page",
+ "select_page_other": "Sélectionner les {{count}} éléments sur cette page",
"selected_count_one": "{{count}} sélectionné",
"selected_count_other": "{{count}} sélectionnés",
"title": "Ajouter des produits"
diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.json
index 2abfe17e47..c56bcf9343 100644
--- a/packages/dashboard-core/src/locales/pl.json
+++ b/packages/dashboard-core/src/locales/pl.json
@@ -1235,7 +1235,14 @@
"add_count_other": "Dodaj {{count}}",
"already_added": "Dodano",
"empty": "Nie znaleziono wyników.",
+ "load_more": "Załaduj więcej",
"search_placeholder": "Szukaj…",
+ "select_all_matching_one": "Zaznacz {{count}} dopasowanie",
+ "select_all_matching_few": "Zaznacz wszystkie {{count}} dopasowania",
+ "select_all_matching_many": "Zaznacz wszystkie {{count}} dopasowań",
+ "select_all_matching_other": "Zaznacz wszystkie {{count}} dopasowania",
+ "select_page_one": "Zaznacz {{count}} na tej stronie",
+ "select_page_other": "Zaznacz wszystkie {{count}} na tej stronie",
"selected_count_one": "Wybrano {{count}}",
"selected_count_other": "Wybrano {{count}}",
"title": "Dodaj produkty"
diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.json
index 064fa579e5..1067f1db19 100644
--- a/packages/dashboard-core/src/locales/zh-CN.json
+++ b/packages/dashboard-core/src/locales/zh-CN.json
@@ -1221,7 +1221,12 @@
"add_count_other": "添加 {{count}} 个",
"already_added": "已添加",
"empty": "未找到结果。",
+ "load_more": "加载更多",
"search_placeholder": "搜索…",
+ "select_all_matching_one": "选择全部 {{count}} 个匹配项",
+ "select_all_matching_other": "选择全部 {{count}} 个匹配项",
+ "select_page_one": "选择本页 {{count}} 个",
+ "select_page_other": "选择本页全部 {{count}} 个",
"selected_count_one": "已选择 {{count}} 个",
"selected_count_other": "已选择 {{count}} 个",
"title": "添加商品"
diff --git a/packages/dashboard/e2e/catalogs.spec.ts b/packages/dashboard/e2e/catalogs.spec.ts
index e57cbe01f8..7fde15455b 100644
--- a/packages/dashboard/e2e/catalogs.spec.ts
+++ b/packages/dashboard/e2e/catalogs.spec.ts
@@ -1,5 +1,13 @@
import { expect, type Page, test } from '@playwright/test'
-import { FIXTURE_PROMO_PRODUCT, gotoIndex, login } from './helpers'
+import {
+ deleteCatalogPickerProducts,
+ FIXTURE_CATALOG_PICKER_PRODUCT_COUNT,
+ FIXTURE_CATALOG_PICKER_PRODUCT_PREFIX,
+ FIXTURE_PROMO_PRODUCT,
+ gotoIndex,
+ login,
+ seedCatalogPickerProducts,
+} from './helpers'
const CATALOGS_PATH = (storeId: string) => `/${storeId}/products/catalogs`
const CTA = /add catalog/i
@@ -356,4 +364,57 @@ test.describe('catalogs', () => {
await page.reload()
await expect(page.locator('#catalog-name')).toHaveValue(renamed, { timeout: 15_000 })
})
+
+ test('paginates the product picker and selects all matching search results', async ({ page }) => {
+ const creds = await login(page)
+ const productPrefix = `${FIXTURE_CATALOG_PICKER_PRODUCT_PREFIX} ${Date.now()}`
+ const seededProductIds = await seedCatalogPickerProducts(
+ page,
+ creds.store_id,
+ productPrefix,
+ creds.accessToken,
+ )
+
+ try {
+ await gotoIndex(page, CATALOGS_PATH(creds.store_id), CTA)
+
+ const name = `E2E Catalog Picker ${Date.now()}`
+ await createCatalog(page, name)
+
+ await page.getByRole('button', { name: /add products/i }).click()
+ const picker = page.getByRole('dialog')
+ await expect(picker.getByRole('heading', { name: /add products to catalog/i })).toBeVisible()
+
+ await picker.getByRole('searchbox').fill(productPrefix)
+
+ const productButtons = picker.getByRole('button', {
+ name: new RegExp(productPrefix, 'i'),
+ })
+ await expect(productButtons.first()).toBeVisible({ timeout: 15_000 })
+ await expect(productButtons).toHaveCount(25, { timeout: 15_000 })
+
+ await picker.getByRole('button', { name: /load more/i }).click()
+ await expect(productButtons).toHaveCount(FIXTURE_CATALOG_PICKER_PRODUCT_COUNT, {
+ timeout: 15_000,
+ })
+
+ await picker
+ .getByRole('button', {
+ name: new RegExp(`select all ${FIXTURE_CATALOG_PICKER_PRODUCT_COUNT} matches`, 'i'),
+ })
+ .click()
+ await picker
+ .getByRole('button', {
+ name: new RegExp(`^add ${FIXTURE_CATALOG_PICKER_PRODUCT_COUNT}$`, 'i'),
+ })
+ .click()
+ await expect(picker).toBeHidden({ timeout: 15_000 })
+
+ await expect(page.getByText(/^new$/i)).toHaveCount(FIXTURE_CATALOG_PICKER_PRODUCT_COUNT, {
+ timeout: 15_000,
+ })
+ } finally {
+ await deleteCatalogPickerProducts(page, creds.store_id, creds.accessToken, seededProductIds)
+ }
+ })
})
diff --git a/packages/dashboard/e2e/helpers.ts b/packages/dashboard/e2e/helpers.ts
index 2516b8c000..75188da3a9 100644
--- a/packages/dashboard/e2e/helpers.ts
+++ b/packages/dashboard/e2e/helpers.ts
@@ -12,6 +12,78 @@ export const FIXTURE_PROMO_TAXON = 'E2E Promo Category'
// permalink so it can never match an unrelated category.
export const FIXTURE_PROMO_TAXON_PERMALINK = 'e2e-promo-category'
export const FIXTURE_PROMO_PRODUCT = 'E2E Promo Product'
+/** Name prefix for catalog picker pagination E2E products; each run appends a timestamp. */
+export const FIXTURE_CATALOG_PICKER_PRODUCT_PREFIX = 'E2E Catalog Picker Product'
+
+/** Count used by the catalog picker pagination/select-all E2E. */
+export const FIXTURE_CATALOG_PICKER_PRODUCT_COUNT = 30
+
+/**
+ * Seed products for the catalog picker pagination test via the Admin API.
+ * Kept out of global-setup so the extra rows do not push bulk-operation
+ * fixtures off the products index first page (default limit 25, newest first).
+ */
+export async function seedCatalogPickerProducts(
+ page: Page,
+ storeId: string,
+ prefix: string,
+ accessToken: string,
+ count = FIXTURE_CATALOG_PICKER_PRODUCT_COUNT,
+): Promise<string[]> {
+ const headers = {
+ 'X-Spree-Store-Id': storeId,
+ Authorization: `Bearer ${accessToken}`,
+ }
+
+ const ids: string[] = []
+ try {
+ for (let index = 0; index < count; index += 1) {
+ const name = `${prefix} ${String(index + 1).padStart(2, '0')}`
+ const res = await page.request.post('/api/v3/admin/products', {
+ headers,
+ data: { name, status: 'active', price: 9.99 },
+ })
+ if (!res.ok()) {
+ throw new Error(
+ `Failed to seed catalog picker product "${name}": ${res.status()} ${await res.text()}`,
+ )
+ }
+ const body = (await res.json()) as { id: string }
+ ids.push(body.id)
+ }
+ } catch (error) {
+ if (ids.length > 0) {
+ await deleteCatalogPickerProducts(page, storeId, accessToken, ids).catch(() => undefined)
+ }
+ throw error
+ }
+
+ return ids
+}
+
+/** Remove picker seed rows so they do not push bulk fixtures off the products index. */
+export async function deleteCatalogPickerProducts(
+ page: Page,
+ storeId: string,
+ accessToken: string,
+ productIds: string[],
+) {
+ const headers = {
+ 'X-Spree-Store-Id': storeId,
+ Authorization: `Bearer ${accessToken}`,
+ }
+
+ await Promise.all(
+ productIds.map(async (id) => {
+ const res = await page.request.delete(`/api/v3/admin/products/${id}`, { headers })
+ if (!res.ok()) {
+ throw new Error(
+ `Failed to delete catalog picker product ${id}: ${res.status()} ${await res.text()}`,
+ )
+ }
+ }),
+ )
+}
// Active products used by products-bulk.spec.ts. Each test owns a disjoint
// pair so the serial suite doesn't cross-contaminate (status mutations on
// A/B don't shift the rows that the category/tag tests target). Kept here
@@ -56,6 +128,9 @@ export interface E2ECredentials {
store_name: string
}
+/** Credentials plus the JWT from the login response (Admin API Bearer auth). */
+export type E2ELoginSession = E2ECredentials & { accessToken: string }
+
let cached: E2ECredentials | null = null
export function getCredentials(): E2ECredentials {
@@ -79,7 +154,7 @@ export function getCredentials(): E2ECredentials {
*
* Not used by `auth.spec.ts` — that spec exercises the login form itself.
*/
-export async function login(page: Page): Promise<E2ECredentials> {
+export async function login(page: Page): Promise<E2ELoginSession> {
const creds = getCredentials()
const res = await page.request.post('/api/v3/admin/auth/login', {
data: { email: creds.admin_email, password: creds.admin_password },
@@ -87,6 +162,10 @@ export async function login(page: Page): Promise<E2ECredentials> {
if (!res.ok()) {
throw new Error(`API login failed with ${res.status()}: ${await res.text()}`)
}
+ const { token: accessToken } = (await res.json()) as { token: string }
+ if (!accessToken) {
+ throw new Error('API login response missing token')
+ }
await page.goto('/')
// Wait for the authenticated redirect to the store-scoped home — not just
// "left /login", which is trivially true at `/` while the boot refresh is
@@ -96,7 +175,7 @@ export async function login(page: Page): Promise<E2ECredentials> {
// page to /login. The redirect only fires after auth init settles, so it
// doubles as the refresh-complete barrier.
await expect(page).toHaveURL(new RegExp(`/${creds.store_id}`), { timeout: 15_000 })
- return creds
+ return { ...creds, accessToken }
}
/**
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 ff2c105978..65635df348 100644
--- a/packages/dashboard/src/components/spree/categories/category-products-card.tsx
+++ b/packages/dashboard/src/components/spree/categories/category-products-card.tsx
@@ -1,5 +1,9 @@
import { useParams } from '@tanstack/react-router'
-import { useCategoryProducts, useRepositionCategoryProduct } from '../../../hooks/use-categories'
+import {
+ listCategoryProductsPage,
+ useCategoryProducts,
+ useRepositionCategoryProduct,
+} from '../../../hooks/use-categories'
import { DeferredProductMembershipCard } from '../deferred-product-membership-card'
/**
@@ -20,6 +24,7 @@ export function CategoryProductsCard({ categoryId }: { categoryId: string }) {
parentId={categoryId}
storeId={storeId}
useProducts={useCategoryProducts}
+ listMembersPage={listCategoryProductsPage}
onReorder={(productId, new_position) => reposition.mutateAsync({ productId, new_position })}
translationNamespace="admin.categories"
/>
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 3fac9a64bf..ca7a799c2a 100644
--- a/packages/dashboard/src/components/spree/collections/collection-products-card.tsx
+++ b/packages/dashboard/src/components/spree/collections/collection-products-card.tsx
@@ -1,6 +1,7 @@
import { useParams } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import {
+ listCollectionProductsPage,
useCollectionProducts,
useRepositionCollectionProduct,
} from '../../../hooks/use-collections'
@@ -35,6 +36,7 @@ export function CollectionProductsCard({
storeId={storeId}
readOnly={automatic}
useProducts={useCollectionProducts}
+ listMembersPage={listCollectionProductsPage}
onReorder={(productId, new_position) => reposition.mutateAsync({ productId, new_position })}
translationNamespace="admin.collections"
description={automatic ? t('admin.collections.products.automatic_hint') : undefined}
diff --git a/packages/dashboard/src/components/spree/deferred-product-membership-card.tsx b/packages/dashboard/src/components/spree/deferred-product-membership-card.tsx
index 6495cb1a8d..d984c83a3d 100644
--- a/packages/dashboard/src/components/spree/deferred-product-membership-card.tsx
+++ b/packages/dashboard/src/components/spree/deferred-product-membership-card.tsx
@@ -12,6 +12,7 @@ import {
type ProductMembershipRow,
} from '@spree/dashboard-ui'
import { PlusIcon, Trash2Icon } from '@spree/dashboard-ui/icons'
+import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import { type ReactNode, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -23,6 +24,12 @@ export type ProductMembershipQuery = (
page?: number,
) => { data?: { data: Product[]; meta: PaginationMeta }; isLoading: boolean }
+/** Raw paginated membership fetch for picker exclusion across every list page. */
+export type ProductMembershipListPage = (
+ parentId: string,
+ page: number,
+) => Promise<{ data: Product[]; meta: PaginationMeta }>
+
/** Persists a drag-to-reorder. Resolve to commit, reject to roll back. */
export type ProductMembershipReorder = (productId: string, position: number) => Promise<unknown>
@@ -54,6 +61,7 @@ export function DeferredProductMembershipCard({
canEdit = true,
readOnly = false,
useProducts,
+ listMembersPage,
onReorder,
translationNamespace,
description,
@@ -67,6 +75,8 @@ export function DeferredProductMembershipCard({
/** True when membership is rule-derived and cannot be curated at all. */
readOnly?: boolean
useProducts: ProductMembershipQuery
+ /** When set, every persisted member id is excluded from the picker, not just the current list page. */
+ listMembersPage?: ProductMembershipListPage
onReorder?: ProductMembershipReorder
/** Locale namespace holding the `products.*` copy, e.g. `admin.catalogs`. */
translationNamespace: string
@@ -107,6 +117,27 @@ export function DeferredProductMembershipCard({
const [pickerOpen, setPickerOpen] = useState(false)
const [selected, setSelected] = useState<string[]>([])
+ const { data: allPersistedMemberIds } = useQuery({
+ queryKey: [translationNamespace, parentId, 'membership-picker-exclude-ids'],
+ queryFn: async () => {
+ if (!listMembersPage) return [] as string[]
+ const ids: string[] = []
+ let memberPage = 1
+ while (true) {
+ const response = await listMembersPage(parentId, memberPage)
+ ids.push(...response.data.map((product) => product.id))
+ const pages = response.meta?.pages ?? memberPage
+ if (!response.meta?.next || memberPage >= pages) break
+ memberPage += 1
+ }
+ return ids
+ },
+ enabled: pickerOpen && !!listMembersPage,
+ staleTime: 30_000,
+ })
+
+ const persistedMemberIds = allPersistedMemberIds ?? serverProducts.map((product) => product.id)
+
const pendingRemoveSet = useMemo(() => new Set(pendingRemoves), [pendingRemoves])
const pendingAddIds = useMemo(() => new Set(pendingAdds.map((p) => p.id)), [pendingAdds])
@@ -158,6 +189,14 @@ export function DeferredProductMembershipCard({
const curatable = canEdit && !readOnly
+ const pickerSelectedIds = useMemo(() => {
+ const ids = new Set(pendingAdds.map((product) => product.id))
+ for (const id of persistedMemberIds) {
+ if (!pendingRemoveSet.has(id)) ids.add(id)
+ }
+ return Array.from(ids)
+ }, [pendingAdds, persistedMemberIds, pendingRemoveSet])
+
// Only the persisted total — staged rows are marked in the list itself, and
// netting them into the count reads as wrong next to the visible rows.
const count = meta?.count ?? 0
@@ -256,7 +295,7 @@ export function DeferredProductMembershipCard({
// as "already in, not re-addable", so leaving them in would grey out
// a product the merchant just removed and leave the row's restore
// arrow as the only way back.
- selectedIds={rows.filter((row) => row.pending !== 'removed').map((row) => row.id)}
+ selectedIds={pickerSelectedIds}
onConfirm={(_, records) => {
// Re-picking a product staged for removal cancels that removal —
// it is still a member, so staging it as an addition too would
@@ -270,7 +309,16 @@ export function DeferredProductMembershipCard({
)
if (fresh.length > 0) staging.setAdds([...pendingAdds, ...fresh])
}}
- search={(q) => adminClient.products.list({ name_cont: q, limit: 25, sort: 'name' })}
+ search={(query, page) => {
+ const excludeIds = pickerSelectedIds
+ return adminClient.products.list({
+ ...(query ? { name_cont: query } : {}),
+ limit: 25,
+ page,
+ sort: 'name',
+ ...(excludeIds.length > 0 ? { id_not_in: excludeIds } : {}),
+ })
+ }}
getOptionLabel={(p) => p.name ?? p.id}
getOptionImageUrl={(p) => p.thumbnail_url}
getOptionSubtitle={(p) => p.slug ?? null}
diff --git a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
index 23c0be7388..475891ede1 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
+++ b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
@@ -68,6 +68,7 @@ import {
Textarea,
} from '@spree/dashboard-ui'
import {
+ listPriceListProductsPage,
useActivatePriceList,
useAddPriceListProducts,
useDeactivatePriceList,
@@ -267,6 +268,7 @@ export function PriceListForm({
storeId={storeId}
canEdit={canEdit}
useProducts={usePriceListProducts}
+ listMembersPage={listPriceListProductsPage}
translationNamespace="admin.pages.products.price_lists"
description={
(priceList.prices_count ?? 0) > 0
diff --git a/packages/dashboard/src/hooks/use-catalogs.ts b/packages/dashboard/src/hooks/use-catalogs.ts
index 77cfc8d92e..5fa31d2690 100644
--- a/packages/dashboard/src/hooks/use-catalogs.ts
+++ b/packages/dashboard/src/hooks/use-catalogs.ts
@@ -106,6 +106,11 @@ export function useCatalogProducts(catalogId: string | undefined, page = 1) {
})
}
+/** Paginated catalog membership fetch for picker exclusion (ids only). */
+export function listCatalogProductsPage(catalogId: string, page: number, limit = 100) {
+ return adminClient.catalogs.products.list(catalogId, { page, limit })
+}
+
export interface CatalogSavePayload {
/** Settings PATCH body; omitted when the form is clean. */
attributes?: CatalogParams
diff --git a/packages/dashboard/src/hooks/use-categories.ts b/packages/dashboard/src/hooks/use-categories.ts
index 8cf9c98f97..eaa16a72d1 100644
--- a/packages/dashboard/src/hooks/use-categories.ts
+++ b/packages/dashboard/src/hooks/use-categories.ts
@@ -103,7 +103,7 @@ const categoryProductsKey = (categoryId: string) => ['categories', categoryId, '
export function useCategoryProducts(categoryId: string | undefined, page = 1, limit = 25) {
return useQuery({
queryKey: useResourceKey('categories', categoryId ?? 'noop', 'products', `${page}:${limit}`),
- queryFn: () => adminClient.categories.products.list(categoryId as string, { page, limit }),
+ queryFn: () => listCategoryProductsPage(categoryId as string, page, limit),
enabled: !!categoryId,
// Keep the current page visible while the next one loads, so the table
// doesn't blank out between pages.
@@ -111,6 +111,11 @@ export function useCategoryProducts(categoryId: string | undefined, page = 1, li
})
}
+/** Paginated category membership fetch for picker exclusion. */
+export function listCategoryProductsPage(categoryId: string, page: number, limit = 100) {
+ return adminClient.categories.products.list(categoryId, { page, limit })
+}
+
/** Add one or many products to a category in a single request. */
export function useAddCategoryProducts(categoryId: string) {
return useResourceMutation<unknown, Error, string[]>({
diff --git a/packages/dashboard/src/hooks/use-collections.ts b/packages/dashboard/src/hooks/use-collections.ts
index 545ddc39c7..c892b0fd7b 100644
--- a/packages/dashboard/src/hooks/use-collections.ts
+++ b/packages/dashboard/src/hooks/use-collections.ts
@@ -105,7 +105,7 @@ const collectionProductsKey = (collectionId: string) =>
export function useCollectionProducts(collectionId: string | undefined, page = 1, limit = 25) {
return useQuery({
queryKey: useResourceKey('collections', collectionId ?? 'noop', 'products', `${page}:${limit}`),
- queryFn: () => adminClient.collections.products.list(collectionId as string, { page, limit }),
+ queryFn: () => listCollectionProductsPage(collectionId as string, page, limit),
enabled: !!collectionId,
// Keep the current page visible while the next one loads, so the table
// doesn't blank out between pages.
@@ -113,6 +113,11 @@ export function useCollectionProducts(collectionId: string | undefined, page = 1
})
}
+/** Paginated collection membership fetch for picker exclusion. */
+export function listCollectionProductsPage(collectionId: string, page: number, limit = 100) {
+ return adminClient.collections.products.list(collectionId, { page, limit })
+}
+
/** Add one or many products to a manual collection in a single request. */
export function useAddCollectionProducts(collectionId: string) {
return useResourceMutation<unknown, Error, string[]>({
diff --git a/packages/dashboard/src/hooks/use-price-lists.ts b/packages/dashboard/src/hooks/use-price-lists.ts
index c5a696b313..72bfe61791 100644
--- a/packages/dashboard/src/hooks/use-price-lists.ts
+++ b/packages/dashboard/src/hooks/use-price-lists.ts
@@ -81,12 +81,17 @@ export function useDeactivatePriceList(id: string) {
export function usePriceListProducts(priceListId: string | undefined, page = 1) {
return useQuery({
queryKey: useResourceKey('price-lists', priceListId ?? 'noop', 'products', `${page}`),
- queryFn: () => adminClient.priceLists.products.list(priceListId as string, { page, limit: 25 }),
+ queryFn: () => listPriceListProductsPage(priceListId as string, page),
enabled: !!priceListId,
placeholderData: (previous) => previous,
})
}
+/** Paginated price-list membership fetch for picker exclusion. */
+export function listPriceListProductsPage(priceListId: string, page: number, limit = 100) {
+ return adminClient.priceLists.products.list(priceListId, { page, limit })
+}
+
// Both flush mutations stay silent — they run inside the editor's Save,
// whose update mutation already reports the outcome.
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
index 30ea83544c..7261c23474 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
@@ -48,6 +48,7 @@ import {
} from '../../../../../components/spree/product-membership-staging'
import { ResourceDetailSkeleton } from '../../../../../components/spree/route-pending'
import {
+ listCatalogProductsPage,
useActivateCatalog,
useCatalog,
useCatalogProducts,
@@ -291,6 +292,7 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {
storeId={storeId}
canEdit={canEdit}
useProducts={useCatalogProducts}
+ listMembersPage={listCatalogProductsPage}
translationNamespace="admin.catalogs"
// What the agreement charges and what it demands, on the rows
// the merchant already curates. A product this catalog lists
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 c598c67942..b56f48776d 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
@@ -209,6 +209,17 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
ids = json_response['data'].map { |p| p['id'] }
expect(ids).to eq([other_product.prefixed_id])
end
+
+ it 'decodes prefixed IDs for q[id_not_in]' do
+ get :index,
+ params: { q: { id_not_in: [product.prefixed_id, third_product.prefixed_id] } },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ ids = json_response['data'].map { |p| p['id'] }
+ expect(ids).not_to include(product.prefixed_id, third_product.prefixed_id)
+ expect(ids).to include(other_product.prefixed_id)
+ end
end
context 'with q[search] (full-text search)' do