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: adding several products at once on purchase orders and transfers (#14628)

Damian Legawiec83f2365755b7
diff --git a/packages/dashboard-core/src/components/resource-picker-sheet.tsx b/packages/dashboard-core/src/components/resource-picker-sheet.tsx
index 541ef454c7..2b1a749dcb 100644
--- a/packages/dashboard-core/src/components/resource-picker-sheet.tsx
+++ b/packages/dashboard-core/src/components/resource-picker-sheet.tsx
@@ -12,8 +12,8 @@ import {
Thumbnail,
} from '@spree/dashboard-ui'
import { Loader2Icon } from '@spree/dashboard-ui/icons'
-import { useQuery } from '@tanstack/react-query'
-import { useDeferredValue, useEffect, useMemo, useRef, useState } from 'react'
+import { useInfiniteQuery } from '@tanstack/react-query'
+import { useDeferredValue, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
export interface PickerOption {
@@ -84,10 +84,7 @@ 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 [selectAllMeta, setSelectAllMeta] = useState<PaginationMeta | undefined>()
const selectAllGenerationRef = useRef(0)
const selectAllSessionRef = useRef({ query: trimmedQuery, open })
@@ -106,28 +103,39 @@ export function ResourcePickerSheet<T extends PickerOption>({
const [submitting, setSubmitting] = useState(false)
const [selectingAll, setSelectingAll] = useState(false)
- const { data, isFetching } = useQuery({
- queryKey: [queryKey, 'picker-search', trimmedQuery, page],
- queryFn: () => search(trimmedQuery, page),
+ // The accumulated pages live in the query cache rather than in local state.
+ // Mirroring them into state via an effect broke reopening the sheet: the
+ // cached page came back reference-identical, so the effect that filled the
+ // local list never re-ran and the sheet rendered "no results" over a cache
+ // that held plenty.
+ const { data, isFetching, isFetchingNextPage, fetchNextPage } = useInfiniteQuery({
+ queryKey: [queryKey, 'picker-search', trimmedQuery],
+ queryFn: ({ pageParam }) => search(trimmedQuery, pageParam),
+ initialPageParam: 1,
+ getNextPageParam: (lastPage, allPages) =>
+ lastPage.meta?.next != null ? allPages.length + 1 : undefined,
enabled: open,
staleTime: 30_000,
})
- 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 = useMemo(() => {
+ const seen = new Set<string>()
+ const flattened: T[] = []
+ for (const loadedPage of data?.pages ?? []) {
+ for (const option of loadedPage.data) {
+ if (seen.has(option.id)) continue
+ seen.add(option.id)
+ flattened.push(option)
+ }
+ }
+ return flattened
+ }, [data])
- const results = loadedResults
- const hasMore = meta?.next != null
+ const lastPage = data?.pages.at(-1)
+ const meta = selectAllMeta ?? lastPage?.meta
+ const hasMore = lastPage?.meta?.next != null
const matchCount = meta?.count ?? results.length
+ const currentPageResults = lastPage?.data ?? []
const selectableOnPage = currentPageResults.filter((option) => !alreadyIn.has(option.id))
const allOnPageSelected =
selectableOnPage.length > 0 && selectableOnPage.every((option) => staged.has(option.id))
@@ -181,7 +189,7 @@ export function ResourcePickerSheet<T extends PickerOption>({
for (const [id, option] of collected) next.set(id, option)
return next
})
- if (lastMeta) setMeta(lastMeta)
+ if (lastMeta) setSelectAllMeta(lastMeta)
} catch (error) {
onConfirmError?.(error)
} finally {
@@ -196,10 +204,7 @@ 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)
+ setSelectAllMeta(undefined)
onOpenChange(false)
} catch (error) {
// The mutation reports its own error toast; swallow so the click handler
@@ -216,16 +221,13 @@ export function ResourcePickerSheet<T extends PickerOption>({
selectAllGenerationRef.current += 1
setStaged(new Map())
setInput('')
- setPage(1)
- setLoadedResults([])
- setCurrentPageResults([])
- setMeta(undefined)
+ setSelectAllMeta(undefined)
}
onOpenChange(next)
}
const initialLoading = isFetching && results.length === 0
- const loadingMore = isFetching && page > 1
+ const loadingMore = isFetchingNextPage
return (
<Sheet open={open} onOpenChange={handleOpenChange}>
@@ -240,10 +242,7 @@ export function ResourcePickerSheet<T extends PickerOption>({
value={input}
onValueChange={(value) => {
setInput(value)
- setPage(1)
- setLoadedResults([])
- setCurrentPageResults([])
- setMeta(undefined)
+ setSelectAllMeta(undefined)
}}
// Enter has no action here; swallow it so it can't submit a host form.
onKeyDown={(e) => e.key === 'Enter' && e.preventDefault()}
@@ -346,7 +345,7 @@ export function ResourcePickerSheet<T extends PickerOption>({
variant="outline"
className="w-full"
disabled={loadingMore}
- onClick={() => setPage((current) => current + 1)}
+ onClick={() => fetchNextPage()}
>
{loadingMore && <Loader2Icon className="size-4 animate-spin" />}
{t('admin.resource_picker.load_more')}
diff --git a/packages/dashboard/e2e/inventory-line-picker.spec.ts b/packages/dashboard/e2e/inventory-line-picker.spec.ts
new file mode 100644
index 0000000000..7fcf0b4a2e
--- /dev/null
+++ b/packages/dashboard/e2e/inventory-line-picker.spec.ts
@@ -0,0 +1,193 @@
+import { expect, type Page, test } from '@playwright/test'
+import { deleteCatalogPickerProducts, login, seedCatalogPickerProducts } from './helpers'
+
+/**
+ * The "Add a product" sheet on a purchase order — the one surface where a
+ * merchant puts several SKUs on a document in one pass.
+ *
+ * Two things shipped broken here because no spec ever opened the sheet: a
+ * multi-select added only one of the products picked, and reopening the sheet
+ * showed an empty list over a cache that still held every result. Both are
+ * invisible to a spec that only checks the button exists, so these drive the
+ * sheet itself.
+ *
+ * The purchase order is the subject rather than the transfer because its
+ * picker offers the whole catalogue — a transfer filters by the warehouse it
+ * leaves from, which would narrow the list to the one stocked fixture SKU.
+ */
+
+/** Enough products to tell "added them all" apart from "added the last one". */
+const PICKED = 3
+
+test.describe('inventory line picker', () => {
+ let productIds: string[] = []
+ let prefix = ''
+
+ test.beforeEach(async ({ page }) => {
+ const creds = await login(page)
+ // Unique per test: the suite runs serially against one database, and a
+ // shared name would let an earlier run's rows widen the match count this
+ // spec asserts on.
+ prefix = `E2E PO Picker ${Date.now()}`
+ productIds = await seedCatalogPickerProducts(
+ page,
+ creds.store_id,
+ prefix,
+ creds.accessToken,
+ PICKED,
+ )
+ await page.goto(`/${creds.store_id}/purchase-orders/new`)
+ await expect(page.getByRole('heading', { name: /new purchase order/i })).toBeVisible({
+ timeout: 15_000,
+ })
+ })
+
+ test.afterEach(async ({ page }) => {
+ if (productIds.length === 0) return
+ const creds = await login(page)
+ await deleteCatalogPickerProducts(page, creds.store_id, creds.accessToken, productIds).catch(
+ () => undefined,
+ )
+ productIds = []
+ })
+
+ test('adds every product picked in one pass, not just one of them', async ({ page }) => {
+ await openPicker(page)
+ await searchFor(page, prefix)
+
+ // Check each row individually: this is the multi-select that used to
+ // collapse to a single line.
+ for (let index = 1; index <= PICKED; index += 1) {
+ await page.getByRole('button', { name: productName(prefix, index) }).click()
+ }
+
+ const sheet = page.getByRole('dialog')
+ await expect(sheet.getByText(`${PICKED} selected`)).toBeVisible()
+ await sheet.getByRole('button', { name: new RegExp(`^add ${PICKED}$`, 'i') }).click()
+
+ // Every picked product reaches the document, each as its own line.
+ await expect(sheet).toBeHidden()
+ for (let index = 1; index <= PICKED; index += 1) {
+ await expect(page.getByText(productName(prefix, index))).toBeVisible()
+ }
+ await expect(quantityInputs(page)).toHaveCount(PICKED)
+ })
+
+ test('still lists products when the sheet is reopened', async ({ page }) => {
+ // Deliberately unsearched, both times. Reopening on the *same* query is
+ // what broke: the cached page came back unchanged, so the sheet had
+ // nothing new to react to and showed "no results" over a full cache.
+ // Typing a different search on the second pass hides the bug, because a
+ // new query fetches afresh.
+ await openPicker(page)
+ await expect(anyResult(page).first()).toBeVisible({ timeout: 15_000 })
+
+ // Leave without picking anything — the close path is what used to empty
+ // the list for good.
+ await closeSheet(page)
+
+ await openPicker(page)
+
+ // The results come back rather than the sheet claiming there are none.
+ await expect(anyResult(page).first()).toBeVisible({ timeout: 15_000 })
+ await expect(page.getByText(/no results found/i)).toHaveCount(0)
+ })
+
+ test('still lists products when the sheet is reopened after a search', async ({ page }) => {
+ // The searched reopen. This path survived the bug on its own — retyping a
+ // query the cache has not seen refetches, which repopulated the list — so
+ // it is here to keep the search-and-reopen path working, not to reproduce
+ // the fault. The unsearched reopen above is the one that catches it.
+ await openPicker(page)
+ await searchFor(page, prefix)
+
+ await closeSheet(page)
+
+ await openPicker(page)
+ await searchFor(page, prefix)
+
+ await expect(page.getByText(/no results found/i)).toHaveCount(0)
+ for (let index = 1; index <= PICKED; index += 1) {
+ await expect(page.getByRole('button', { name: productName(prefix, index) })).toBeVisible()
+ }
+ })
+
+ test('reopening after adding offers the rest and keeps the lines already added', async ({
+ page,
+ }) => {
+ await openPicker(page)
+ await searchFor(page, prefix)
+ await page.getByRole('button', { name: productName(prefix, 1) }).click()
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^add 1$/i })
+ .click()
+ await expect(page.getByRole('dialog')).toBeHidden()
+
+ // Reopening after a confirm is the path a merchant takes to add a product
+ // they forgot; the sheet has to come back usable. Unsearched on purpose —
+ // the confirm path cleared the box, so this is the query the cache holds.
+ await openPicker(page)
+ await expect(anyResult(page).first()).toBeVisible({ timeout: 15_000 })
+ await searchFor(page, prefix)
+
+ // What is already on the order is offered as added rather than pickable.
+ await expect(
+ page.getByRole('button', { name: productName(prefix, 1) }).getByText(/^added$/i),
+ ).toBeVisible()
+
+ await page.getByRole('button', { name: productName(prefix, 2) }).click()
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^add 1$/i })
+ .click()
+
+ // The second product joins the first instead of replacing it.
+ await expect(page.getByRole('dialog')).toBeHidden()
+ await expect(page.getByText(productName(prefix, 1))).toBeVisible()
+ await expect(page.getByText(productName(prefix, 2))).toBeVisible()
+ await expect(quantityInputs(page)).toHaveCount(2)
+ })
+})
+
+/** Any row in the picker list, whatever the catalogue happens to hold. */
+function anyResult(page: Page) {
+ return page.getByRole('dialog').getByRole('button', { name: /SKU/ })
+}
+
+/** Leave the sheet without picking anything. */
+async function closeSheet(page: Page) {
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^cancel$/i })
+ .click()
+ await expect(page.getByRole('dialog')).toBeHidden()
+}
+
+function productName(prefix: string, index: number) {
+ return `${prefix} ${String(index).padStart(2, '0')}`
+}
+
+/** The order has no lines yet, so the empty state carries the only add button. */
+async function openPicker(page: Page) {
+ await page
+ .getByRole('button', { name: /add a product/i })
+ .first()
+ .click()
+ await expect(
+ page.getByRole('dialog').getByRole('heading', { name: /add products/i }),
+ ).toBeVisible()
+}
+
+/** Narrow to this spec's own fixtures — the catalogue holds other products. */
+async function searchFor(page: Page, query: string) {
+ await page.getByRole('dialog').getByRole('searchbox').fill(query)
+ await expect(page.getByRole('button', { name: productName(query, 1) })).toBeVisible({
+ timeout: 15_000,
+ })
+}
+
+/** One per line on the document; the quantity cell every line renders. */
+function quantityInputs(page: Page) {
+ return page.getByRole('spinbutton', { name: /^ordered$/i })
+}
diff --git a/packages/dashboard/src/components/spree/variant-line-editor.test.ts b/packages/dashboard/src/components/spree/variant-line-editor.test.ts
new file mode 100644
index 0000000000..d8705bb08d
--- /dev/null
+++ b/packages/dashboard/src/components/spree/variant-line-editor.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest'
+import { addVariantsToLines, type VariantLine } from './variant-line-editor'
+
+const variant = (id: string) => ({ id, sku: id.toUpperCase(), product_name: `Product ${id}` })
+
+describe('addVariantsToLines', () => {
+ it('adds every variant of a multi-select, not just the first', () => {
+ const picked = [variant('a'), variant('b'), variant('c')]
+
+ const lines = addVariantsToLines([], picked, false)
+
+ expect(lines.map((line) => line.variant.id)).toEqual(['a', 'b', 'c'])
+ expect(lines.every((line) => line.quantity === 1)).toBe(true)
+ })
+
+ it('keeps lines already on the document and appends the new ones', () => {
+ const existing: VariantLine[] = [{ variant: variant('a'), quantity: 4 }]
+
+ const lines = addVariantsToLines(existing, [variant('b'), variant('c')], false)
+
+ expect(lines.map((line) => line.variant.id)).toEqual(['a', 'b', 'c'])
+ expect(lines[0].quantity).toBe(4)
+ })
+
+ it('counts a re-picked variant up instead of duplicating its row', () => {
+ const existing: VariantLine[] = [{ variant: variant('a'), quantity: 2 }]
+
+ const lines = addVariantsToLines(existing, [variant('a'), variant('b')], false)
+
+ expect(lines).toHaveLength(2)
+ expect(lines[0].quantity).toBe(3)
+ })
+
+ it('counts a variant repeated inside one batch onto a single line', () => {
+ const lines = addVariantsToLines([], [variant('a'), variant('b'), variant('a')], false)
+
+ expect(lines.map((line) => line.variant.id)).toEqual(['a', 'b'])
+ expect(lines[0].quantity).toBe(2)
+ })
+
+ it('seeds a cost only where the document has one', () => {
+ expect(addVariantsToLines([], [variant('a')], true)[0].unitCost).toBe('0.00')
+ expect(addVariantsToLines([], [variant('a')], false)[0].unitCost).toBeUndefined()
+ })
+
+ it('leaves the lines untouched when nothing was picked', () => {
+ const existing: VariantLine[] = [{ variant: variant('a'), quantity: 1 }]
+ expect(addVariantsToLines(existing, [], false)).toBe(existing)
+ })
+})
diff --git a/packages/dashboard/src/components/spree/variant-line-editor.tsx b/packages/dashboard/src/components/spree/variant-line-editor.tsx
index a03363a596..d03144bae8 100644
--- a/packages/dashboard/src/components/spree/variant-line-editor.tsx
+++ b/packages/dashboard/src/components/spree/variant-line-editor.tsx
@@ -46,6 +46,37 @@ export interface VariantLine {
unitCost?: string
}
+/**
+ * Folds a whole picked batch into the existing lines, in one pass.
+ *
+ * Adding a batch one variant at a time reads the same `lines` for every call,
+ * so only the last pick of a multi-select survives. Taking the batch whole is
+ * what makes picking several products at once add several lines.
+ */
+export function addVariantsToLines(
+ lines: VariantLine[],
+ variants: VariantLineVariant[],
+ withCost: boolean,
+): VariantLine[] {
+ if (variants.length === 0) return lines
+ const next = [...lines]
+ // Indexed rather than scanned per variant: "select all matching" pages
+ // through the whole catalogue, so a batch can be thousands of variants long
+ // and a scan inside the loop would stall the page.
+ const indexByVariantId = new Map(next.map((line, index) => [line.variant.id, index]))
+
+ for (const variant of variants) {
+ const index = indexByVariantId.get(variant.id)
+ if (index === undefined) {
+ next.push({ variant, quantity: 1, unitCost: withCost ? '0.00' : undefined })
+ indexByVariantId.set(variant.id, next.length - 1)
+ } else {
+ next[index] = { ...next[index], quantity: next[index].quantity + 1 }
+ }
+ }
+ return next
+}
+
/**
* Picks SKUs and their quantities for a draft inventory document.
*
@@ -91,19 +122,6 @@ export function VariantLineEditor({
// refused later, per line, when the transfer is marked in transit.
const locked = !!requireStockLocation && !stockLocationId
- function addVariant(variant: Variant) {
- const existing = lines.find((line) => line.variant.id === variant.id)
- if (existing) {
- onChange(
- lines.map((line) =>
- line.variant.id === variant.id ? { ...line, quantity: line.quantity + 1 } : line,
- ),
- )
- return
- }
- onChange([...lines, { variant, quantity: 1, unitCost: withCost ? '0.00' : undefined }])
- }
-
function update(variantId: string, patch: Partial<VariantLine>) {
onChange(lines.map((line) => (line.variant.id === variantId ? { ...line, ...patch } : line)))
}
@@ -124,9 +142,7 @@ export function VariantLineEditor({
// sources, and a cached result would offer the wrong shelf's SKUs.
queryKey={`inventory-line-variant-picker:${stockLocationId ?? 'any'}`}
selectedIds={lines.map((line) => line.variant.id)}
- onConfirm={(_ids, variants) => {
- for (const variant of variants) addVariant(variant)
- }}
+ onConfirm={(_ids, variants) => onChange(addVariantsToLines(lines, variants, withCost))}
search={async (query, page) =>
adminClient.variants.list({
...(query ? { search: query } : {}),